{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: CODE_OF_CONDUCT.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nThe Adversarial Robustness Toolbox (ART) is dedicated to providing a harassment-free experience for everyone, regardless of gender, gender identity and expression, sexual orientation, disability, physical appearance, body size, age, race, or religion. We do not tolerate harassment of participants in any form.\n\nThis code of conduct applies to all Adversarial Robustness Toolbox spaces, both online and off. Anyone who violates this code of conduct may be sanctioned or expelled from these spaces at the discretion of the Trusted-AI team.\n\nWe may add additional rules over time, which will be made clearly available to participants. Participants are responsible for knowing and abiding by these rules.\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: CONTRIBUTING.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Contributing to the Adversarial Robustness Toolbox\n\n## Adding new Features\nAdding new features, improving documentation, fixing bugs, or writing tutorials are all examples of helpful \ncontributions. Furthermore, if you are publishing a new attack or defense, we strongly encourage you to add it to the \nAdversarial Robustness Toolbox so that others may evaluate it fairly in their own work.\n\nBug fixes can be initiated through GitHub pull requests. When making code contributions to the Adversarial Robustness \nToolbox, we ask that you follow the `PEP 8` coding standard and that you provide unit tests for the new features.\n\nContributions of new features must include unit test covering at least 80% of the new statements.\n\n## Validating Git Commits\nThis project uses [DCO](https://developercertificate.org/). Be sure to sign off your commits using the `-s` flag or \nadding `Signed-off-By: Name` in the commit message. Example:\n```bash\ngit commit -s -m 'Informative commit message'\n```\n\n## Unit tests\nWhen submitting additional unit tests for ART, in order to keep the code base maintainable, please make sure each unit \ntest can run ideally in a few seconds.\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: MAINTAINERS.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Maintainers Guide\n\nFollowing is the current list of maintainers on this project\n\nThe maintainers are listed in alphabetical order of their Github username.\n- Beat Buesser ([beat-buesser](https://github.com/beat-buesser))\n- Ian Molloy ([imolloy](https://github.com/imolloy))\n- Mathieu Sinn ([mathsinn](https://github.com/mathsinn))\n- Ngoc Minh Tran ([minhitbk](https://github.com/minhitbk))\n- Irina Nicolae ([ririnicolae](https://github.com/ririnicolae))\n\n## Methodology\n\nThe quality of the master branch should never be compromised.\n\nThe remainder of this document details how to merge pull requests to the\nrepositories.\n\n## Merge Approval\n\nThe project maintainers use LGTM (Looks Good To Me) in comments on the pull\nrequest to indicate acceptance prior to merging. A change requires LGTMs from\ntwo project maintainers. If the code is written by a maintainer, the change\nonly requires one additional LGTM.\n\n## Reviewing Pull Requests\n\nWe recommend reviewing pull requests directly within GitHub. This allows a\npublic commentary on changes, providing transparency for all users. When\nproviding feedback be civil, courteous, and kind. Disagreement is fine, so long\nas the discourse is carried out politely. If we see a record of uncivil or\nabusive comments, we will revoke your commit privileges and invite you to leave\nthe project.\n\nDuring your review, consider the following points:\n\n### Does the change have positive impact?\n\nSome proposed changes may not represent a positive impact to the project. Ask\nwhether or not the change will make understanding the code easier, or if it\ncould simply be a personal preference on the part of the author (see\n[bikeshedding](https://en.wiktionary.org/wiki/bikeshedding)).\n\nPull requests that do not have a clear positive impact should be closed without\nmerging.\n\n### Do the changes make sense?\n\nIf you do not understand what the changes are or what they accomplish, ask the\nauthor for clarification. Ask the author to add comments and/or clarify test\ncase names to make the intentions clear.\n\nAt times, such clarification will reveal that the author may not be using the\ncode correctly, or is unaware of features that accommodate their needs. If you\nfeel this is the case, work up a code sample that would address the pull\nrequest for them, and feel free to close the pull request once they confirm.\n\n### Does the change introduce a new feature?\n\nFor any given pull request, ask yourself \"is this a new feature?\" If so, does\nthe pull request (or associated issue) contain narrative indicating the need\nfor the feature? If not, ask them to provide that information.\n\nAre new unit tests in place that test all new behaviors introduced? If not, do\nnot merge the feature until they are! Is documentation in place for the new\nfeature? (See the documentation guidelines). If not, do not merge the feature\nuntil it is! Is the feature necessary for general use cases? Try and keep the\nscope of any given component narrow. If a proposed feature does not fit that\nscope, recommend to the user that they maintain the feature on their own, and\nclose the request. You may also recommend that they see if the feature gains\ntraction among other users, and suggest they re-submit when they can show such\nsupport.\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: PULL_REQUEST_TEMPLATE.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Description\n\nPlease include a summary of the change, motivation and which issue is fixed. Any dependencies changes should also be included.\n\nFixes # (issue)\n\n## Type of change\n\nPlease check all relevant options.\n\n- [ ] Improvement (non-breaking)\n- [ ] Bug fix (non-breaking)\n- [ ] New feature (non-breaking)\n- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)\n- [ ] This change requires a documentation update\n\n# Testing\n\nPlease describe the tests that you ran to verify your changes. Consider listing any relevant details of your test configuration.\n\n- [ ] Test A\n- [ ] Test B\n\n**Test Configuration**:\n- OS\n- Python version\n- ART version or commit number\n- TensorFlow / Keras / PyTorch version\n\n# Checklist\n\n- [ ] My code follows the style guidelines of this project\n- [ ] I have performed a self-review of my own code\n- [ ] I have commented my code\n- [ ] I have made corresponding changes to the documentation\n- [ ] My changes generate no new warnings\n- [ ] I have added tests that prove my fix is effective or that my feature works\n- [ ] New and existing unit tests pass locally with my changes\n- [ ] My changes have been tested using both CPU and GPU devices\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: README-cn.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Adversarial Robustness Toolbox (ART) v1.20\n

\n \n

\n
\n\n![CodeQL](https://github.com/Trusted-AI/adversarial-robustness-toolbox/workflows/CodeQL/badge.svg)\n[![Documentation Status](https://readthedocs.org/projects/adversarial-robustness-toolbox/badge/?version=latest)](http://adversarial-robustness-toolbox.readthedocs.io/en/latest/?badge=latest)\n[![PyPI](https://badge.fury.io/py/adversarial-robustness-toolbox.svg)](https://badge.fury.io/py/adversarial-robustness-toolbox)\n[![codecov](https://codecov.io/gh/Trusted-AI/adversarial-robustness-toolbox/branch/main/graph/badge.svg)](https://codecov.io/gh/Trusted-AI/adversarial-robustness-toolbox)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/adversarial-robustness-toolbox)](https://pypi.org/project/adversarial-robustness-toolbox/)\n[![slack-img](https://img.shields.io/badge/chat-on%20slack-yellow.svg)](https://ibm-art.slack.com/)\n[![Downloads](https://static.pepy.tech/badge/adversarial-robustness-toolbox)](https://pepy.tech/project/adversarial-robustness-toolbox)\n[![Downloads](https://static.pepy.tech/badge/adversarial-robustness-toolbox/month)](https://pepy.tech/project/adversarial-robustness-toolbox)\n[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/5090/badge)](https://bestpractices.coreinfrastructure.org/projects/5090)\n\n
\n \n \n \n \"Fallback\n \n
\n
\n\n\u5bf9\u6297\u6027\u9c81\u68d2\u6027\u5de5\u5177\u96c6\uff08ART\uff09\u662f\u7528\u4e8e\u673a\u5668\u5b66\u4e60\u5b89\u5168\u6027\u7684Python\u5e93\u3002ART \u7531\n[Linux Foundation AI & Data Foundation](https://lfaidata.foundation) (LF AI & Data)\u3002 ART\u63d0\u4f9b\u7684\u5de5\u5177\u53ef\n\u5e2e\u52a9\u5f00\u53d1\u4eba\u5458\u548c\u7814\u7a76\u4eba\u5458\u9488\u5bf9\u4ee5\u4e0b\u65b9\u9762\u634d\u536b\u548c\u8bc4\u4f30\u673a\u5668\u5b66\u4e60\u6a21\u578b\u548c\u5e94\u7528\u7a0b\u5e8f\uff1a\n\u9003\u9038\uff0c\u6570\u636e\u6c61\u67d3\uff0c\u6a21\u578b\u63d0\u53d6\u548c\u63a8\u65ad\u7684\u5bf9\u6297\u6027\u5a01\u80c1\u3002ART\u652f\u6301\u6240\u6709\u6d41\u884c\u7684\u673a\u5668\u5b66\u4e60\u6846\u67b6\n\uff08TensorFlow\uff0cKeras\uff0cPyTorch\uff0cscikit-learn\uff0cXGBoost\uff0cLightGBM\uff0cCatBoost\uff0cGPy\u7b49\uff09\uff0c\u6240\u6709\u6570\u636e\u7c7b\u578b\n\uff08\u56fe\u50cf\uff0c\u8868\u683c\uff0c\u97f3\u9891\uff0c\u89c6\u9891\u7b49\uff09\u548c\u673a\u5668\u5b66\u4e60\u4efb\u52a1\uff08\u5206\u7c7b\uff0c\u7269\u4f53\u68c0\u6d4b\uff0c\u8bed\u97f3\u8bc6\u522b\uff0c\n\u751f\u6210\u6a21\u578b\uff0c\u8ba4\u8bc1\u7b49\uff09\u3002\n\n## Adversarial Threats\n\n
\n \n \n \n \"Fallback\n \n
\n\n

\n \n

\n
\n\n## ART for Red and Blue Teams (selection)\n\n
\n \n \n \n \"Fallback\n \n
\n
\n\n## \u5b66\u5230\u66f4\u591a\n\n| **[\u5f00\u59cb\u4f7f\u7528][get-started]** | **[\u6587\u732e\u8d44\u6599][documentation]** | **[\u8d21\u732e][contributing]** |\n|-------------------------------------|-------------------------------|-----------------------------------|\n| - [\u5b89\u88c5][installation]
- [\u4f8b\u5b50](examples/README.md)
- [Notebooks](notebooks/README.md) | - [\u653b\u51fb][attacks]
- [\u9632\u5fa1][defences]
- [\u8bc4\u4f30\u5668][estimators]
- [\u6307\u6807][metrics]
- [\u6280\u672f\u6587\u6863](https://adversarial-robustness-toolbox.readthedocs.io) | - [Slack](https://ibm-art.slack.com), [\u9080\u8bf7\u51fd](https://join.slack.com/t/ibm-art/shared_invite/enQtMzkyOTkyODE4NzM4LTA4NGQ1OTMxMzFmY2Q1MzE1NWI2MmEzN2FjNGNjOGVlODVkZDE0MjA1NTA4OGVkMjVkNmQ4MTY1NmMyOGM5YTg)
- [\u8d21\u732e](CONTRIBUTING.md)
- [\u8def\u7ebf\u56fe][roadmap]
- [\u5f15\u7528][citing] |\n\n[get-started]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Get-Started\n[attacks]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Attacks\n[defences]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Defences\n[estimators]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Estimators\n[metrics]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Metrics\n[contributing]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Contributing\n[documentation]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Documentation\n[installation]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Get-Started#setup\n[roadmap]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Roadmap\n[citing]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Contributing#citing-art\n\n\u8be5\u5e93\u6b63\u5728\u4e0d\u65ad\u5f00\u53d1\u4e2d\u3002\u6b22\u8fce\u53cd\u9988\uff0c\u9519\u8bef\u62a5\u544a\u548c\u8d21\u732e\uff01\n\n# \u81f4\u8c22\n\n\u672c\u6750\u6599\u90e8\u5206\u57fa\u4e8e\u56fd\u9632\u9ad8\u7ea7\u7814\u7a76\u8ba1\u5212\u5c40\uff08DARPA\uff09\u652f\u6301\u7684\u5de5\u4f5c\uff0c\u5408\u540c\u7f16\u53f7HR001120C0013\u3002\n\u672c\u6750\u6599\u4e2d\u8868\u8fbe\u7684\u4efb\u4f55\u610f\u89c1\uff0c\u53d1\u73b0\u548c\u7ed3\u8bba\u6216\u5efa\u8bae\u5747\u4e3a\u4f5c\u8005\u7684\u89c2\u70b9\uff0c\u5e76\u4e0d\u4e00\u5b9a\u53cd\u6620\u56fd\u9632\u9ad8\u7ea7\u7814\u7a76\u8ba1\u5212\u5c40\uff08DARPA\uff09\u7684\u89c2\u70b9\u3002\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Adversarial Robustness Toolbox (ART) v1.20\n

\n \n

\n
\n\n![CodeQL](https://github.com/Trusted-AI/adversarial-robustness-toolbox/workflows/CodeQL/badge.svg)\n[![Documentation Status](https://readthedocs.org/projects/adversarial-robustness-toolbox/badge/?version=latest)](http://adversarial-robustness-toolbox.readthedocs.io/en/latest/?badge=latest)\n[![PyPI](https://badge.fury.io/py/adversarial-robustness-toolbox.svg)](https://badge.fury.io/py/adversarial-robustness-toolbox)\n[![codecov](https://codecov.io/gh/Trusted-AI/adversarial-robustness-toolbox/branch/main/graph/badge.svg)](https://codecov.io/gh/Trusted-AI/adversarial-robustness-toolbox)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/adversarial-robustness-toolbox)](https://pypi.org/project/adversarial-robustness-toolbox/)\n[![slack-img](https://img.shields.io/badge/chat-on%20slack-yellow.svg)](https://ibm-art.slack.com/)\n[![Downloads](https://static.pepy.tech/badge/adversarial-robustness-toolbox)](https://pepy.tech/project/adversarial-robustness-toolbox)\n[![Downloads](https://static.pepy.tech/badge/adversarial-robustness-toolbox/month)](https://pepy.tech/project/adversarial-robustness-toolbox)\n[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/5090/badge)](https://bestpractices.coreinfrastructure.org/projects/5090)\n\n[\u4e2d\u6587README\u8bf7\u6309\u6b64\u5904](README-cn.md)\n\n
\n \n \n \n \"Fallback\n \n
\n
\n\nAdversarial Robustness Toolbox (ART) is a Python library for Machine Learning Security. ART is hosted by the \n[Linux Foundation AI & Data Foundation](https://lfaidata.foundation) (LF AI & Data). ART provides tools that enable\ndevelopers and researchers to defend and evaluate Machine Learning models and applications against the\nadversarial threats of Evasion, Poisoning, Extraction, and Inference. ART supports all popular machine learning frameworks\n(TensorFlow, Keras, PyTorch, scikit-learn, XGBoost, LightGBM, CatBoost, GPy, etc.), all data types\n(images, tables, audio, video, etc.) and machine learning tasks (classification, object detection, speech recognition,\ngeneration, certification, etc.).\n\n## Adversarial Threats\n\n
\n \n \n \n \"Fallback\n \n
\n\n

\n \n

\n
\n\n## ART for Red and Blue Teams (selection)\n\n
\n \n \n \n \"Fallback\n \n
\n
\n\n## Learn more\n\n| **[Get Started][get-started]** | **[Documentation][documentation]** | **[Contributing][contributing]** |\n|-------------------------------------|-------------------------------|-----------------------------------|\n| - [Installation][installation]
- [Examples](examples/README.md)
- [Notebooks](notebooks/README.md) | - [Attacks][attacks]
- [Defences][defences]
- [Estimators][estimators]
- [Metrics][metrics]
- [Technical Documentation](https://adversarial-robustness-toolbox.readthedocs.io) | - [Slack](https://ibm-art.slack.com), [Invitation](https://join.slack.com/t/ibm-art/shared_invite/enQtMzkyOTkyODE4NzM4LTA4NGQ1OTMxMzFmY2Q1MzE1NWI2MmEzN2FjNGNjOGVlODVkZDE0MjA1NTA4OGVkMjVkNmQ4MTY1NmMyOGM5YTg)
- [Contributing](CONTRIBUTING.md)
- [Roadmap][roadmap]
- [Citing][citing] |\n\n[get-started]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Get-Started\n[attacks]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Attacks\n[defences]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Defences\n[estimators]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Estimators\n[metrics]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/ART-Metrics\n[contributing]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Contributing\n[documentation]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Documentation\n[installation]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Get-Started#setup\n[roadmap]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Roadmap\n[citing]: https://github.com/Trusted-AI/adversarial-robustness-toolbox/wiki/Contributing#citing-art\n\nThe library is under continuous development. Feedback, bug reports and contributions are very welcome!\n\n# Acknowledgment\nThis material is partially based upon work supported by the Defense Advanced Research Projects Agency (DARPA) under\nContract No. HR001120C0013. Any opinions, findings and conclusions or recommendations expressed in this material are\nthose of the author(s) and do not necessarily reflect the views of the Defense Advanced Research Projects Agency (DARPA).\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: SECURITY.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Security Policy\n\n## Reporting a Vulnerability\n(Following https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md)\n\nPlease email reports about any security related issues you find to info@lfai.foundation. This mail is delivered to a small team maintaining the Trusted-AI projects. Your email will be acknowledged within a few business day, and you'll receive a more detailed response to your email within 7 days indicating the next steps in handling your report.\n\nPlease use a descriptive subject line for your report email. After the initial reply to your report, the team will endeavor to keep you informed of the progress being made towards a fix and announcement.\n\nIn addition, please include the following information along with your report:\n\nYour name and affiliation (if any).\nA description of the technical details of the vulnerabilities. It is very important to let us know how we can reproduce your findings.\nAn explanation who can exploit this vulnerability, and what they gain when doing so -- write an attack scenario. This will help us evaluate your report quickly, especially if the issue is complex.\nWhether this vulnerability public or known to third parties. If it is, please provide details.\nIf you believe that an existing (public) issue is security-related, please send an email to info@lfai.foundation. The email should include the issue ID and a short description of why it should be handled according to this security policy.\n\nWe apply the following disclosure process:\n\nWhen a report is received, we confirm the issue and determine its severity.\nIf we know of specific third-party services or software based on ART that require mitigation before publication, those projects will be notified.\nAn advisory is prepared (but not published) which details the problem and steps for mitigation.\nThe vulnerability is fixed and potential workarounds are identified.\nWherever possible, the fix is also prepared for the branches corresponding to all releases of ART at most one year old. We will attempt to commit these fixes as soon as possible, and as close together as possible.\n\nPatch releases are published for all fixed released versions and the advisory is published.\n\nNote that each version of ART is supported for only 1 year after the release.\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport importlib\nimport json\nimport logging\nimport os\nimport shutil\nimport tempfile\nfrom typing import Dict, List, TYPE_CHECKING, Union\nimport warnings\n\nimport numpy as np\nimport pytest\nimport requests\n\nfrom art.data_generators import (\n KerasDataGenerator,\n PyTorchDataGenerator,\n TensorFlowV2DataGenerator,\n)\nfrom art.defences.preprocessor import FeatureSqueezing, JpegCompression, SpatialSmoothing\nfrom art.estimators.classification import KerasClassifier\nfrom tests.utils import (\n ARTTestFixtureNotImplemented,\n get_attack_classifier_pt,\n get_image_classifier_kr,\n get_image_classifier_kr_functional,\n get_image_classifier_kr_tf,\n get_image_classifier_kr_tf_functional,\n get_image_classifier_kr_tf_with_wildcard,\n get_image_classifier_pt,\n get_image_classifier_pt_functional,\n get_image_classifier_tf,\n get_image_classifier_hf,\n get_image_gan_tf_v2,\n get_image_generator_tf_v2,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_scikit_list,\n get_tabular_classifier_tf,\n load_dataset,\n master_seed,\n)\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\ndeep_learning_frameworks = [\n \"keras\", \"tensorflow2\", \"pytorch\", \"kerastf\", \"jax\", \"huggingface\",\n]\nnon_deep_learning_frameworks = [\"scikitlearn\"]\n\nart_supported_frameworks = []\nart_supported_frameworks.extend(deep_learning_frameworks)\nart_supported_frameworks.extend(non_deep_learning_frameworks)\n\nmaster_seed(1234)\n\n\ndef get_default_framework():\n import tensorflow as tf\n\n if tf.__version__[0] == \"2\":\n default_framework = \"tensorflow2\"\n else:\n raise ValueError(\"TensorFlow version not recognised.\")\n\n return default_framework\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--framework\",\n action=\"store\",\n default=get_default_framework(),\n help=\"ART tests allow you to specify which framework to use. The default framework used is `tensorflow`. \"\n \"Other options available are {0}\".format(art_supported_frameworks),\n )\n\n\n@pytest.fixture\ndef image_dl_estimator_defended(framework):\n def _image_dl_estimator_defended(one_classifier=False, **kwargs):\n sess = None\n classifier = None\n\n clip_values = (0, 1)\n fs = FeatureSqueezing(bit_depth=2, clip_values=clip_values)\n\n defenses = []\n if kwargs.get(\"defenses\") is None:\n defenses.append(fs)\n else:\n if \"FeatureSqueezing\" in kwargs.get(\"defenses\"):\n defenses.append(fs)\n if \"JpegCompression\" in kwargs.get(\"defenses\"):\n defenses.append(JpegCompression(clip_values=clip_values, apply_predict=True))\n if \"SpatialSmoothing\" in kwargs.get(\"defenses\"):\n defenses.append(SpatialSmoothing())\n del kwargs[\"defenses\"]\n\n if framework == \"tensorflow2\":\n classifier, _ = get_image_classifier_tf(**kwargs)\n\n if framework == \"keras\":\n classifier = get_image_classifier_kr(**kwargs)\n\n if framework == \"kerastf\":\n classifier = get_image_classifier_kr_tf(**kwargs)\n\n if framework == \"pytorch\":\n classifier = get_image_classifier_pt(**kwargs)\n for i, defense in enumerate(defenses):\n if \"channels_first\" in defense.params:\n defenses[i].channels_first = classifier.channels_first\n\n if classifier is not None:\n classifier.set_params(preprocessing_defences=defenses)\n else:\n raise ARTTestFixtureNotImplemented(\n \"no defended image estimator\", image_dl_estimator_defended.__name__, framework, {\"defenses\": defenses}\n )\n\n return classifier, sess\n\n return _image_dl_estimator_defended\n\n\n@pytest.fixture(scope=\"function\")\ndef image_dl_estimator_for_attack(framework, image_dl_estimator, image_dl_estimator_defended):\n def _image_dl_estimator_for_attack(attack, defended=False, **kwargs):\n if defended:\n potential_classifier, _ = image_dl_estimator_defended(**kwargs)\n else:\n potential_classifier, _ = image_dl_estimator(**kwargs)\n\n classifier_list = [potential_classifier]\n classifier_tested = [\n potential_classifier\n for potential_classifier in classifier_list\n if all(t in type(potential_classifier).__mro__ for t in attack._estimator_requirements)\n ]\n\n if len(classifier_tested) == 0:\n raise ARTTestFixtureNotImplemented(\n \"no estimator available\", image_dl_estimator_for_attack.__name__, framework, {\"attack\": attack}\n )\n return classifier_tested[0]\n\n return _image_dl_estimator_for_attack\n\n\n@pytest.fixture\ndef estimator_for_attack(framework):\n # TODO DO NOT USE THIS FIXTURE this needs to be refactored into image_dl_estimator_for_attack\n def _get_attack_classifier_list(**kwargs):\n if framework == \"pytorch\":\n return get_attack_classifier_pt(**kwargs)\n\n raise ARTTestFixtureNotImplemented(\"no estimator available\", image_dl_estimator_for_attack.__name__, framework)\n\n return _get_attack_classifier_list\n\n\n@pytest.fixture(autouse=True)\ndef setup_tear_down_framework(framework):\n # Ran before each test\n if framework == \"tensorflow2\":\n import tensorflow as tf\n\n if tf.__version__[0] != \"2\":\n tf.reset_default_graph()\n\n yield True\n\n # Ran after each test\n if framework == \"keras\":\n import keras\n\n keras.backend.clear_session()\n\n\n@pytest.fixture\ndef image_iterator(framework, get_default_mnist_subset, default_batch_size):\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n\n def _get_image_iterator():\n if framework == \"keras\" or framework == \"kerastf\":\n from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n keras_gen = ImageDataGenerator(\n width_shift_range=0.075,\n height_shift_range=0.075,\n rotation_range=12,\n shear_range=0.075,\n zoom_range=0.05,\n fill_mode=\"constant\",\n cval=0,\n )\n return keras_gen.flow(x_train_mnist, y_train_mnist, batch_size=default_batch_size)\n\n if framework == \"tensorflow2\":\n import tensorflow as tf\n\n dataset = tf.data.Dataset.from_tensor_slices((x_train_mnist, y_train_mnist)).batch(default_batch_size)\n return dataset\n\n if framework in [\"pytorch\", \"huggingface\"]:\n import torch\n\n # Create tensors from data\n x_train_tens = torch.from_numpy(x_train_mnist)\n x_train_tens = x_train_tens.float()\n y_train_tens = torch.from_numpy(y_train_mnist)\n dataset = torch.utils.data.TensorDataset(x_train_tens, y_train_tens)\n return torch.utils.data.DataLoader(dataset=dataset, batch_size=default_batch_size, shuffle=True)\n\n return None\n\n return _get_image_iterator\n\n\n@pytest.fixture\ndef image_data_generator(framework, get_default_mnist_subset, image_iterator, default_batch_size):\n def _image_data_generator(**kwargs):\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n image_it = image_iterator()\n data_generator = None\n\n if framework == \"keras\" or framework == \"kerastf\":\n data_generator = KerasDataGenerator(\n iterator=image_it,\n size=x_train_mnist.shape[0],\n batch_size=default_batch_size,\n )\n\n if framework == \"tensorflow2\":\n data_generator = TensorFlowV2DataGenerator(\n iterator=image_it,\n size=x_train_mnist.shape[0],\n batch_size=default_batch_size,\n )\n\n if framework in [\"pytorch\", \"huggingface\"]:\n data_generator = PyTorchDataGenerator(\n iterator=image_it, size=x_train_mnist.shape[0], batch_size=default_batch_size\n )\n\n return data_generator\n\n return _image_data_generator\n\n\n@pytest.fixture\ndef store_expected_values(request):\n \"\"\"\n Stores expected values to be retrieved by the expected_values fixture\n Note1: Numpy arrays MUST be converted to list before being stored as json\n Note2: It's possible to store both a framework independent and framework specific value. If both are stored the\n framework specific value will be used\n :param request:\n :return:\n \"\"\"\n\n def _store_expected_values(values_to_store, framework=\"\"):\n\n framework_name = framework\n if framework_name:\n framework_name = \"_\" + framework_name\n\n file_name = request.node.location[0].split(\"/\")[-1][:-3] + \".json\"\n\n try:\n with open(\n os.path.join(os.path.dirname(__file__), os.path.dirname(request.node.location[0]), file_name), \"r\"\n ) as f:\n expected_values = json.load(f)\n except FileNotFoundError:\n expected_values = {}\n\n test_name = request.node.name + framework_name\n expected_values[test_name] = values_to_store\n\n with open(\n os.path.join(os.path.dirname(__file__), os.path.dirname(request.node.location[0]), file_name), \"w\"\n ) as f:\n json.dump(expected_values, f, indent=4)\n\n return _store_expected_values\n\n\n@pytest.fixture\ndef expected_values(framework, request):\n \"\"\"\n Retrieves the expected values that were stored using the store_expected_values fixture\n :param request:\n :return:\n \"\"\"\n\n file_name = request.node.location[0].split(\"/\")[-1][:-3] + \".json\"\n\n framework_name = framework\n if framework_name:\n framework_name = \"_\" + framework_name\n\n def _expected_values():\n with open(\n os.path.join(os.path.dirname(__file__), os.path.dirname(request.node.location[0]), file_name), \"r\"\n ) as f:\n expected_values = json.load(f)\n\n # searching first for any framework specific expected value\n framework_specific_values = request.node.name + framework_name\n if framework_specific_values in expected_values:\n return expected_values[framework_specific_values]\n elif request.node.name in expected_values:\n return expected_values[request.node.name]\n else:\n raise ARTTestFixtureNotImplemented(\n \"Couldn't find any expected values for test {0}\".format(request.node.name),\n expected_values.__name__,\n framework_name,\n )\n\n return _expected_values\n\n\n@pytest.fixture\ndef supported_losses_types(framework):\n def supported_losses_types():\n if framework == \"keras\":\n return [\"label\", \"function_losses\", \"function_backend\"]\n if framework == \"kerastf\":\n # if loss_type is not \"label\" and loss_name not in [\"categorical_hinge\", \"kullback_leibler_divergence\"]:\n return [\"label\", \"function\", \"class\"]\n\n raise ARTTestFixtureNotImplemented(\n \"Could not find supported_losses_types\", supported_losses_types.__name__, framework\n )\n\n return supported_losses_types\n\n\n@pytest.fixture\ndef supported_losses_logit(framework):\n def _supported_losses_logit():\n if framework == \"keras\":\n return [\"categorical_crossentropy_function_backend\", \"sparse_categorical_crossentropy_function_backend\"]\n if framework == \"kerastf\":\n # if loss_type is not \"label\" and loss_name not in [\"categorical_hinge\", \"kullback_leibler_divergence\"]:\n return [\n \"categorical_crossentropy_function\",\n \"categorical_crossentropy_class\",\n \"sparse_categorical_crossentropy_function\",\n \"sparse_categorical_crossentropy_class\",\n ]\n raise ARTTestFixtureNotImplemented(\n \"Could not find supported_losses_logit\", supported_losses_logit.__name__, framework\n )\n\n return _supported_losses_logit\n\n\n@pytest.fixture\ndef supported_losses_proba(framework):\n def _supported_losses_proba():\n if framework == \"keras\":\n return [\n \"categorical_hinge_function_losses\",\n \"categorical_crossentropy_label\",\n \"categorical_crossentropy_function_losses\",\n \"categorical_crossentropy_function_backend\",\n \"sparse_categorical_crossentropy_label\",\n \"sparse_categorical_crossentropy_function_losses\",\n \"sparse_categorical_crossentropy_function_backend\",\n ]\n if framework == \"kerastf\":\n return [\n \"categorical_hinge_function\",\n \"categorical_hinge_class\",\n \"categorical_crossentropy_label\",\n \"categorical_crossentropy_function\",\n \"categorical_crossentropy_class\",\n \"sparse_categorical_crossentropy_label\",\n \"sparse_categorical_crossentropy_function\",\n \"sparse_categorical_crossentropy_class\",\n # \"kullback_leibler_divergence_function\",\n \"kullback_leibler_divergence_class\",\n ]\n\n raise ARTTestFixtureNotImplemented(\n \"Could not find supported_losses_proba\", supported_losses_proba.__name__, framework\n )\n\n return _supported_losses_proba\n\n\n@pytest.fixture\ndef image_dl_generator(framework):\n def _image_dl_generator(**kwargs):\n if framework == \"tensorflow2\":\n return get_image_generator_tf_v2(64, 100)\n raise ARTTestFixtureNotImplemented(\"no test generator available\", image_dl_generator.__name__, framework)\n\n return _image_dl_generator\n\n\n@pytest.fixture\ndef image_dl_gan(framework):\n sess = None\n\n def _image_dl_gan(**kwargs):\n if framework == \"tensorflow2\":\n return get_image_gan_tf_v2(**kwargs), sess\n raise ARTTestFixtureNotImplemented(\"no test gan available\", image_dl_gan.__name__, framework)\n\n return _image_dl_gan\n\n\n@pytest.fixture\ndef image_dl_estimator(framework):\n def _image_dl_estimator(functional=False, **kwargs):\n sess = None\n wildcard = False\n classifier = None\n\n if kwargs.get(\"wildcard\") is not None:\n if kwargs.get(\"wildcard\") is True:\n wildcard = True\n del kwargs[\"wildcard\"]\n\n if framework == \"keras\":\n if wildcard is False and functional is False:\n if functional:\n classifier = get_image_classifier_kr_functional(**kwargs)\n else:\n try:\n classifier = get_image_classifier_kr(**kwargs)\n except NotImplementedError:\n raise ARTTestFixtureNotImplemented(\n \"This combination of loss function options is currently not supported.\",\n image_dl_estimator.__name__,\n framework,\n )\n\n if framework == \"tensorflow2\":\n if wildcard is False and functional is False:\n classifier, sess = get_image_classifier_tf(**kwargs, framework=framework)\n return classifier, sess\n\n if framework == \"pytorch\":\n if not wildcard:\n if functional:\n classifier = get_image_classifier_pt_functional(**kwargs)\n else:\n classifier = get_image_classifier_pt(**kwargs)\n\n if framework == \"kerastf\":\n if wildcard:\n classifier = get_image_classifier_kr_tf_with_wildcard(**kwargs)\n else:\n if functional:\n classifier = get_image_classifier_kr_tf_functional(**kwargs)\n else:\n classifier = get_image_classifier_kr_tf(**kwargs)\n\n if framework == \"huggingface\":\n if not wildcard:\n classifier = get_image_classifier_hf(**kwargs)\n\n if classifier is None:\n raise ARTTestFixtureNotImplemented(\n \"no test deep learning estimator available\", image_dl_estimator.__name__, framework\n )\n\n return classifier, sess\n\n return _image_dl_estimator\n\n\n@pytest.fixture\ndef art_warning(request):\n def _art_warning(exception):\n\n if request.node.get_closest_marker(\"framework_agnostic\"):\n if not request.node.get_closest_marker(\"parametrize\"):\n raise Exception(\n \"This test has marker framework_agnostic decorator which means it will only be ran \"\n \"once. However the ART test exception was thrown, hence it is never run fully. \"\n )\n elif (\n request.node.get_closest_marker(\"only_with_platform\")\n and len(request.node.get_closest_marker(\"only_with_platform\").args) == 1\n ):\n raise Exception(\n \"This test has marker only_with_platform decorator which means it will only be ran \"\n \"once. However the ARTTestFixtureNotImplemented exception was thrown, hence it is \"\n \"never run fully. \"\n )\n\n return _art_warning\n\n\n@pytest.fixture\ndef decision_tree_estimator(framework):\n def _decision_tree_estimator(clipped=True):\n if framework == \"scikitlearn\":\n return get_tabular_classifier_scikit_list(clipped=clipped, model_list_names=[\"decisionTreeClassifier\"])[0]\n\n raise ARTTestFixtureNotImplemented(\n \"no test decision_tree_classifier available\", decision_tree_estimator.__name__, framework\n )\n\n return _decision_tree_estimator\n\n\n@pytest.fixture\ndef tabular_dl_estimator(framework):\n def _tabular_dl_estimator(clipped=True):\n classifier = None\n if framework == \"keras\":\n if clipped:\n classifier = get_tabular_classifier_kr()\n else:\n kr_classifier = get_tabular_classifier_kr()\n classifier = KerasClassifier(model=kr_classifier.model, use_logits=False, channels_first=True)\n\n if framework == \"tensorflow2\":\n if clipped:\n classifier, _ = get_tabular_classifier_tf()\n\n if framework == \"pytorch\":\n if clipped:\n classifier = get_tabular_classifier_pt()\n\n if classifier is None:\n raise ARTTestFixtureNotImplemented(\n \"no deep learning tabular estimator available\", tabular_dl_estimator.__name__, framework\n )\n return classifier\n\n return _tabular_dl_estimator\n\n\n@pytest.fixture(scope=\"function\")\ndef create_test_image(create_test_dir):\n test_dir = create_test_dir\n # Download one ImageNet pic for tests\n url = \"http://farm1.static.flickr.com/163/381342603_81db58bea4.jpg\"\n result = requests.get(url, stream=True)\n if result.status_code == 200:\n image = result.raw.read()\n f = open(os.path.join(test_dir, \"test.jpg\"), \"wb\")\n f.write(image)\n f.close()\n\n yield os.path.join(test_dir, \"test.jpg\")\n\n\n@pytest.fixture(scope=\"session\")\ndef framework(request):\n ml_framework = request.config.getoption(\"--framework\")\n if ml_framework == \"tensorflow\":\n import tensorflow as tf\n\n if tf.__version__[0] == \"2\":\n ml_framework = \"tensorflow2\"\n else:\n raise ValueError(\"TensorFlow version not recognised.\")\n\n if ml_framework not in art_supported_frameworks:\n raise Exception(\n \"framework value {0} is unsupported. Please use one of these valid values: {1}\".format(\n ml_framework, \" \".join(art_supported_frameworks)\n )\n )\n # if utils_test.is_valid_framework(framework):\n # raise Exception(\"The framework specified was incorrect. Valid options available\n # are {0}\".format(art_supported_frameworks))\n return ml_framework\n\n\n@pytest.fixture(scope=\"session\")\ndef default_batch_size():\n yield 16\n\n\n@pytest.fixture(scope=\"session\")\ndef load_iris_dataset():\n logging.info(\"Loading Iris dataset\")\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris), _, _ = load_dataset(\"iris\")\n\n yield (x_train_iris, y_train_iris), (x_test_iris, y_test_iris)\n\n\n@pytest.fixture(scope=\"function\")\ndef get_iris_dataset(load_iris_dataset, framework):\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = load_iris_dataset\n\n x_train_iris_original = x_train_iris.copy()\n y_train_iris_original = y_train_iris.copy()\n x_test_iris_original = x_test_iris.copy()\n y_test_iris_original = y_test_iris.copy()\n\n yield (x_train_iris, y_train_iris), (x_test_iris, y_test_iris)\n\n np.testing.assert_array_almost_equal(x_train_iris_original, x_train_iris, decimal=3)\n np.testing.assert_array_almost_equal(y_train_iris_original, y_train_iris, decimal=3)\n np.testing.assert_array_almost_equal(x_test_iris_original, x_test_iris, decimal=3)\n np.testing.assert_array_almost_equal(y_test_iris_original, y_test_iris, decimal=3)\n\n\n@pytest.fixture(scope=\"session\")\ndef load_diabetes_dataset():\n logging.info(\"Loading Diabetes dataset\")\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes), _, _ = load_dataset(\"diabetes\")\n\n yield (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes)\n\n\n@pytest.fixture(scope=\"function\")\ndef get_diabetes_dataset(load_diabetes_dataset, framework):\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes) = load_diabetes_dataset\n\n x_train_diabetes_original = x_train_diabetes.copy()\n y_train_diabetes_original = y_train_diabetes.copy()\n x_test_diabetes_original = x_test_diabetes.copy()\n y_test_diabetes_original = y_test_diabetes.copy()\n\n yield (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes)\n\n np.testing.assert_array_almost_equal(x_train_diabetes_original, x_train_diabetes, decimal=3)\n np.testing.assert_array_almost_equal(y_train_diabetes_original, y_train_diabetes, decimal=3)\n np.testing.assert_array_almost_equal(x_test_diabetes_original, x_test_diabetes, decimal=3)\n np.testing.assert_array_almost_equal(y_test_diabetes_original, y_test_diabetes, decimal=3)\n\n\n@pytest.fixture(scope=\"session\")\ndef default_dataset_subset_sizes():\n n_train = 1000\n n_test = 100\n yield n_train, n_test\n\n\n@pytest.fixture()\ndef mnist_shape(framework):\n if framework in [\"pytorch\", \"huggingface\"]:\n return (1, 28, 28)\n else:\n return (28, 28, 1)\n\n\n@pytest.fixture()\ndef cifar10_shape(framework):\n if framework == \"pytorch\":\n return (3, 32, 32)\n else:\n return (32, 32, 3)\n\n\n@pytest.fixture()\ndef get_default_mnist_subset(get_mnist_dataset, default_dataset_subset_sizes, mnist_shape):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train, n_test = default_dataset_subset_sizes\n\n x_train_mnist = np.reshape(x_train_mnist, (x_train_mnist.shape[0],) + mnist_shape).astype(np.float32)\n x_test_mnist = np.reshape(x_test_mnist, (x_test_mnist.shape[0],) + mnist_shape).astype(np.float32)\n\n yield (x_train_mnist[:n_train], y_train_mnist[:n_train]), (x_test_mnist[:n_test], y_test_mnist[:n_test])\n\n\n@pytest.fixture()\ndef get_default_cifar10_subset(get_cifar10_dataset, default_dataset_subset_sizes, cifar10_shape):\n (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10) = get_cifar10_dataset\n n_train, n_test = default_dataset_subset_sizes\n\n x_train_cifar10 = np.reshape(x_train_cifar10, (x_train_cifar10.shape[0],) + cifar10_shape).astype(np.float32)\n x_test_cifar10 = np.reshape(x_test_cifar10, (x_test_cifar10.shape[0],) + cifar10_shape).astype(np.float32)\n\n yield (x_train_cifar10[:n_train], y_train_cifar10[:n_train]), (x_test_cifar10[:n_test], y_test_cifar10[:n_test])\n\n\n@pytest.fixture(scope=\"session\")\ndef load_mnist_dataset():\n logging.info(\"Loading mnist\")\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist), _, _ = load_dataset(\"mnist\")\n yield (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist)\n\n\n@pytest.fixture(scope=\"session\")\ndef load_cifar10_dataset():\n logging.info(\"Loading cifar10\")\n (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10), _, _ = load_dataset(\"cifar10\")\n yield (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10)\n\n\n@pytest.fixture(scope=\"function\")\ndef create_test_dir():\n test_dir = tempfile.mkdtemp()\n yield test_dir\n shutil.rmtree(test_dir)\n\n\n@pytest.fixture(scope=\"function\")\ndef get_mnist_dataset(load_mnist_dataset, mnist_shape):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = load_mnist_dataset\n\n x_train_mnist = np.reshape(x_train_mnist, (x_train_mnist.shape[0],) + mnist_shape).astype(np.float32)\n x_test_mnist = np.reshape(x_test_mnist, (x_test_mnist.shape[0],) + mnist_shape).astype(np.float32)\n\n x_train_mnist_original = x_train_mnist.copy()\n y_train_mnist_original = y_train_mnist.copy()\n x_test_mnist_original = x_test_mnist.copy()\n y_test_mnist_original = y_test_mnist.copy()\n\n yield (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist)\n\n # Check that the test data has not been modified, only catches changes in attack.generate if self has been used\n np.testing.assert_array_almost_equal(x_train_mnist_original, x_train_mnist, decimal=3)\n np.testing.assert_array_almost_equal(y_train_mnist_original, y_train_mnist, decimal=3)\n np.testing.assert_array_almost_equal(x_test_mnist_original, x_test_mnist, decimal=3)\n np.testing.assert_array_almost_equal(y_test_mnist_original, y_test_mnist, decimal=3)\n\n\n@pytest.fixture(scope=\"function\")\ndef get_cifar10_dataset(load_cifar10_dataset, cifar10_shape):\n (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10) = load_cifar10_dataset\n\n x_train_cifar10 = np.reshape(x_train_cifar10, (x_train_cifar10.shape[0],) + cifar10_shape).astype(np.float32)\n x_test_cifar10 = np.reshape(x_test_cifar10, (x_test_cifar10.shape[0],) + cifar10_shape).astype(np.float32)\n\n x_train_cifar10_original = x_train_cifar10.copy()\n y_train_cifar10_original = y_train_cifar10.copy()\n x_test_cifar10_original = x_test_cifar10.copy()\n y_test_cifar10_original = y_test_cifar10.copy()\n\n yield (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10)\n\n # Check that the test data has not been modified, only catches changes in attack.generate if self has been used\n np.testing.assert_array_almost_equal(x_train_cifar10_original, x_train_cifar10, decimal=3)\n np.testing.assert_array_almost_equal(y_train_cifar10_original, y_train_cifar10, decimal=3)\n np.testing.assert_array_almost_equal(x_test_cifar10_original, x_test_cifar10, decimal=3)\n np.testing.assert_array_almost_equal(y_test_cifar10_original, y_test_cifar10, decimal=3)\n\n\n# ART test fixture to skip test for specific framework values\n# eg: @pytest.mark.only_with_platform(\"tensorflow\")\n@pytest.fixture(autouse=True)\ndef only_with_platform(request, framework):\n if request.node.get_closest_marker(\"only_with_platform\"):\n if framework not in request.node.get_closest_marker(\"only_with_platform\").args:\n pytest.skip(\"skipped on this platform: {}\".format(framework))\n\n\n# ART test fixture to skip test for specific framework values\n# eg: @pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"pytorch\", \"scikitlearn\",\n# \"kerastf\", \"non_dl_frameworks\", \"dl_frameworks\")\n@pytest.fixture(autouse=True)\ndef skip_by_framework(request, framework):\n if request.node.get_closest_marker(\"skip_framework\"):\n framework_to_skip_list = list(request.node.get_closest_marker(\"skip_framework\").args)\n if \"dl_frameworks\" in framework_to_skip_list:\n framework_to_skip_list.extend(deep_learning_frameworks)\n\n if \"non_dl_frameworks\" in framework_to_skip_list:\n framework_to_skip_list.extend(non_deep_learning_frameworks)\n\n if \"tensorflow\" in framework_to_skip_list:\n framework_to_skip_list.append(\"tensorflow2\")\n\n if framework in framework_to_skip_list:\n pytest.skip(\"skipped on this platform: {}\".format(framework))\n\n\n@pytest.fixture\ndef make_customer_record():\n def _make_customer_record(name):\n return {\"name\": name, \"orders\": []}\n\n return _make_customer_record\n\n\n@pytest.fixture(autouse=True)\ndef framework_agnostic(request, framework):\n if request.node.get_closest_marker(\"framework_agnostic\"):\n if framework != get_default_framework():\n pytest.skip(\"framework agnostic test skipped for framework : {}\".format(framework))\n\n\n# ART test fixture to skip test for specific required modules\n# eg: @pytest.mark.skip_module(\"deepspeech_pytorch\", \"apex.amp\", \"object_detection\")\n@pytest.fixture(autouse=True)\ndef skip_by_module(request):\n if request.node.get_closest_marker(\"skip_module\"):\n modules_from_args = request.node.get_closest_marker(\"skip_module\").args\n\n # separate possible parent modules and test them first\n modules_parents = [m.split(\".\", 1)[0] for m in modules_from_args]\n\n # merge with modules including submodules (Note: sort ensures that parent comes first)\n modules_full = sorted(set(modules_parents).union(modules_from_args))\n\n for module in modules_full:\n if module in modules_full:\n module_spec = importlib.util.find_spec(module)\n module_found = module_spec is not None\n\n if not module_found:\n pytest.skip(f\"Test skipped because package {module} not available.\")\n\n\n@pytest.fixture()\ndef fix_get_rcnn():\n\n from art.estimators.estimator import BaseEstimator, LossGradientsMixin\n from art.estimators.object_detection.object_detector import ObjectDetectorMixin\n\n class DummyObjectDetector(ObjectDetectorMixin, LossGradientsMixin, BaseEstimator):\n def __init__(self):\n self._clip_values = (0, 1)\n self.channels_first = False\n self._input_shape = None\n self._compute_loss_count = 1\n\n def loss_gradient(self, x: np.ndarray, y: None, **kwargs):\n return np.ones_like(x)\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs):\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n dict_i = {\"boxes\": np.array([[0.1, 0.2, 0.3, 0.4]]), \"labels\": np.array([[2]]), \"scores\": np.array([[0.8]])}\n return [dict_i] * x.shape[0]\n\n @property\n def native_label_is_pytorch_format(self):\n return True\n\n @property\n def input_shape(self):\n return self._input_shape\n\n def compute_losses(\n self, x: np.ndarray, y: Union[List[Dict[str, np.ndarray]], List[Dict[str, \"torch.Tensor\"]]]\n ) -> Dict[str, np.ndarray]:\n\n losses_dict = {\n \"loss_classifier\": np.array(0.43572357, dtype=float),\n \"loss_box_reg\": np.array(0.17341757, dtype=float),\n \"loss_objectness\": np.array(0.02198849, dtype=float),\n \"loss_rpn_box_reg\": np.array(0.03471708, dtype=float),\n }\n\n return losses_dict\n\n def compute_loss(\n self, x: np.ndarray, y: Union[List[Dict[str, np.ndarray]], List[Dict[str, \"torch.Tensor\"]]], **kwargs\n ) -> Union[np.ndarray, \"torch.Tensor\"]:\n self._compute_loss_count += 1\n loss = 0.43572357 / self._compute_loss_count\n return loss\n\n frcnn = DummyObjectDetector()\n return frcnn\n\n\n@pytest.fixture()\ndef fix_get_goturn():\n\n from art.estimators.estimator import BaseEstimator, LossGradientsMixin\n from art.estimators.object_tracking.object_tracker import ObjectTrackerMixin\n\n class DummyObjectTracker(ObjectTrackerMixin, LossGradientsMixin, BaseEstimator):\n def __init__(self):\n super().__init__(\n model=None,\n clip_values=(0, 1),\n preprocessing_defences=None,\n postprocessing_defences=None,\n preprocessing=(0, 1),\n )\n\n import torch\n\n self.channels_first = False\n self._input_shape = None\n self.postprocessing_defences = None\n self.device = torch.device(\"cpu\")\n\n def loss_gradient(self, x: np.ndarray, y: None, **kwargs):\n return np.ones_like(x)\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs):\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n boxes_list = list()\n for i in range(x.shape[1]):\n boxes_list.append([0.1, 0.2, 0.3, 0.4])\n\n dict_i = {\"boxes\": np.array(boxes_list), \"labels\": np.array([[2]]), \"scores\": np.array([[0.8]])}\n return [dict_i] * x.shape[0]\n\n @property\n def native_label_is_pytorch_format(self):\n return True\n\n @property\n def input_shape(self):\n return self._input_shape\n\n goturn = DummyObjectTracker()\n return goturn\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: run_tests.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n#!/usr/bin/env bash\n\nexit_code=0\n\n# Set TensorFlow logging to minimum level ERROR\nexport TF_CPP_MIN_LOG_LEVEL=\"3\"\n\n# --------------------------------------------------------------------------------------------------------------- TESTS\n\n# NOTE: All the tests should be ran within this loop. All other tests are legacy tests that must be made framework\n# independent to be incorporated within this loop\nframeworkList=(\"tensorflow\" \"keras\" \"pytorch\" \"scikitlearn\" \"kerastf\")\nframework=$1\nlegacy_module=$2\n\nif [[ ${framework} != \"legacy\" ]]\nthen\n echo \"#######################################################################\"\n echo \"############### Running tests with framework $framework ###############\"\n echo \"#######################################################################\"\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/defences/detector/evasion --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed defences/detector/evasion tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/defences/detector/poison/test_spectral_signature_defense.py --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed defences/detector/poison/test_spectral_signature_defense.py tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/defences/preprocessor --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed defences/preprocessor tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/defences/trainer --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed defences/trainer tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/defences/transformer --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed defences/transformer tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/preprocessing/audio --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed preprocessing/audio tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/preprocessing/image --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed preprocessing/image tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/preprocessing/expectation_over_transformation --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed preprocessing/expectation_over_transformation tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/utils --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed utils tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv -s tests/attacks/poison/ --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed attacks/poison tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv -s tests/attacks/evasion/ --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed attacks/evasion\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/estimators/speech_recognition/ --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed estimators/speech_recognition tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/attacks/inference/ --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed attacks/inference\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/classifiersFrameworks/ --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed classifiersFrameworks tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/estimators/classification/test_deeplearning_common.py --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed estimators/classification/test_deeplearning_common.py $framework\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/estimators/classification/test_deeplearning_specific.py --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed estimators/classification tests for framework $framework\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/estimators/certification/ --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed estimators/certification tests for framework $framework\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/estimators/classification/test_blackbox_existing_predictions.py --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed estimators/classification/test_blackbox_existing_predictions.py $framework\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/estimators/regression/test_blackbox.py --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed estimators/regression/test_blackbox.py $framework\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/metrics/privacy --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed metrics/privacy tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/evaluations --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed evaluations tests\"; fi\n\n pytest --cov-report=xml --cov=art --cov-append -q -vv tests/test_summary_writer.py --framework=$framework --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed summary writer tests\"; fi\n\nelse\n declare -a attacks_1=(\"tests/attacks/test_adversarial_patch.py\" \\\n \"tests/attacks/test_adversarial_embedding.py\" \\\n \"tests/attacks/test_backdoor_attack.py\" \\\n \"tests/attacks/test_carlini.py\" \\\n \"tests/attacks/test_copycat_cnn.py\" \\\n \"tests/attacks/test_decision_tree_attack.py\" \\\n \"tests/attacks/test_deepfool.py\" \\\n \"tests/attacks/test_elastic_net.py\" \\\n \"tests/attacks/test_feature_collision.py\" \\\n \"tests/attacks/test_functionally_equivalent_extraction.py\" \\\n \"tests/attacks/test_graphite.py\" \\\n \"tests/attacks/test_hclu.py\" \\\n \"tests/attacks/test_input_filter.py\" \\\n \"tests/attacks/test_hop_skip_jump.py\" \\\n \"tests/attacks/test_iterative_method.py\" \\\n \"tests/attacks/test_knockoff_nets.py\" )\n\n declare -a attacks_2=(\"tests/attacks/test_newtonfool.py\" \\\n \"tests/attacks/test_poisoning_attack_svm.py\" \\\n \"tests/attacks/test_projected_gradient_descent.py\" \\\n \"tests/attacks/test_saliency_map.py\" \\\n \"tests/attacks/test_spatial_transformation.py\" \\\n \"tests/attacks/test_universal_perturbation.py\" \\\n \"tests/attacks/test_virtual_adversarial.py\" \\\n \"tests/attacks/test_zoo.py\" \\\n \"tests/attacks/test_pixel_attack.py\" \\\n \"tests/attacks/test_threshold_attack.py\" \\\n \"tests/attacks/test_wasserstein.py\" \\\n \"tests/attacks/test_targeted_universal_perturbation.py\" \\\n \"tests/attacks/test_simba.py\" )\n\n declare -a estimators=(\"tests/estimators/classification/test_blackbox.py\" \\\n \"tests/estimators/classification/test_catboost.py\" \\\n \"tests/estimators/classification/test_classifier.py\" \\\n \"tests/estimators/classification/test_deep_partition_ensemble.py\" \\\n \"tests/estimators/classification/test_detector_classifier.py\" \\\n \"tests/estimators/classification/test_ensemble.py\" \\\n \"tests/estimators/classification/test_GPy.py\" \\\n \"tests/estimators/classification/test_input_filter.py\" \\\n \"tests/estimators/classification/test_lightgbm.py\" \\\n \"tests/estimators/classification/test_query_efficient_bb.py\" \\\n \"tests/estimators/classification/test_scikitlearn.py\" \\\n \"tests/estimators/classification/test_xgboost.py\" \\\n \"tests/estimators/regression/test_scikitlearn.py\" )\n\n declare -a defences=(\"tests/defences/test_adversarial_trainer.py\" \\\n \"tests/defences/test_class_labels.py\" \\\n \"tests/defences/test_defensive_distillation.py\" \\\n \"tests/defences/test_feature_squeezing.py\" \\\n \"tests/defences/test_gaussian_augmentation.py\" \\\n \"tests/defences/test_gaussian_noise.py\" \\\n \"tests/defences/test_high_confidence.py\" \\\n \"tests/defences/test_label_smoothing.py\" \\\n \"tests/defences/test_neural_cleanse.py\" \\\n \"tests/defences/test_pixel_defend.py\" \\\n \"tests/defences/test_reverse_sigmoid.py\" \\\n \"tests/defences/test_rounded.py\" \\\n \"tests/defences/test_thermometer_encoding.py\" \\\n \"tests/defences/test_variance_minimization.py\" \\\n \"tests/defences/detector/evasion/test_beyond_detector.py\" \\\n \"tests/defences/detector/evasion/test_binary_activation_detector.py\" \\\n \"tests/defences/detector/evasion/test_binary_input_detector.py\" \\\n \"tests/defences/detector/evasion/test_subsetscanning_detector.py\" \\\n \"tests/defences/detector/poison/test_activation_defence.py\" \\\n \"tests/defences/detector/poison/test_clustering_analyzer.py\" \\\n \"tests/defences/detector/poison/test_ground_truth_evaluator.py\" \\\n \"tests/defences/detector/poison/test_provenance_defence.py\" \\\n \"tests/defences/detector/poison/test_roni.py\" )\n\n declare -a metrics=(\"tests/metrics/test_gradient_check.py\" \\\n \"tests/metrics/test_metrics.py\" \\\n \"tests/metrics/test_verification_decision_trees.py\" )\n\n declare -a art=(\"tests/test_data_generators.py\" \\\n \"tests/test_optimizers.py\" \\\n \"tests/test_utils.py\" \\\n \"tests/test_visualization.py\" )\n\n # ----------------------------------------------------------------------------------------------- CODE TO RUN TESTS\n\n run_test () {\n test=$1\n test_file_name=\"$(echo ${test} | rev | cut -d'/' -f1 | rev)\"\n\n echo $'\\n\\n'\n echo \"######################################################################\"\n echo ${test}\n echo \"######################################################################\"\n pytest --cov-report=xml --cov=art --cov-append -q -vv ${test} --durations=20 --durations-min=0\n if [[ $? -ne 0 ]]; then exit_code=1; echo \"Failed $test\"; fi\n }\n\n tests=\"$legacy_module[@]\"\n for test in \"${!tests}\"; do\n run_test ${test}\n done\nfi\n\nexit ${exit_code}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: setup.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nimport codecs\nimport os\n\nfrom setuptools import find_packages, setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ninstall_requires = [\n \"numpy>=1.18.0\",\n \"scipy>=1.4.1\",\n \"scikit-learn>=0.22.2\",\n \"six\",\n \"setuptools\",\n \"tqdm\",\n]\n\ndocs_require = [\n \"sphinx >= 1.4\",\n \"sphinx_rtd_theme\",\n \"sphinx-autodoc-annotation\",\n \"sphinx-autodoc-typehints\",\n \"matplotlib\",\n \"numpy>=1.18.0\",\n \"scipy>=1.4.1\",\n \"six>=1.13.0\",\n \"scikit-learn>=0.22.2\",\n \"Pillow>=6.0.0\",\n]\n\n\ndef read(rel_path):\n here = os.path.abspath(os.path.dirname(__file__))\n with codecs.open(os.path.join(here, rel_path), \"r\", encoding=\"utf-8\") as fp:\n return fp.read()\n\n\ndef get_version(rel_path):\n for line in read(rel_path).splitlines():\n if line.startswith(\"__version__\"):\n delim = '\"' if '\"' in line else \"'\"\n return line.split(delim)[1]\n raise RuntimeError(\"Unable to find version string.\")\n\n\nsetup(\n name=\"adversarial-robustness-toolbox\",\n version=get_version(\"art/__init__.py\"),\n description=\"Toolbox for adversarial machine learning.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Irina Nicolae\",\n author_email=\"irinutza.n@gmail.com\",\n maintainer=\"Beat Buesser\",\n maintainer_email=\"beat.buesser@ie.ibm.com\",\n url=\"https://github.com/Trusted-AI/adversarial-robustness-toolbox\",\n license=\"MIT\",\n install_requires=install_requires,\n extras_require={\n \"docs\": docs_require,\n \"catboost\": [\"catboost\"],\n \"gpy\": [\"GPy\"],\n \"keras\": [\"keras\", \"h5py\"],\n \"lightgbm\": [\"lightgbm\"],\n \"tensorflow\": [\"tensorflow\", \"h5py\"],\n \"tensorflow_image\": [\"tensorflow\", \"h5py\", \"Pillow\", \"ffmpeg-python\", \"opencv-python\"],\n \"tensorflow_audio\": [\"tensorflow\", \"h5py\", \"pydub\", \"resampy\", \"librosa\"],\n \"pytorch\": [\"torch\", \"torchvision\"],\n \"pytorch_image\": [\"torch\", \"torchvision\", \"kornia\", \"Pillow\", \"ffmpeg-python\", \"opencv-python\"],\n \"pytorch_audio\": [\"torch\", \"torchvision\", \"torchaudio\", \"pydub\", \"resampy\", \"librosa\"],\n \"xgboost\": [\"xgboost\"],\n \"all\": [\n \"catboost\",\n \"lightgbm\",\n \"tensorflow\",\n \"tensorflow-addons\",\n \"h5py\",\n \"torch\",\n \"torchvision\",\n \"xgboost\",\n \"pandas\",\n \"kornia\",\n \"matplotlib\",\n \"Pillow\",\n \"statsmodels\",\n \"pydub\",\n \"resampy\",\n \"ffmpeg-python\",\n \"cma\",\n \"librosa\",\n \"opencv-python\",\n \"numba\",\n ],\n \"non_framework\": [\n \"matplotlib\",\n \"Pillow\",\n \"statsmodels\",\n \"pydub\",\n \"resampy\",\n \"ffmpeg-python\",\n \"cma\",\n \"pandas\",\n \"librosa\",\n \"opencv-python\",\n \"pytest\",\n \"pytest-flake8\",\n \"pytest-mock\",\n \"pytest-cov\",\n \"requests\",\n \"sortedcontainers\",\n \"numba\",\n \"timm\",\n \"multiprocess\",\n ]\n },\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Education\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Programming Language :: Python :: 3.12\",\n \"Topic :: Software Development :: Libraries\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n \"Topic :: Security\",\n ],\n packages=find_packages(exclude=[\"tests\", \"tests.*\"]),\n include_package_data=True,\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe Adversarial Robustness Toolbox (ART).\n\"\"\"\n\nimport logging.config\n\n# Project Imports\nfrom art import attacks\nfrom art import defences\nfrom art import estimators\nfrom art import evaluations\nfrom art import metrics\nfrom art import preprocessing\n\n# Semantic Version\n__version__ = \"1.20.1\"\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"std\": {\n \"format\": \"%(asctime)s [%(levelname)s] %(name)s: %(message)s\",\n \"datefmt\": \"%Y-%m-%d %H:%M\",\n }\n },\n \"handlers\": {\n \"default\": {\n \"class\": \"logging.NullHandler\",\n },\n \"test\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"std\",\n \"level\": logging.INFO,\n },\n },\n \"loggers\": {\n \"art\": {\"handlers\": [\"default\"]},\n \"tests\": {\"handlers\": [\"test\"], \"level\": \"INFO\", \"propagate\": True},\n },\n}\nlogging.config.dictConfig(LOGGING)\nlogger = logging.getLogger(__name__)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/config.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module loads and provides configuration parameters for ART.\n\"\"\"\nimport json\nimport logging\nimport os\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\n# ------------------------------------------------------------------------------------------------- CONSTANTS AND TYPES\n\nART_NUMPY_DTYPE = np.float32 # pylint: disable=invalid-name\nART_DATA_PATH: str\n\n# --------------------------------------------------------------------------------------------- DEFAULT PACKAGE CONFIGS\n\n_folder = os.path.expanduser(\"~\")\nif not os.access(_folder, os.W_OK): # pragma: no cover\n _folder = \"/tmp\" # pylint: disable=invalid-name\n_folder = os.path.join(_folder, \".art\")\n\n\ndef set_data_path(path):\n \"\"\"\n Set the path for ART's data directory (ART_DATA_PATH).\n \"\"\"\n expanded_path = os.path.abspath(os.path.expanduser(path))\n os.makedirs(expanded_path, exist_ok=True)\n if not os.access(expanded_path, os.R_OK): # pragma: no cover\n raise OSError(f\"path {expanded_path} cannot be read from\")\n if not os.access(expanded_path, os.W_OK): # pragma: no cover\n logger.warning(\"path %s is read only\", expanded_path)\n\n global ART_DATA_PATH # pylint: disable=global-statement\n ART_DATA_PATH = expanded_path\n logger.info(\"set ART_DATA_PATH to %s\", expanded_path)\n\n\n# Load data from configuration file if it exists. Otherwise, create one.\n_config_path = os.path.expanduser(os.path.join(_folder, \"config.json\"))\nif os.path.exists(_config_path):\n try:\n with open(_config_path, encoding=\"utf8\") as f:\n _config = json.load(f)\n\n # Since renaming this variable we must update existing config files\n if \"DATA_PATH\" in _config: # pragma: no cover\n _config[\"ART_DATA_PATH\"] = _config.pop(\"DATA_PATH\")\n try:\n with open(_config_path, \"w\", encoding=\"utf8\") as f:\n f.write(json.dumps(_config, indent=4))\n except IOError:\n logger.warning(\"Unable to update configuration file\", exc_info=True)\n\n except ValueError: # pragma: no cover\n _config = {}\n\nif not os.path.exists(_folder):\n try:\n os.makedirs(_folder)\n except OSError: # pragma: no cover\n logger.warning(\"Unable to create folder for configuration file.\", exc_info=True)\n\nif not os.path.exists(_config_path):\n # Generate default config\n _config = {\"ART_DATA_PATH\": os.path.join(_folder, \"data\")}\n\n try:\n with open(_config_path, \"w\", encoding=\"utf8\") as f:\n f.write(json.dumps(_config, indent=4))\n except IOError: # pragma: no cover\n logger.warning(\"Unable to create configuration file\", exc_info=True)\n\nif \"ART_DATA_PATH\" in _config: # pragma: no cover\n set_data_path(_config[\"ART_DATA_PATH\"])\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/data_generators.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule defining an interface for data generators and providing concrete implementations for the supported frameworks.\nTheir purpose is to allow for data loading and batching on the fly, as well as dynamic data augmentation.\nThe generators can be used with the `fit_generator` function in the :class:`.Classifier` interface. Users can define\ntheir own generators following the :class:`.DataGenerator` interface. For large, numpy array-based datasets, the\n:class:`.NumpyDataGenerator` class can be flexibly used with `fit_generator` on framework-specific classifiers.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nimport inspect\nimport logging\nfrom typing import Any, Generator, Iterator, TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n import keras\n import tensorflow as tf\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass DataGenerator(abc.ABC):\n \"\"\"\n Base class for data generators.\n \"\"\"\n\n def __init__(self, size: int | None, batch_size: int) -> None:\n \"\"\"\n Base initializer for data generators.\n\n :param size: Total size of the dataset.\n :param batch_size: Size of the minibatches.\n \"\"\"\n if size is not None and (not isinstance(size, int) or size < 1):\n raise ValueError(\"The total size of the dataset must be an integer greater than zero.\")\n self._size = size\n\n if not isinstance(batch_size, int) or batch_size < 1:\n raise ValueError(\"The batch size must be an integer greater than zero.\")\n self._batch_size = batch_size\n\n if size is not None and batch_size > size:\n raise ValueError(\"The batch size must be smaller than the dataset size.\")\n\n self._iterator: Any | None = None\n\n @abc.abstractmethod\n def get_batch(self) -> tuple:\n \"\"\"\n Provide the next batch for training in the form of a tuple `(x, y)`. The generator should loop over the data\n indefinitely.\n\n :return: A tuple containing a batch of data `(x, y)`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def iterator(self):\n \"\"\"\n :return: Return the framework's iterable data generator.\n \"\"\"\n return self._iterator\n\n @property\n def batch_size(self) -> int:\n \"\"\"\n :return: Return the batch size.\n \"\"\"\n return self._batch_size\n\n @property\n def size(self) -> int | None:\n \"\"\"\n :return: Return the dataset size.\n \"\"\"\n return self._size\n\n\nclass NumpyDataGenerator(DataGenerator):\n \"\"\"\n Simple numpy data generator backed by numpy arrays.\n\n Can be useful for applying numpy data to estimators in other frameworks\n e.g., when translating the entire numpy data to GPU tensors would cause OOM\n \"\"\"\n\n def __init__(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 1,\n drop_remainder: bool = True,\n shuffle: bool = False,\n ):\n \"\"\"\n Create a numpy data generator backed by numpy arrays\n\n :param x: Numpy array of inputs\n :param y: Numpy array of targets\n :param batch_size: Size of the minibatches\n :param drop_remainder: Whether to omit the last incomplete minibatch in an epoch\n :param shuffle: Whether to shuffle the dataset for each epoch\n \"\"\"\n x = np.asanyarray(x)\n y = np.asanyarray(y)\n try:\n if len(x) != len(y):\n raise ValueError(\"inputs must be of equal length\")\n except TypeError as err:\n raise ValueError(f\"inputs x {x} and y {y} must be sized objects\") from err\n size = len(x)\n self.x = x\n self.y = y\n super().__init__(size, int(batch_size))\n self.shuffle = bool(shuffle)\n\n self.drop_remainder = bool(drop_remainder)\n batches_per_epoch = size / self.batch_size\n if not self.drop_remainder:\n batches_per_epoch = np.ceil(batches_per_epoch)\n self.batches_per_epoch = int(batches_per_epoch)\n self._iterator = self\n self.generator: Iterator[Any] = iter([])\n\n def __iter__(self):\n if self.shuffle:\n index = np.arange(self.size)\n np.random.shuffle(index)\n for i in range(self.batches_per_epoch):\n batch_index = index[i * self.batch_size : (i + 1) * self.batch_size]\n yield (self.x[batch_index], self.y[batch_index])\n else:\n for i in range(self.batches_per_epoch):\n yield (\n self.x[i * self.batch_size : (i + 1) * self.batch_size],\n self.y[i * self.batch_size : (i + 1) * self.batch_size],\n )\n\n def get_batch(self) -> tuple:\n \"\"\"\n Provide the next batch for training in the form of a tuple `(x, y)`.\n The generator will loop over the data indefinitely.\n If drop_remainder is True, then the last minibatch in each epoch may be a different size\n\n :return: A tuple containing a batch of data `(x, y)`.\n \"\"\"\n try:\n return next(self.generator)\n except StopIteration:\n self.generator = iter(self)\n return next(self.generator)\n\n\nclass KerasDataGenerator(DataGenerator):\n \"\"\"\n Wrapper class on top of the Keras-native data generators. These can either be generator functions,\n `keras.utils.Sequence` or Keras-specific data generators (`keras.preprocessing.image.ImageDataGenerator`).\n \"\"\"\n\n def __init__(\n self,\n iterator: (\n \"keras.utils.Sequence\"\n | \"tf.keras.utils.Sequence\"\n | \"keras.preprocessing.image.ImageDataGenerator\"\n | \"tf.keras.preprocessing.image.ImageDataGenerator\"\n | Generator\n ),\n size: int | None,\n batch_size: int,\n ) -> None:\n \"\"\"\n Create a Keras data generator wrapper instance.\n\n :param iterator: A generator as specified by Keras documentation. Its output must be a tuple of either\n `(inputs, targets)` or `(inputs, targets, sample_weights)`. All arrays in this tuple must have\n the same length. The generator is expected to loop over its data indefinitely.\n :param size: Total size of the dataset.\n :param batch_size: Size of the minibatches.\n \"\"\"\n super().__init__(size=size, batch_size=batch_size)\n self._iterator = iterator\n\n def get_batch(self) -> tuple:\n \"\"\"\n Provide the next batch for training in the form of a tuple `(x, y)`. The generator should loop over the data\n indefinitely.\n\n :return: A tuple containing a batch of data `(x, y)`.\n \"\"\"\n if inspect.isgeneratorfunction(self.iterator):\n return next(self.iterator)\n\n iter_ = iter(self.iterator)\n return next(iter_)\n\n\nclass PyTorchDataGenerator(DataGenerator):\n \"\"\"\n Wrapper class on top of the PyTorch native data loader :class:`torch.utils.data.DataLoader`.\n \"\"\"\n\n def __init__(self, iterator: \"torch.utils.data.DataLoader\", size: int, batch_size: int) -> None:\n \"\"\"\n Create a data generator wrapper on top of a PyTorch :class:`DataLoader`.\n\n :param iterator: A PyTorch data generator.\n :param size: Total size of the dataset.\n :param batch_size: Size of the minibatches.\n \"\"\"\n from torch.utils.data import DataLoader\n\n super().__init__(size=size, batch_size=batch_size)\n if not isinstance(iterator, DataLoader):\n raise TypeError(f\"Expected instance of PyTorch `DataLoader, received {type(iterator)} instead.`\")\n\n self._iterator: DataLoader = iterator\n self._current = iter(self.iterator)\n\n def get_batch(self) -> tuple:\n \"\"\"\n Provide the next batch for training in the form of a tuple `(x, y)`. The generator should loop over the data\n indefinitely.\n\n :return: A tuple containing a batch of data `(x, y)`.\n :rtype: `tuple`\n \"\"\"\n try:\n batch = list(next(self._current))\n except StopIteration:\n self._current = iter(self.iterator)\n batch = list(next(self._current))\n\n for i, item in enumerate(batch):\n batch[i] = item.data.cpu().numpy()\n\n return tuple(batch)\n\n\nclass TensorFlowV2DataGenerator(DataGenerator):\n \"\"\"\n Wrapper class on top of the TensorFlow v2 native iterators :class:`tf.data.Iterator`.\n \"\"\"\n\n def __init__(self, iterator: \"tf.data.Dataset\", size: int, batch_size: int) -> None:\n \"\"\"\n Create a data generator wrapper for TensorFlow. Supported iterators: initializable, reinitializable, feedable.\n\n :param iterator: TensorFlow Dataset.\n :param size: Total size of the dataset.\n :param batch_size: Size of the minibatches.\n :raises `TypeError`, `ValueError`: If input parameters are not valid.\n \"\"\"\n\n import tensorflow as tf\n\n super().__init__(size=size, batch_size=batch_size)\n self._iterator = iterator\n self._iterator_iter = iter(iterator)\n\n if not isinstance(iterator, tf.data.Dataset):\n raise TypeError(\"Only support object tf.data.Dataset\")\n\n def get_batch(self) -> tuple:\n \"\"\"\n Provide the next batch for training in the form of a tuple `(x, y)`. The generator should loop over the data\n indefinitely.\n\n :return: A tuple containing a batch of data `(x, y)`.\n :raises `ValueError`: If the iterator has reached the end.\n \"\"\"\n # Get next batch\n x, y = next(self._iterator_iter)\n return x.numpy(), y.numpy()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/exceptions.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule containing ART's exceptions.\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Type\n\n\nclass EstimatorError(TypeError):\n \"\"\"\n Basic exception for errors raised by unexpected estimator types.\n \"\"\"\n\n def __init__(self, this_class, class_expected_list: list[Type | tuple[Type]], classifier_given) -> None:\n super().__init__()\n self.this_class = this_class\n self.class_expected_list = class_expected_list\n self.classifier_given = classifier_given\n\n classes_expected_message = \"\"\n for idx, class_expected in enumerate(class_expected_list):\n if idx != 0:\n classes_expected_message += \" and \"\n if isinstance(class_expected, type):\n classes_expected_message += f\"{class_expected}\"\n else:\n classes_expected_message += \"(\"\n for or_idx, or_class in enumerate(class_expected):\n if or_idx != 0:\n classes_expected_message += \" or \"\n classes_expected_message += f\"{or_class}\"\n classes_expected_message += \")\"\n\n self.message = (\n f\"{this_class.__name__} requires an estimator derived from {classes_expected_message}, \"\n f\"the provided classifier is an instance of {type(classifier_given)} \"\n f\"and is derived from {classifier_given.__class__.__bases__}.\"\n )\n\n def __str__(self) -> str:\n return self.message\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/optimizers.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule defining an interface for optimizers.\n\"\"\"\nimport numpy as np\n\n\nclass Adam:\n \"\"\"\n A simple implementation of Adam optimizer.\n \"\"\"\n\n def __init__(self, alpha=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8):\n self.m_dx = 0.0\n self.v_dx = 0.0\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.epsilon = epsilon\n self.alpha = alpha\n\n def update(self, niter: int, x: np.ndarray, delta_x: np.ndarray) -> np.ndarray:\n \"\"\"\n Update one iteration.\n\n :param niter: Number of current iteration.\n :param x: Current value.\n :param delta_x: Current first derivative at `x`.\n :return: Updated value.\n \"\"\"\n # momentum\n self.m_dx = self.beta_1 * self.m_dx + (1 - self.beta_1) * delta_x\n\n # rms\n self.v_dx = self.beta_2 * self.v_dx + (1 - self.beta_2) * (delta_x**2)\n\n # bias\n m_dw_corr = self.m_dx / (1 - self.beta_1**niter)\n v_dw_corr = self.v_dx / (1 - self.beta_2**niter)\n\n # update\n x = x - self.alpha * (m_dw_corr / (np.sqrt(v_dw_corr) + self.epsilon))\n\n return x\n\n def optimize(self, func, jac, x_0, max_iter, loss_converged):\n \"\"\"\n Optimize function for max. iterations.\n\n :param func: A callable returning the function value.\n :param jac: A callable returning the Jacobian value.\n :param x_0: Initial value.\n :param max_iter: Number of optimisation iterations.\n :param loss_converged: Target loss.\n :return: Optimized value.\n \"\"\"\n\n num_iter = 1\n converged = False\n\n while not converged and num_iter <= max_iter:\n\n delta_x = jac(x_0)\n\n x_0 = self.update(num_iter, x=x_0, delta_x=delta_x)\n\n loss = func(x_0)\n\n if loss < loss_converged:\n converged = True\n\n num_iter += 1\n\n return x_0\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/summary_writer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module defines and implements the summary writers for TensorBoard output.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom math import sqrt\n\nimport numpy as np\n\n\nclass SummaryWriter(ABC):\n \"\"\"\n This abstract base class defines the API for summary writers.\n \"\"\"\n\n def __init__(self, summary_writer: str | bool):\n \"\"\"\n Create summary writer.\n\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n \"\"\"\n self._summary_writer_arg = summary_writer\n self._init_counter = 0\n\n self._init_summary_writer(summary_writer, init_counter=0)\n\n @property\n def summary_writer(self):\n \"\"\"\n Return the TensorBoardX summary writer instance.\n \"\"\"\n return self._summary_writer\n\n @abstractmethod\n def update(\n self, batch_id, global_step, grad=None, patch=None, estimator=None, x=None, y=None, targeted=False, **kwargs\n ):\n \"\"\"\n Update the summary writer.\n\n :param batch_id: ID of the current mini-batch.\n :param global_step: Global iteration step.\n :param grad: Loss gradients.\n :param patch: Adversarial patch.\n :param estimator: The estimator to evaluate or calculate gradients of `grad` is None to obtain new metrics.\n :param x: Input data.\n :param y: True or target labels.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n \"\"\"\n raise NotImplementedError\n\n def _init_summary_writer(self, summary_writer, init_counter):\n \"\"\"\n Initialise the summary writer.\n\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n \"\"\"\n from tensorboardX import SummaryWriter as SummaryWriterTbx\n\n if isinstance(summary_writer, str):\n comment = f\"generate-{init_counter}\"\n logdir = summary_writer + \"/\" + comment\n self._summary_writer = SummaryWriterTbx(logdir=logdir)\n else:\n comment = f\"-generate-{init_counter}\"\n self._summary_writer = SummaryWriterTbx(comment=comment)\n\n def reset(self):\n \"\"\"\n Flush and reset the summary writer.\n \"\"\"\n self.summary_writer.flush()\n self._init_counter += 1\n self._init_summary_writer(self._summary_writer_arg, init_counter=self._init_counter)\n\n\nclass SummaryWriterDefault(SummaryWriter):\n \"\"\"\n Implementation of the default ART Summary Writer.\n \"\"\"\n\n def __init__(\n self,\n summary_writer: str | bool,\n ind_1: bool = False,\n ind_2: bool = False,\n ind_3: bool = False,\n ind_4: bool = False,\n ):\n super().__init__(summary_writer=summary_writer)\n\n self.ind_1 = ind_1\n self.ind_2 = ind_2\n self.ind_3 = ind_3\n self.ind_4 = ind_4\n\n self.loss = None\n self.loss_prev: dict[str, np.ndarray] = {}\n self.losses: dict[str, list[np.ndarray]] = {}\n\n self.i_3: dict[str, np.ndarray] = {}\n self.i_4: dict[str, np.ndarray] = {}\n\n def update(\n self,\n batch_id: int,\n global_step: int,\n grad: np.ndarray | None = None,\n patch: np.ndarray | None = None,\n estimator=None,\n x: np.ndarray | None = None,\n y: np.ndarray | None = None,\n targeted: bool = False,\n **kwargs,\n ):\n \"\"\"\n Update the summary writer.\n\n :param batch_id: ID of the current mini-batch.\n :param global_step: Global iteration step.\n :param grad: Loss gradients.\n :param patch: Adversarial patch.\n :param estimator: The estimator to evaluate or calculate gradients of `grad` is None to obtain new metrics.\n :param x: Input data.\n :param y: True or target labels.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n \"\"\"\n\n # Gradients\n if grad is not None:\n\n l_1 = np.linalg.norm(grad.reshape(grad.shape[0], -1), axis=1, ord=1)\n self.summary_writer.add_scalars(\n f\"gradients/norm-L1/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(l_1)},\n global_step=global_step,\n )\n\n l_2 = np.linalg.norm(grad.reshape(grad.shape[0], -1), axis=1, ord=2)\n self.summary_writer.add_scalars(\n f\"gradients/norm-L2/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(l_2)},\n global_step=global_step,\n )\n\n l_inf = np.linalg.norm(grad.reshape(grad.shape[0], -1), axis=1, ord=np.inf)\n self.summary_writer.add_scalars(\n f\"gradients/norm-Linf/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(l_inf)},\n global_step=global_step,\n )\n\n # Patch\n if patch is not None:\n if patch.shape[2] in [1, 3, 4]:\n patch = np.transpose(patch, (2, 0, 1))\n self.summary_writer.add_image(\n \"patch\",\n patch,\n global_step=global_step,\n )\n\n # Losses\n if estimator is not None and x is not None and y is not None:\n if hasattr(estimator, \"compute_losses\"):\n losses = estimator.compute_losses(x=x, y=y)\n\n for key, value in losses.items():\n if np.ndim(value) == 0:\n self.summary_writer.add_scalar(\n f\"loss/{key}/batch-{batch_id}\",\n value,\n global_step=global_step,\n )\n else:\n self.summary_writer.add_scalars(\n f\"loss/{key}/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(value)},\n global_step=global_step,\n )\n\n elif hasattr(estimator, \"compute_loss\"):\n loss = estimator.compute_loss(x=x, y=y)\n\n if np.ndim(loss) == 0:\n self.summary_writer.add_scalar(\n f\"loss/batch-{batch_id}\",\n loss,\n global_step=global_step,\n )\n else:\n self.summary_writer.add_scalars(\n f\"loss/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(loss)},\n global_step=global_step,\n )\n\n # Indicators of Attack Failure by Pintor et al. (2021)\n # Paper link: https://arxiv.org/abs/2106.09947\n if self.ind_1: # Silent Success\n from art.estimators.classification.classifier import ClassifierMixin\n\n if isinstance(estimator, ClassifierMixin):\n if y is not None:\n y_pred = estimator.predict(x) # type: ignore\n self.i_1 = np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)\n self.summary_writer.add_scalars(\n f\"Attack Failure Indicator 1 - Silent Success/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(self.i_1)},\n global_step=global_step,\n )\n else:\n raise ValueError(\"Attack Failure Indicator 1 requires `y`.\")\n else:\n raise ValueError(\n \"Attack Failure Indicator 1 is only supported for classification, for the current \"\n \"`estimator` set `ind_1=False`.\"\n )\n\n if self.ind_2: # Break-point Angle\n losses = estimator.compute_loss(x=x, y=y)\n\n if str(batch_id) not in self.losses:\n self.losses[str(batch_id)] = []\n\n self.losses[str(batch_id)].append(losses)\n\n self.i_2 = np.ones_like(losses)\n\n if len(self.losses[str(batch_id)]) >= 3:\n\n delta_loss = self.losses[str(batch_id)][0] - self.losses[str(batch_id)][-1]\n delta_step = global_step\n\n side_b = sqrt(2.0)\n\n for i_step in range(1, len(self.losses[str(batch_id)]) - 1):\n\n side_a = np.sqrt(\n np.square((self.losses[str(batch_id)][0] - self.losses[str(batch_id)][i_step]) / delta_loss)\n + (i_step / delta_step) ** 2\n )\n side_c = np.sqrt(\n np.square((self.losses[str(batch_id)][i_step] - self.losses[str(batch_id)][-1]) / delta_loss)\n + ((delta_step - i_step) / delta_step) ** 2\n )\n cos_beta = -(side_b**2 - (side_a**2 + side_c**2)) / (2 * side_a * side_c)\n\n i_2_step = 1 - np.abs(cos_beta)\n self.i_2 = np.minimum(self.i_2, i_2_step)\n\n if np.ndim(self.i_2) == 0:\n self.summary_writer.add_scalar(\n f\"Attack Failure Indicator 2 - Break-point Angle/batch-{batch_id}\",\n self.i_2,\n global_step=global_step,\n )\n else:\n self.summary_writer.add_scalars(\n f\"Attack Failure Indicator 2 - Break-point Angle/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(self.i_2)},\n global_step=global_step,\n )\n\n if self.ind_3: # Diverging (Increasing) Loss\n loss = estimator.compute_loss(x=x, y=y)\n\n if str(batch_id) in self.i_3:\n if targeted:\n if isinstance(loss, float):\n loss_add = loss\n else:\n loss_add = loss[loss > self.loss_prev[str(batch_id)]]\n self.i_3[str(batch_id)][loss > self.loss_prev[str(batch_id)]] += loss_add\n else:\n if isinstance(loss, float):\n loss_add = loss\n else:\n loss_add = loss[loss < self.loss_prev[str(batch_id)]]\n self.i_3[str(batch_id)][loss < self.loss_prev[str(batch_id)]] += loss_add\n else:\n self.i_3[str(batch_id)] = np.zeros_like(loss)\n\n if np.ndim(self.i_3[str(batch_id)]) == 0:\n self.summary_writer.add_scalar(\n f\"Attack Failure Indicator 3 - Diverging Loss/batch-{batch_id}\",\n self.i_3[str(batch_id)],\n global_step=global_step,\n )\n else:\n self.summary_writer.add_scalars(\n f\"Attack Failure Indicator 3 - Diverging Loss/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(self.i_3[str(batch_id)])},\n global_step=global_step,\n )\n\n self.loss_prev[str(batch_id)] = loss\n\n if self.ind_4: # Zero Gradients\n\n threshold = 0.0\n\n if grad is not None:\n\n if str(batch_id) not in self.i_4:\n self.i_4[str(batch_id)] = np.zeros(grad.shape[0])\n\n self.i_4[str(batch_id)][\n np.linalg.norm(grad.reshape(grad.shape[0], -1), axis=1, ord=2) <= threshold\n ] += 1\n\n self.summary_writer.add_scalars(\n f\"Attack Failure Indicator 4 - Zero Gradients/batch-{batch_id}\",\n {str(i): v for i, v in enumerate(self.i_4[str(batch_id)] / global_step)},\n global_step=global_step,\n )\n else:\n raise ValueError(\"Attack Failure Indicator 4 requires `grad`.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule providing convenience functions.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nimport math\nimport os\nimport shutil\nimport sys\nimport tarfile\nimport warnings\nimport zipfile\nfrom functools import wraps\nfrom inspect import signature\nfrom typing import TYPE_CHECKING, Optional, Tuple, Union\n\nimport numpy as np\nimport six\nfrom scipy.special import gammainc\nfrom tqdm.auto import tqdm\n\nfrom art import config\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\n# ------------------------------------------------------------------------------------------------- CONSTANTS AND TYPES\n\n\nDATASET_TYPE = Tuple[ # pylint: disable=invalid-name\n Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray], float, float\n]\nCLIP_VALUES_TYPE = Tuple[Union[int, float, np.ndarray], Union[int, float, np.ndarray]] # pylint: disable=invalid-name\n\nif TYPE_CHECKING:\n # pylint: disable=cyclic-import\n from art.defences.preprocessor.preprocessor import Preprocessor\n\n PREPROCESSING_TYPE = Optional[ # pylint: disable=invalid-name\n Union[\n Tuple[Union[int, float, np.ndarray], Union[int, float, np.ndarray]], Preprocessor, Tuple[Preprocessor, ...]\n ]\n ]\n\n from art.estimators.classification.blackbox import BlackBoxClassifier\n from art.estimators.classification.catboost import CatBoostARTClassifier\n from art.estimators.classification.classifier import (\n Classifier,\n ClassifierClassLossGradients,\n ClassifierDecisionTree,\n ClassifierLossGradients,\n ClassifierNeuralNetwork,\n )\n from art.estimators.classification.detector_classifier import DetectorClassifier\n from art.estimators.classification.ensemble import EnsembleClassifier\n from art.estimators.classification.GPy import GPyGaussianProcessClassifier\n from art.estimators.classification.keras import KerasClassifier\n from art.experimental.estimators.classification.jax import JaxClassifier\n from art.estimators.classification.lightgbm import LightGBMClassifier\n from art.estimators.classification.pytorch import PyTorchClassifier\n from art.estimators.classification.query_efficient_bb import QueryEfficientGradientEstimationClassifier\n from art.estimators.classification.scikitlearn import (\n ScikitlearnAdaBoostClassifier,\n ScikitlearnBaggingClassifier,\n ScikitlearnClassifier,\n ScikitlearnDecisionTreeClassifier,\n ScikitlearnDecisionTreeRegressor,\n ScikitlearnExtraTreeClassifier,\n ScikitlearnExtraTreesClassifier,\n ScikitlearnGradientBoostingClassifier,\n ScikitlearnLogisticRegression,\n ScikitlearnRandomForestClassifier,\n ScikitlearnSVC,\n )\n from art.estimators.classification.tensorflow import TensorFlowV2Classifier\n from art.estimators.classification.xgboost import XGBoostClassifier\n from art.estimators.certification.deep_z import PytorchDeepZ\n from art.estimators.certification.interval import PyTorchIBPClassifier\n from art.estimators.certification.derandomized_smoothing.ablators import BlockAblator, ColumnAblator\n from art.estimators.generation.tensorflow import TensorFlowV2Generator\n from art.estimators.object_detection.object_detector import ObjectDetector\n from art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\n from art.estimators.object_detection.pytorch_faster_rcnn import PyTorchFasterRCNN\n from art.estimators.object_detection.pytorch_yolo import PyTorchYolo\n from art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\n from art.estimators.pytorch import PyTorchEstimator\n from art.estimators.keras import KerasEstimator\n from art.estimators.regression.scikitlearn import ScikitlearnRegressor\n from art.estimators.regression.pytorch import PyTorchRegressor\n from art.estimators.regression.keras import KerasRegressor\n from art.estimators.regression.blackbox import BlackBoxRegressor\n from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\n from art.estimators.tensorflow import TensorFlowV2Estimator\n\n CLASSIFIER_LOSS_GRADIENTS_TYPE = Union[ # pylint: disable=invalid-name\n ClassifierLossGradients,\n EnsembleClassifier,\n GPyGaussianProcessClassifier,\n KerasClassifier,\n JaxClassifier,\n PyTorchClassifier,\n ScikitlearnLogisticRegression,\n ScikitlearnSVC,\n TensorFlowV2Classifier,\n QueryEfficientGradientEstimationClassifier,\n ]\n\n CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE = Union[ # pylint: disable=invalid-name\n ClassifierClassLossGradients,\n EnsembleClassifier,\n GPyGaussianProcessClassifier,\n KerasClassifier,\n PyTorchClassifier,\n ScikitlearnLogisticRegression,\n ScikitlearnSVC,\n TensorFlowV2Classifier,\n ]\n\n CLASSIFIER_NEURALNETWORK_TYPE = Union[ # pylint: disable=invalid-name\n ClassifierNeuralNetwork,\n DetectorClassifier,\n EnsembleClassifier,\n KerasClassifier,\n PyTorchClassifier,\n TensorFlowV2Classifier,\n ]\n\n CLASSIFIER_DECISION_TREE_TYPE = Union[ # pylint: disable=invalid-name\n ClassifierDecisionTree,\n LightGBMClassifier,\n ScikitlearnDecisionTreeClassifier,\n ScikitlearnExtraTreesClassifier,\n ScikitlearnGradientBoostingClassifier,\n ScikitlearnRandomForestClassifier,\n XGBoostClassifier,\n ]\n\n CLASSIFIER_TYPE = Union[ # pylint: disable=invalid-name\n Classifier,\n BlackBoxClassifier,\n CatBoostARTClassifier,\n DetectorClassifier,\n EnsembleClassifier,\n GPyGaussianProcessClassifier,\n KerasClassifier,\n JaxClassifier,\n LightGBMClassifier,\n PyTorchClassifier,\n ScikitlearnClassifier,\n ScikitlearnDecisionTreeClassifier,\n ScikitlearnExtraTreeClassifier,\n ScikitlearnAdaBoostClassifier,\n ScikitlearnBaggingClassifier,\n ScikitlearnExtraTreesClassifier,\n ScikitlearnGradientBoostingClassifier,\n ScikitlearnRandomForestClassifier,\n ScikitlearnLogisticRegression,\n ScikitlearnSVC,\n TensorFlowV2Classifier,\n XGBoostClassifier,\n CLASSIFIER_NEURALNETWORK_TYPE,\n ]\n\n GENERATOR_TYPE = Union[TensorFlowV2Generator] # pylint: disable=invalid-name\n\n REGRESSOR_TYPE = Union[ # pylint: disable=invalid-name\n ScikitlearnRegressor, ScikitlearnDecisionTreeRegressor, PyTorchRegressor, KerasRegressor, BlackBoxRegressor\n ]\n\n OBJECT_DETECTOR_TYPE = Union[ # pylint: disable=invalid-name\n ObjectDetector,\n PyTorchObjectDetector,\n PyTorchFasterRCNN,\n PyTorchYolo,\n TensorFlowV2FasterRCNN,\n ]\n\n SPEECH_RECOGNIZER_TYPE = Union[PyTorchDeepSpeech,] # pylint: disable=invalid-name\n\n PYTORCH_ESTIMATOR_TYPE = Union[ # pylint: disable=invalid-name\n PyTorchClassifier,\n PyTorchDeepSpeech,\n PyTorchEstimator,\n PyTorchObjectDetector,\n PyTorchFasterRCNN,\n PyTorchYolo,\n PyTorchRegressor,\n ]\n\n PYTORCH_OBJECT_DETECTOR_TYPE = Union[PyTorchObjectDetector] # pylint: disable=invalid-name\n\n KERAS_ESTIMATOR_TYPE = Union[ # pylint: disable=invalid-name\n KerasClassifier,\n KerasEstimator,\n KerasRegressor,\n ]\n\n TENSORFLOWV2_ESTIMATOR_TYPE = Union[ # pylint: disable=invalid-name\n TensorFlowV2Classifier,\n TensorFlowV2Estimator,\n TensorFlowV2FasterRCNN,\n ]\n\n ESTIMATOR_TYPE = Union[ # pylint: disable=invalid-name\n CLASSIFIER_TYPE,\n REGRESSOR_TYPE,\n OBJECT_DETECTOR_TYPE,\n SPEECH_RECOGNIZER_TYPE,\n PYTORCH_ESTIMATOR_TYPE,\n KERAS_ESTIMATOR_TYPE,\n TENSORFLOWV2_ESTIMATOR_TYPE,\n ]\n\n CLONABLE = Union[ # pylint: disable=invalid-name\n ScikitlearnClassifier,\n PyTorchClassifier,\n TensorFlowV2Classifier,\n KerasEstimator,\n PyTorchRegressor,\n ScikitlearnRegressor,\n XGBoostClassifier,\n ]\n\n ABLATOR_TYPE = Union[BlockAblator, ColumnAblator] # pylint: disable=invalid-name\n\n CERTIFIER_TYPE = Union[PytorchDeepZ] # pylint: disable=invalid-name\n IBP_CERTIFIER_TYPE = Union[PyTorchIBPClassifier] # pylint: disable=invalid-name\n\n# --------------------------------------------------------------------------------------------------------- DEPRECATION\n\n\nclass _Deprecated:\n \"\"\"\n Create Deprecated() singleton object.\n \"\"\"\n\n _instance = None\n\n def __new__(cls):\n if _Deprecated._instance is None:\n _Deprecated._instance = object.__new__(cls)\n return _Deprecated._instance\n\n\nDeprecated = _Deprecated()\n\n\ndef deprecated(end_version: str, *, reason: str = \"\", replaced_by: str = \"\") -> Callable:\n \"\"\"\n Deprecate a function or method and raise a `DeprecationWarning`.\n\n The `@deprecated` decorator is used to deprecate functions and methods. Several cases are supported. For example\n one can use it to deprecate a function that has become redundant or rename a function. The following code examples\n provide different use cases of how to use decorator.\n\n .. code-block:: python\n\n @deprecated(\"0.1.5\", replaced_by=\"sum\")\n def simple_addition(a, b):\n return a + b\n\n :param end_version: Release version of removal.\n :param reason: Additional deprecation reason.\n :param replaced_by: Function that replaces deprecated function.\n \"\"\"\n\n def decorator(function):\n reason_msg = \"\\n\" + reason if reason else reason\n replaced_msg = f\" It will be replaced by '{replaced_by}'.\" if replaced_by else replaced_by\n deprecated_msg = (\n f\"Function '{function.__name__}' is deprecated and will be removed in future release {end_version}.\"\n )\n\n @wraps(function)\n def wrapper(*args, **kwargs):\n warnings.simplefilter(\"always\", category=DeprecationWarning)\n warnings.warn(\n deprecated_msg + replaced_msg + reason_msg,\n category=DeprecationWarning,\n stacklevel=2,\n )\n warnings.simplefilter(\"default\", category=DeprecationWarning)\n return function(*args, **kwargs)\n\n return wrapper\n\n return decorator\n\n\ndef deprecated_keyword_arg(identifier: str, end_version: str, *, reason: str = \"\", replaced_by: str = \"\") -> Callable:\n \"\"\"\n Deprecate a keyword argument and raise a `DeprecationWarning`.\n\n The `@deprecated_keyword_arg` decorator is used to deprecate keyword arguments. The deprecated keyword argument must\n default to `Deprecated`. Several use cases are supported. For example one can use it to rename a keyword\n identifier. The following code examples provide different use cases of how to use the decorator.\n\n .. code-block:: python\n\n @deprecated_keyword_arg(\"print\", \"1.1.0\", replaced_by=\"verbose\")\n def simple_addition(a, b, print=Deprecated, verbose=False):\n if verbose:\n print(a + b)\n return a + b\n\n @deprecated_keyword_arg(\"verbose\", \"1.1.0\")\n def simple_addition(a, b, verbose=Deprecated):\n return a + b\n\n :param identifier: Keyword identifier.\n :param end_version: Release version of removal.\n :param reason: Additional deprecation reason.\n :param replaced_by: Function that replaces deprecated function.\n \"\"\"\n\n def decorator(function):\n reason_msg = \"\\n\" + reason if reason else reason\n replaced_msg = f\" It will be replaced by '{replaced_by}'.\" if replaced_by else replaced_by\n deprecated_msg = (\n f\"Keyword argument '{identifier}' in '{function.__name__}' is deprecated and will be removed in\"\n f\" future release {end_version}.\"\n )\n\n @wraps(function)\n def wrapper(*args, **kwargs):\n params = signature(function).bind(*args, **kwargs)\n params.apply_defaults()\n\n if params.signature.parameters[identifier].default is not Deprecated:\n raise ValueError(\"Deprecated keyword argument must default to the Decorator singleton.\")\n if replaced_by != \"\" and replaced_by not in params.arguments:\n raise ValueError(\"Deprecated keyword replacement not found in function signature.\")\n\n if params.arguments[identifier] is not Deprecated:\n warnings.simplefilter(\"always\", category=DeprecationWarning)\n warnings.warn(deprecated_msg + replaced_msg + reason_msg, category=DeprecationWarning, stacklevel=2)\n warnings.simplefilter(\"default\", category=DeprecationWarning)\n return function(*args, **kwargs)\n\n return wrapper\n\n return decorator\n\n\n# ----------------------------------------------------------------------------------------------------- MATH OPERATIONS\n\n\ndef projection_l1_1(values: np.ndarray, eps: int | float | np.ndarray) -> np.ndarray:\n \"\"\"\n This function computes the orthogonal projections of a batch of points on L1-balls of given radii\n The batch size is m = values.shape[0]. The points are flattened to dimension\n n = np.prod(value.shape[1:]). This is required to facilitate sorting.\n\n If a[0] <= ... <= a[n-1], then the projection can be characterized using the largest j such that\n a[j+1] +...+ a[n-1] - a[j]*(n-j-1) >= eps. The ith coordinate of projection is equal to 0\n if i=0,...,j.\n\n :param values: A batch of m points, each a ndarray\n :param eps: The radii of the respective L1-balls\n :return: projections\n \"\"\"\n # pylint: disable=invalid-name\n\n shp = values.shape\n a = values.copy()\n n = np.prod(a.shape[1:])\n m = a.shape[0]\n a = a.reshape((m, n))\n sgns = np.sign(a)\n a = np.abs(a)\n\n a_argsort = a.argsort(axis=1)\n a_sorted = np.zeros((m, n))\n for i in range(m):\n a_sorted[i, :] = a[i, a_argsort[i, :]]\n a_argsort_inv = a.argsort(axis=1).argsort(axis=1)\n mat = np.zeros((m, 2))\n\n # if a_sorted[i, n-1] >= a_sorted[i, n-2] + eps, then the projection is [0,...,0,eps]\n done = early_done = False\n active = np.array([1] * m)\n after_vec = np.zeros((m, n))\n proj = a_sorted.copy()\n j = n - 2\n while j >= 0:\n mat[:, 0] += a_sorted[:, j + 1] # = sum(a_sorted[: i] : i = j + 1,...,n-1\n mat[:, 1] = a_sorted[:, j] * (n - j - 1) + eps\n # Find the max in each problem max{ sum{a_sorted[:, i] : i=j+1,..,n-1} , a_sorted[:, j] * (n-j-1) + eps }\n row_maxes = np.max(mat, axis=1)\n # Set to 1 if max > a_sorted[:, j] * (n-j-1) + eps > sum ; otherwise, set to 0\n ind_set = np.sign(np.sign(row_maxes - mat[:, 0]))\n # ind_set = ind_set.reshape((m, 1))\n # Multiplier for activation\n act_multiplier = (1 - ind_set) * active\n act_multiplier = np.transpose([np.transpose(act_multiplier)] * n)\n # if done, the projection is supported by the current indices j+1,..,n-1 and the amount by which each\n # has to be reduced is delta\n delta = (mat[:, 0] - eps) / (n - j - 1)\n # The vector of reductions\n delta_vec = np.transpose(np.array([delta] * (n - j - 1)))\n # The sub-vectors: a_sorted[:, (j+1):]\n a_sub = a_sorted[:, int(j + 1) :]\n # After reduction by delta_vec\n a_after = a_sub - delta_vec\n after_vec[:, int(j + 1) :] = a_after\n proj += act_multiplier * (after_vec - proj)\n active = active * ind_set\n if sum(active) == 0:\n done = early_done = True\n break\n j -= 1\n if not early_done:\n delta = (mat[:, 0] + a_sorted[:, 0] - eps) / n\n ind_set = np.sign(np.maximum(delta, 0))\n act_multiplier = ind_set * active\n act_multiplier = np.transpose([np.transpose(act_multiplier)] * n)\n delta_vec = np.transpose(np.array([delta] * n))\n a_after = a_sorted - delta_vec\n proj += act_multiplier * (a_after - proj)\n done = True\n if not done:\n proj = active * (a_sorted - proj)\n\n for i in range(m):\n proj[i, :] = proj[i, a_argsort_inv[i, :]]\n\n proj = sgns * proj\n proj = proj.reshape(shp)\n\n return proj\n\n\ndef projection_l1_2(values: np.ndarray, eps: int | float | np.ndarray) -> np.ndarray:\n \"\"\"\n This function computes the orthogonal projections of a batch of points on L1-balls of given radii\n The batch size is m = values.shape[0]. The points are flattened to dimension\n n = np.prod(value.shape[1:]). This is required to facilitate sorting.\n\n Starting from a vector a = (a1,...,an) such that a1 >= ... >= an >= 0, a1 + ... + an > 1,\n we first move to a' = a - (t,...,t) such that either a1 + ... + an >= 1 , an >= 0,\n and min( a1 + ... + an - nt - 1, an -t ) = 0. This means t = min( (a1 + ... + an - 1)/n, an).\n If t = (a1 + ... + an - 1)/n , then a' is the desired projection. Otherwise, the problem is reduced to\n finding the projection of (a1 - t, ... , a{n-1} - t ).\n\n :param values: A batch of m points, each a ndarray\n :param eps: The radii of the respective L1-balls\n :return: projections\n \"\"\"\n # pylint: disable=invalid-name\n shp = values.shape\n a = values.copy()\n n = np.prod(a.shape[1:])\n m = a.shape[0]\n a = a.reshape((m, n))\n sgns = np.sign(a)\n a = np.abs(a)\n a_argsort = a.argsort(axis=1)\n a_sorted = np.zeros((m, n))\n for i in range(m):\n a_sorted[i, :] = a[i, a_argsort[i, :]]\n\n a_argsort_inv = a.argsort(axis=1).argsort(axis=1)\n row_sums = np.sum(a, axis=1)\n mat = np.zeros((m, 2))\n mat0 = np.zeros((m, 2))\n a_var = a_sorted.copy()\n for j in range(n):\n mat[:, 0] = (row_sums - eps) / (n - j)\n mat[:, 1] = a_var[:, j]\n mat0[:, 1] = np.min(mat, axis=1)\n min_t = np.max(mat0, axis=1)\n if np.max(min_t) < 1e-8:\n continue\n row_sums = row_sums - a_var[:, j] * (n - j)\n a_var[:, (j + 1) :] = a_var[:, (j + 1) :] - np.matmul(min_t.reshape((m, 1)), np.ones((1, n - j - 1)))\n a_var[:, j] = a_var[:, j] - min_t\n proj = np.zeros((m, n))\n for i in range(m):\n proj[i, :] = a_var[i, a_argsort_inv[i, :]]\n\n proj = sgns * proj\n proj = proj.reshape(shp)\n return proj\n\n\ndef projection(\n values: np.ndarray,\n eps: int | float | np.ndarray,\n norm_p: int | float | str,\n *,\n suboptimal: bool = True,\n) -> np.ndarray:\n \"\"\"\n Project `values` on the L_p norm ball of size `eps`.\n\n :param values: Array of perturbations to clip.\n :param eps: If a scalar, the norm of the L_p ball onto which samples are projected. Equivalently in general, can be\n any array of non-negatives broadcastable with `values`, and the projection occurs onto the unit ball\n for the weighted L_{p, w} norm with `w = 1 / eps`. Currently, for any given sample, non-uniform weights\n are only supported with infinity norm. Example: To specify sample-wise scalar, you can provide\n `eps.shape = (n_samples,) + (1,) * values[0].ndim`.\n :param norm_p: Lp norm to use for clipping, with `norm_p > 0`. Only 1, 2, `np.inf` and \"inf\" are currently\n supported with `suboptimal=False` for now.\n :param suboptimal: If `True` simply projects by rescaling to Lp ball. Fast but may be suboptimal for `norm_p != 2`.\n Ignored when `norm_p in [np.inf, \"inf\"]` because optimal solution is fast. Defaults to `True`.\n :return: Values of `values` after projection.\n \"\"\"\n norm = np.inf if norm_p == \"inf\" else float(norm_p)\n assert norm > 0\n\n values_tmp = values.reshape(len(values), -1) # (n_samples, d)\n\n eps = np.broadcast_to(eps, values.shape)\n eps = eps.reshape(len(eps), -1) # (n_samples, d)\n assert np.all(eps >= 0)\n if norm != np.inf and not np.all(eps == eps[:, [0]]):\n raise NotImplementedError(\n \"Projection onto the weighted L_p ball is currently not supported with finite `norm_p`.\"\n )\n\n if (suboptimal or norm == 2) and norm != np.inf: # Simple rescaling\n values_norm = np.linalg.norm(values_tmp, ord=norm, axis=1, keepdims=True) # (n_samples, 1)\n with np.errstate(divide=\"ignore\"):\n values_tmp = values_tmp * np.where(values_norm, np.minimum(1, eps / values_norm), 0)\n else: # Optimal\n if norm == np.inf: # Easy exact case\n values_tmp = np.sign(values_tmp) * np.minimum(np.abs(values_tmp), eps)\n elif norm == 1: # Harder exact case\n projection_l1 = projection_l1_1 if values_tmp.shape[1] > 29 else projection_l1_2 # From empirical tests\n values_tmp = projection_l1(values_tmp, eps[:, 0])\n elif norm > 1: # Convex optim\n raise NotImplementedError(\n 'Values of `norm_p > 1` different from 2, `np.inf` and \"inf\" are currently not supported with '\n \"`suboptimal=False`.\"\n )\n else: # Non-convex optim\n raise NotImplementedError(\"Values of `norm_p < 1` are currently not supported with `suboptimal=False`.\")\n\n values = values_tmp.reshape(values.shape).astype(values.dtype)\n return values\n\n\ndef random_sphere(\n nb_points: int,\n nb_dims: int,\n radius: int | float | np.ndarray,\n norm: int | float | str,\n) -> np.ndarray:\n \"\"\"\n Generate uniformly at random `m x n`-dimension points in the `norm`-norm ball with radius `radius` and centered\n around 0.\n\n :param nb_points: Number of random data points.\n :param nb_dims: Dimensionality of the sphere.\n :param radius: Radius of the sphere.\n :param norm: Current support: 1, 2, np.inf, \"inf\".\n :return: The generated random sphere.\n \"\"\"\n if norm == 1:\n if isinstance(radius, np.ndarray):\n raise NotImplementedError(\n \"The parameter `radius` of type `np.ndarray` is not supported to use with norm 1.\"\n )\n\n var_u = np.random.uniform(size=(nb_points, nb_dims))\n var_v = np.sort(var_u)\n v_pre = np.concatenate((np.zeros((nb_points, 1)), var_v[:, : nb_dims - 1]), axis=-1)\n x = var_v - v_pre\n res = radius * x * np.random.choice([-1, 1], (nb_points, nb_dims))\n\n elif norm == 2:\n if isinstance(radius, np.ndarray):\n raise NotImplementedError(\n \"The parameter `radius` of type `np.ndarray` is not supported to use with norm 2.\"\n )\n\n a_tmp = np.random.randn(nb_points, nb_dims)\n s_2 = np.sum(a_tmp**2, axis=1)\n base = gammainc(nb_dims / 2.0, s_2 / 2.0) ** (1 / nb_dims) * radius / np.sqrt(s_2)\n res = a_tmp * (np.tile(base, (nb_dims, 1))).T\n\n elif norm in [np.inf, \"inf\"]:\n if isinstance(radius, np.ndarray):\n radius = radius * np.ones(shape=(nb_points, nb_dims))\n\n res = np.random.uniform(-radius, radius, (nb_points, nb_dims))\n\n else:\n raise NotImplementedError(f\"Norm {norm} not supported\")\n\n return res\n\n\ndef uniform_sample_from_sphere_or_ball(\n nb_points: int,\n nb_dims: int,\n radius: int | float | np.ndarray,\n sample_space: str = \"ball\",\n norm: int | float | str = 2,\n) -> np.ndarray:\n \"\"\"\n Generate a sample of distributed independently and uniformly on the sphere (with respect to the given\n norm) in dimension with radius and centered at the origin. Note that the sphere is the boundary\n of the ball, i.e., every point on the sphere has the same distance to the origin.\n\n :param nb_points: Number of random data points\n :param nb_dims: Dimensionality of the sphere\n :param radius: Radius of the sphere\n :param sample_space: One of 'b', 's', 'sphere', 'ball'\n :param norm: Current support: 1, 2, np.inf, \"inf\"\n :return: The sampled points from the sphere (i.e., boundary of the ball)\n \"\"\"\n assert sample_space in [\"b\", \"s\", \"sphere\", \"ball\"]\n\n if norm == 1:\n if sample_space in [\"s\", \"sphere\"]:\n y = np.random.exponential(1, (nb_points, nb_dims))\n sums = np.sum(y, axis=1)\n scal = np.outer(sums, np.ones(nb_dims))\n y = y / scal\n else:\n y = np.random.exponential(1, (nb_points, nb_dims + 1))\n sums = np.sum(y, axis=1)\n scal = np.outer(sums, np.ones(nb_dims + 1))\n y = y / scal\n y = y[:, :nb_dims]\n\n y = y * np.random.choice([-1, 1], (nb_points, nb_dims))\n if type(radius) in [int, float]:\n res = y * radius\n else:\n radii = np.outer(radius, np.ones(nb_dims))\n res = y * radii\n\n elif norm == 2:\n x = np.random.normal(0.0, 1.0, (nb_points, nb_dims))\n scal = radius / np.sqrt(np.sum(x * x, axis=1))\n scal = np.transpose(np.array(list(scal) * nb_dims).reshape((nb_dims, nb_points)))\n res = x * scal\n if sample_space in [\"b\", \"ball\"]:\n rnd = np.random.rand(nb_points)\n scal = np.float_power(rnd, 1 / nb_dims)\n scal = np.outer(scal, np.ones(nb_dims))\n res = res * scal\n\n elif norm in [np.inf, \"inf\"]:\n if sample_space in [\"b\", \"ball\"]:\n x = np.random.uniform(-1.0, 1.0, (nb_points, nb_dims))\n else:\n x = np.random.uniform(0, 1.0, (nb_points, nb_dims))\n rnd = np.random.random((nb_points, nb_dims))\n maxes = np.max(rnd, axis=1)\n maxes = np.outer(maxes, np.ones(nb_dims))\n x = np.maximum((rnd >= maxes), x) * np.random.choice([-1, 1], (nb_points, nb_dims))\n if type(radius) in [int, float]:\n res = x * radius\n else:\n radii = np.outer(radius, np.ones(nb_dims))\n res = x * radii\n else:\n raise NotImplementedError(f\"Norm {norm} not supported\")\n\n return res\n\n\ndef original_to_tanh(\n x_original: np.ndarray,\n clip_min: float | np.ndarray,\n clip_max: float | np.ndarray,\n tanh_smoother: float = 0.999999,\n) -> np.ndarray:\n \"\"\"\n Transform input from original to tanh space.\n\n :param x_original: An array with the input to be transformed.\n :param clip_min: Minimum clipping value.\n :param clip_max: Maximum clipping value.\n :param tanh_smoother: Scalar for multiplying arguments of arctanh to avoid division by zero.\n :return: An array holding the transformed input.\n \"\"\"\n x_tanh = np.clip(x_original, clip_min, clip_max)\n x_tanh = (x_tanh - clip_min) / (clip_max - clip_min)\n x_tanh = np.arctanh(((x_tanh * 2) - 1) * tanh_smoother)\n return x_tanh\n\n\ndef tanh_to_original(\n x_tanh: np.ndarray,\n clip_min: float | np.ndarray,\n clip_max: float | np.ndarray,\n) -> np.ndarray:\n \"\"\"\n Transform input from tanh to original space.\n\n :param x_tanh: An array with the input to be transformed.\n :param clip_min: Minimum clipping value.\n :param clip_max: Maximum clipping value.\n :return: An array holding the transformed input.\n \"\"\"\n return (np.tanh(x_tanh) + 1.0) / 2.0 * (clip_max - clip_min) + clip_min\n\n\n# --------------------------------------------------------------------------------------------------- LABELS OPERATIONS\n\n\ndef to_categorical(labels: Union[np.ndarray, list[float]], nb_classes: int | None = None) -> np.ndarray:\n \"\"\"\n Convert an array of labels to binary class matrix.\n\n :param labels: An array of integer labels of shape `(nb_samples,)`.\n :param nb_classes: The number of classes (possible labels).\n :return: A binary matrix representation of `y` in the shape `(nb_samples, nb_classes)`.\n \"\"\"\n labels = np.array(labels, dtype=int)\n if nb_classes is None:\n nb_classes = np.max(labels) + 1\n categorical = np.zeros((labels.shape[0], nb_classes), dtype=np.float32)\n categorical[np.arange(labels.shape[0]), np.squeeze(labels)] = 1\n return categorical\n\n\ndef float_to_categorical(labels: np.ndarray, nb_classes: int | None = None):\n \"\"\"\n Convert an array of floating point labels to binary class matrix.\n\n :param labels: An array of floating point labels of shape `(nb_samples,)`\n :param nb_classes: The number of classes (possible labels)\n :return: A binary matrix representation of `labels` in the shape `(nb_samples, nb_classes)`\n :rtype: `np.ndarray`\n \"\"\"\n labels = np.array(labels)\n unique = np.unique(labels)\n unique.sort()\n indexes = [np.where(unique == value)[0] for value in labels]\n if nb_classes is None:\n nb_classes = len(unique)\n categorical = np.zeros((labels.shape[0], nb_classes), dtype=np.float32)\n categorical[np.arange(labels.shape[0]), np.squeeze(indexes)] = 1\n return categorical\n\n\ndef floats_to_one_hot(labels: np.ndarray):\n \"\"\"\n Convert a 2D-array of floating point labels to binary class matrix.\n\n :param labels: A 2D-array of floating point labels of shape `(nb_samples, nb_classes)`\n :return: A binary matrix representation of `labels` in the shape `(nb_samples, nb_classes)`\n :rtype: `np.ndarray`\n \"\"\"\n labels = np.array(labels)\n for feature in labels.T:\n unique = np.unique(feature)\n unique.sort()\n for index, value in enumerate(unique):\n feature[feature == value] = index\n return labels.astype(np.float32)\n\n\ndef check_and_transform_label_format(\n labels: np.ndarray, nb_classes: int | None, return_one_hot: bool = True\n) -> np.ndarray:\n \"\"\"\n Check label format and transform to one-hot-encoded labels if necessary. Only supports single-output classification.\n\n :param labels: An array of integer labels of shape `(nb_samples,)`, `(nb_samples, 1)` or `(nb_samples, nb_classes)`.\n :param nb_classes: The number of classes, as an integer. If None the number of classes is determined automatically.\n :param return_one_hot: True if returning one-hot encoded labels, False if returning index labels.\n :return: Labels with shape `(nb_samples, nb_classes)` (one-hot) or `(nb_samples,)` (index).\n \"\"\"\n labels_return = labels\n\n if nb_classes is not None and not isinstance(nb_classes, (int, np.integer)):\n raise TypeError(\"nb_classes that is not an integer is not supported\")\n\n if len(labels.shape) == 2 and labels.shape[1] > 1: # multi-class, one-hot encoded\n if not return_one_hot:\n labels_return = np.argmax(labels, axis=1)\n labels_return = np.expand_dims(labels_return, axis=1)\n elif len(labels.shape) == 2 and labels.shape[1] == 1:\n if nb_classes is None:\n nb_classes = int(np.max(labels) + 1)\n if nb_classes > 2: # multi-class, index labels\n if return_one_hot:\n labels_return = to_categorical(labels, nb_classes)\n else:\n labels_return = np.expand_dims(labels, axis=1)\n elif nb_classes == 2: # binary, index labels\n if return_one_hot:\n labels_return = to_categorical(labels, nb_classes)\n else:\n raise ValueError(\n \"Shape of labels not recognised.\"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, \"\n \"nb_classes)\"\n )\n elif len(labels.shape) == 1: # index labels\n if return_one_hot:\n labels_return = to_categorical(labels, nb_classes)\n else:\n labels_return = np.expand_dims(labels, axis=1)\n else:\n raise ValueError(\n \"Shape of labels not recognised.\"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, \"\n \"nb_classes)\"\n )\n\n return labels_return\n\n\ndef random_targets(labels: np.ndarray, nb_classes: int) -> np.ndarray:\n \"\"\"\n Given a set of correct labels, randomly changes some correct labels to target labels different from the original\n ones. These can be one-hot encoded or integers.\n\n :param labels: The correct labels.\n :param nb_classes: The number of classes for this model.\n :return: An array holding the randomly-selected target classes, one-hot encoded.\n \"\"\"\n if len(labels.shape) > 1:\n labels = np.argmax(labels, axis=1)\n\n result = np.zeros(labels.shape)\n\n for class_ind in range(nb_classes):\n other_classes = list(range(nb_classes))\n other_classes.remove(class_ind)\n in_cl = labels == class_ind\n result[in_cl] = np.random.choice(other_classes)\n\n return to_categorical(result, nb_classes)\n\n\ndef least_likely_class(x: np.ndarray, classifier: \"CLASSIFIER_TYPE\") -> np.ndarray:\n \"\"\"\n Compute the least likely class predictions for sample `x`. This strategy for choosing attack targets was used in\n (Kurakin et al., 2016).\n\n | Paper link: https://arxiv.org/abs/1607.02533\n\n :param x: A data sample of shape accepted by `classifier`.\n :param classifier: The classifier used for computing predictions.\n :return: Least-likely class predicted by `classifier` for sample `x` in one-hot encoding.\n \"\"\"\n return to_categorical(np.argmin(classifier.predict(x), axis=1), nb_classes=classifier.nb_classes)\n\n\ndef second_most_likely_class(x: np.ndarray, classifier: \"CLASSIFIER_TYPE\") -> np.ndarray:\n \"\"\"\n Compute the second most likely class predictions for sample `x`. This strategy can be used for choosing target\n labels for an attack to improve its chances to succeed.\n\n :param x: A data sample of shape accepted by `classifier`.\n :param classifier: The classifier used for computing predictions.\n :return: Second most likely class predicted by `classifier` for sample `x` in one-hot encoding.\n \"\"\"\n return to_categorical(\n np.argpartition(classifier.predict(x), -2, axis=1)[:, -2],\n nb_classes=classifier.nb_classes,\n )\n\n\ndef get_label_conf(y_vec: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Returns the confidence and the label of the most probable class given a vector of class confidences\n\n :param y_vec: Vector of class confidences, no. of instances as first dimension.\n :return: Confidences and labels.\n \"\"\"\n assert len(y_vec.shape) == 2\n\n confs, labels = np.amax(y_vec, axis=1), np.argmax(y_vec, axis=1)\n return confs, labels\n\n\ndef get_labels_np_array(preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the label of the most probable class given an array of class confidences.\n\n :param preds: Array of class confidences, nb of instances as first dimension.\n :return: Labels.\n \"\"\"\n if len(preds.shape) >= 2:\n preds_max = np.amax(preds, axis=1, keepdims=True)\n else:\n preds_max = np.round(preds)\n y = preds == preds_max\n y = y.astype(np.uint8)\n return y\n\n\ndef get_feature_values(x: np.ndarray, single_index_feature: bool) -> list:\n \"\"\"\n Returns a list of unique values of a given feature.\n\n :param x: The feature column(s).\n :param single_index_feature: Bool representing whether this is a single-column or multiple-column feature (for\n example 1-hot encoded and then scaled).\n :return: For a single-column feature, a simple list containing all possible values, in increasing order.\n For a multi-column feature, a list of lists, where each internal list represents a column and the values\n represent the possible values for that column (in increasing order).\n \"\"\"\n values = []\n if single_index_feature:\n values = np.unique(x).tolist()\n else:\n for column in x.T:\n values.append(np.unique(column).tolist())\n return values\n\n\ndef get_feature_index(feature: int | slice) -> int | slice:\n \"\"\"\n Returns a modified feature index: in case of a slice of size 1, returns the corresponding integer. In case\n of a slice with missing params, tries to fill them. Otherwise, returns the same value (integer or slice) as passed.\n\n :param feature: The index or slice representing a feature to attack\n :return: An integer representing a single column index or a slice representing a multi-column index\n \"\"\"\n if isinstance(feature, int):\n return feature\n\n start = feature.start\n stop = feature.stop\n step = feature.step\n if start is None:\n start = 0\n if step is None:\n step = 1\n if stop is not None and ((stop - start) // step) == 1:\n return start\n\n return slice(start, stop, step)\n\n\ndef remove_attacked_feature(attack_feature: int | slice, non_numerical_features: list[int] | None):\n \"\"\"\n Removes the attacked feature from the list of non-numeric features to encode.\n\n :param attack_feature: The index or slice representing a feature to attack\n :param non_numerical_features: a list of feature indexes that require encoding in order to feed into an ML model\n (i.e., strings)\n :return:\n \"\"\"\n if non_numerical_features is not None and isinstance(attack_feature, int):\n if attack_feature in non_numerical_features:\n non_numerical_features.remove(attack_feature)\n\n\ndef compute_success_array(\n classifier: \"CLASSIFIER_TYPE\",\n x_clean: np.ndarray,\n labels: np.ndarray,\n x_adv: np.ndarray,\n targeted: bool = False,\n batch_size: int = 1,\n) -> np.ndarray:\n \"\"\"\n Compute the success rate of an attack based on clean samples, adversarial samples and targets or correct labels.\n\n :param classifier: Classifier used for prediction.\n :param x_clean: Original clean samples.\n :param labels: Correct labels of `x_clean` if the attack is untargeted, or target labels of the attack otherwise.\n :param x_adv: Adversarial samples to be evaluated.\n :param targeted: `True` if the attack is targeted. In that case, `labels` are treated as target classes instead of\n correct labels of the clean samples.\n :param batch_size: Batch size.\n :return: Percentage of successful adversarial samples.\n \"\"\"\n adv_preds = classifier.predict(x_adv, batch_size=batch_size)\n if len(adv_preds.shape) >= 2:\n adv_preds = np.argmax(adv_preds, axis=1)\n else:\n adv_preds = np.round(adv_preds)\n if targeted:\n attack_success = adv_preds == np.argmax(labels, axis=1)\n else:\n preds = classifier.predict(x_clean, batch_size=batch_size)\n if len(preds.shape) >= 2:\n preds = np.argmax(preds, axis=1)\n else:\n preds = np.round(preds)\n attack_success = adv_preds != preds\n\n return attack_success\n\n\ndef compute_success(\n classifier: \"CLASSIFIER_TYPE\",\n x_clean: np.ndarray,\n labels: np.ndarray,\n x_adv: np.ndarray,\n targeted: bool = False,\n batch_size: int = 1,\n) -> float:\n \"\"\"\n Compute the success rate of an attack based on clean samples, adversarial samples and targets or correct labels.\n\n :param classifier: Classifier used for prediction.\n :param x_clean: Original clean samples.\n :param labels: Correct labels of `x_clean` if the attack is untargeted, or target labels of the attack otherwise.\n :param x_adv: Adversarial samples to be evaluated.\n :param targeted: `True` if the attack is targeted. In that case, `labels` are treated as target classes instead of\n correct labels of the clean samples.\n :param batch_size: Batch size.\n :return: Percentage of successful adversarial samples.\n \"\"\"\n attack_success = compute_success_array(classifier, x_clean, labels, x_adv, targeted, batch_size)\n return np.sum(attack_success) / x_adv.shape[0]\n\n\ndef compute_accuracy(preds: np.ndarray, labels: np.ndarray, abstain: bool = True) -> tuple[float, float]:\n \"\"\"\n Compute the accuracy rate and coverage rate of predictions\n In the case where predictions are abstained, those samples are ignored.\n\n :param preds: Predictions.\n :param labels: Correct labels of `x`.\n :param abstain: True if ignore abstained prediction, False if count them as incorrect.\n :return: Tuple of accuracy rate and coverage rate.\n \"\"\"\n has_pred = np.sum(preds, axis=1)\n idx_pred = np.where(has_pred)[0]\n labels = np.argmax(labels[idx_pred], axis=1)\n num_correct = np.sum(np.argmax(preds[idx_pred], axis=1) == labels)\n coverage_rate = len(idx_pred) / preds.shape[0]\n\n if abstain:\n acc_rate = num_correct / preds[idx_pred].shape[0]\n else:\n acc_rate = num_correct / preds.shape[0]\n\n return acc_rate, coverage_rate\n\n\ndef intersection_over_union(bbox_1: np.ndarray, bbox_2: np.ndarray) -> float:\n \"\"\"\n Compute the intersection over union (IoU) of two bounding boxes.\n Both bounding boxes are expected to be in torchvision format [x1, y1, x2, y2].\n\n param bbox_1: Bounding box 1 in torchvision format [x1, y1, x2, y2].\n param bbox_2: Bounding box 2 in torchvision format [x1, y2, x2, y2].\n return: The intersection over union (IoU) of the two bounding boxes.\n \"\"\"\n # Calculate area of the intersection\n x_1 = max(bbox_1[0], bbox_2[0])\n y_1 = max(bbox_1[1], bbox_2[1])\n x_2 = min(bbox_1[2], bbox_2[2])\n y_2 = min(bbox_1[3], bbox_2[3])\n intersection = max(0, x_2 - x_1 + 1) * max(0, y_2 - y_1 + 1)\n\n # Calculate the area of the union\n bbox_1_area = (bbox_1[2] - bbox_1[0] + 1) * (bbox_1[3] - bbox_1[1] + 1)\n bbox_2_area = (bbox_2[2] - bbox_2[0] + 1) * (bbox_2[3] - bbox_2[1] + 1)\n union = bbox_1_area + bbox_2_area - intersection\n\n return intersection / union\n\n\ndef intersection_over_area(bbox_1: np.ndarray, bbox_2: np.ndarray) -> float:\n \"\"\"\n Compute the intersection over area (IoA) of two bounding boxes.\n Both bounding boxes are expected to be in torchvision format [x1, y1, x2, y2].\n\n param bbox_1: Bounding box 1 in torchvision format [x1, y1, x2, y2].\n param bbox_2: Bounding box 2 in torchvision format [x1, y2, x2, y2].\n return: The intersection over area (IoA) of the two bounding boxes.\n \"\"\"\n # Calculate area of the intersection\n x_1 = max(bbox_1[0], bbox_2[0])\n y_1 = max(bbox_1[1], bbox_2[1])\n x_2 = min(bbox_1[2], bbox_2[2])\n y_2 = min(bbox_1[3], bbox_2[3])\n intersection = max(0, x_2 - x_1 + 1) * max(0, y_2 - y_1 + 1)\n\n # Calculate the area of bbox_1\n bbox_1_area = (bbox_1[2] - bbox_1[0] + 1) * (bbox_1[3] - bbox_1[1] + 1)\n\n return intersection / bbox_1_area\n\n\ndef non_maximum_suppression(\n preds: dict[str, np.ndarray], iou_threshold: float, confidence_threshold: float | None = None\n) -> dict[str, np.ndarray]:\n \"\"\"\n Perform non-maximum suppression on the predicted object detection labels of a single image.\n\n :param preds: Predicted labels of format `dict[str, np.ndarray]` for a single image. The fields of the dict are\n as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores of each prediction.\n :param iou_threshold: The IoU threshold to discard overlapping bounding boxes.\n :param confidence_threshold: The confidence threshold to discard bounding boxes.\n return: Filtered predicted labels of the single image in the same format as the input.\n \"\"\"\n boxes = preds[\"boxes\"]\n labels = preds[\"labels\"]\n scores = preds[\"scores\"]\n\n # Filter out bounding boxes below confidence threshold\n if confidence_threshold is not None:\n mask = scores >= confidence_threshold\n boxes = boxes[mask]\n labels = labels[mask]\n scores = scores[mask]\n\n # Candidate bounding boxes\n keep_indices = []\n indices = np.argsort(scores)[::-1]\n\n while len(indices) > 0:\n # Get first bounding box\n current_idx = indices[0]\n box_1 = boxes[current_idx]\n label_1 = labels[current_idx]\n\n keep_indices.append(current_idx)\n remove_indices = [0]\n\n # Find overlapping bounding boxes above IoU threshold\n for i, idx in enumerate(indices[1:], start=1):\n box_2 = boxes[idx]\n label_2 = labels[idx]\n\n if label_1 != label_2:\n continue\n\n iou = intersection_over_union(box_1, box_2)\n if iou >= iou_threshold:\n remove_indices.append(i)\n\n # Remove overlapping bounding boxes from candidates\n indices = np.delete(indices, remove_indices)\n\n filtered_preds = {\n \"boxes\": boxes[keep_indices],\n \"labels\": labels[keep_indices],\n \"scores\": scores[keep_indices],\n }\n return filtered_preds\n\n\n# -------------------------------------------------------------------------------------------------- DATASET OPERATIONS\n\n\ndef load_cifar10(\n raw: bool = False,\n) -> DATASET_TYPE:\n \"\"\"\n Loads CIFAR10 dataset from config.CIFAR10_PATH or downloads it if necessary.\n\n :param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1.\n :return: `(x_train, y_train), (x_test, y_test), min, max`\n \"\"\"\n\n def load_batch(fpath: str) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Utility function for loading CIFAR batches, as written in Keras.\n\n :param fpath: Full path to the batch file.\n :return: `(data, labels)`\n \"\"\"\n with open(fpath, \"rb\") as file_:\n if sys.version_info < (3,):\n content = six.moves.cPickle.load(file_)\n else:\n content = six.moves.cPickle.load(file_, encoding=\"bytes\")\n content_decoded = {}\n for key, value in content.items():\n content_decoded[key.decode(\"utf8\")] = value\n content = content_decoded\n data = content[\"data\"]\n labels = content[\"labels\"]\n\n data = data.reshape(data.shape[0], 3, 32, 32)\n return data, labels\n\n path = get_file(\n \"cifar-10-batches-py\",\n extract=True,\n path=config.ART_DATA_PATH,\n url=\"https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\",\n )\n\n num_train_samples = 50000\n\n x_train = np.zeros((num_train_samples, 3, 32, 32), dtype=np.uint8)\n y_train = np.zeros((num_train_samples,), dtype=np.uint8)\n\n for i in range(1, 6):\n fpath = os.path.join(path, \"data_batch_\" + str(i))\n data, labels = load_batch(fpath)\n x_train[(i - 1) * 10000 : i * 10000, :, :, :] = data\n y_train[(i - 1) * 10000 : i * 10000] = labels\n\n fpath = os.path.join(path, \"test_batch\")\n x_test, y_test = load_batch(fpath)\n\n # Set channels last\n x_train = x_train.transpose((0, 2, 3, 1))\n x_test = x_test.transpose((0, 2, 3, 1))\n\n min_, max_ = 0.0, 255.0\n if not raw:\n min_, max_ = 0.0, 1.0\n x_train, y_train = preprocess(x_train, y_train, clip_values=(0, 255))\n x_test, y_test = preprocess(x_test, y_test, clip_values=(0, 255))\n\n return (x_train, y_train), (x_test, y_test), min_, max_\n\n\ndef load_mnist(\n raw: bool = False,\n) -> DATASET_TYPE:\n \"\"\"\n Loads MNIST dataset from `config.ART_DATA_PATH` or downloads it if necessary.\n\n :param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1.\n :return: `(x_train, y_train), (x_test, y_test), min, max`.\n \"\"\"\n path = get_file(\n \"mnist.npz\",\n path=config.ART_DATA_PATH,\n url=\"https://s3.amazonaws.com/img-datasets/mnist.npz\",\n )\n\n dict_mnist = np.load(path)\n x_train = dict_mnist[\"x_train\"]\n y_train = dict_mnist[\"y_train\"]\n x_test = dict_mnist[\"x_test\"]\n y_test = dict_mnist[\"y_test\"]\n dict_mnist.close()\n\n # Add channel axis\n min_, max_ = 0.0, 255.0\n if not raw:\n min_, max_ = 0.0, 1.0\n x_train = np.expand_dims(x_train, axis=3)\n x_test = np.expand_dims(x_test, axis=3)\n x_train, y_train = preprocess(x_train, y_train)\n x_test, y_test = preprocess(x_test, y_test)\n\n return (x_train, y_train), (x_test, y_test), min_, max_\n\n\ndef load_stl() -> DATASET_TYPE:\n \"\"\"\n Loads the STL-10 dataset from `config.ART_DATA_PATH` or downloads it if necessary.\n\n :return: `(x_train, y_train), (x_test, y_test), min, max`.\n \"\"\"\n min_, max_ = 0.0, 1.0\n\n # Download and extract data if needed\n\n path = get_file(\n \"stl10_binary\",\n path=config.ART_DATA_PATH,\n extract=True,\n url=\"https://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz\",\n )\n\n with open(os.path.join(path, \"train_X.bin\"), \"rb\") as f_numpy:\n x_train = np.fromfile(f_numpy, dtype=np.uint8)\n x_train = np.reshape(x_train, (-1, 3, 96, 96))\n\n with open(os.path.join(path, \"test_X.bin\"), \"rb\") as f_numpy:\n x_test = np.fromfile(f_numpy, dtype=np.uint8)\n x_test = np.reshape(x_test, (-1, 3, 96, 96))\n\n # Set channel last\n x_train = x_train.transpose((0, 2, 3, 1))\n x_test = x_test.transpose((0, 2, 3, 1))\n\n with open(os.path.join(path, \"train_y.bin\"), \"rb\") as f_numpy:\n y_train_uint = np.fromfile(f_numpy, dtype=np.uint8)\n y_train = y_train_uint - 1\n\n with open(os.path.join(path, \"test_y.bin\"), \"rb\") as f_numpy:\n y_test_uint = np.fromfile(f_numpy, dtype=np.uint8)\n y_test = y_test_uint - 1\n\n x_train, y_train = preprocess(x_train, y_train)\n x_test, y_test = preprocess(x_test, y_test)\n\n return (x_train, y_train), (x_test, y_test), min_, max_\n\n\ndef load_iris(raw: bool = False, test_set: float = 0.3) -> DATASET_TYPE:\n \"\"\"\n Loads the UCI Iris dataset from `config.ART_DATA_PATH` or downloads it if necessary.\n\n :param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1.\n :param test_set: Proportion of the data to use as validation split. The value should be between 0 and 1.\n :return: Entire dataset and labels.\n \"\"\"\n from sklearn.datasets import load_iris as load_iris_sk\n\n iris = load_iris_sk()\n data = iris.data\n if not raw:\n data /= np.amax(data)\n labels = to_categorical(iris.target, 3)\n\n min_, max_ = float(np.amin(data)), float(np.amax(data))\n\n # Split training and test sets\n split_index = int((1 - test_set) * len(data) / 3)\n x_train = np.vstack((data[:split_index], data[50 : 50 + split_index], data[100 : 100 + split_index]))\n y_train = np.vstack(\n (\n labels[:split_index],\n labels[50 : 50 + split_index],\n labels[100 : 100 + split_index],\n )\n )\n\n if split_index >= 49:\n x_test, y_test = None, None\n else:\n\n x_test = np.vstack(\n (\n data[split_index:50],\n data[50 + split_index : 100],\n data[100 + split_index :],\n )\n ).astype(np.float32)\n y_test = np.vstack(\n (\n labels[split_index:50],\n labels[50 + split_index : 100],\n labels[100 + split_index :],\n )\n )\n assert len(x_train) + len(x_test) == 150\n\n # Shuffle test set\n random_indices = np.random.permutation(len(y_test))\n x_test, y_test = x_test[random_indices], y_test[random_indices]\n\n # Shuffle training set\n random_indices = np.random.permutation(len(y_train))\n x_train, y_train = x_train[random_indices].astype(np.float32), y_train[random_indices]\n\n return (x_train, y_train), (x_test, y_test), min_, max_ # type: ignore\n\n\ndef load_diabetes(raw: bool = False, test_set: float = 0.3) -> DATASET_TYPE:\n \"\"\"\n Loads the Diabetes Regression dataset from sklearn.\n\n :param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1.\n :param test_set: Proportion of the data to use as validation split. The value should be between 0 and 1.\n :return: Entire dataset and labels.\n \"\"\"\n from sklearn.datasets import load_diabetes as load_diabetes_sk\n\n diabetes = load_diabetes_sk()\n data = diabetes.data\n if not raw:\n data /= np.amax(data, axis=0)\n targets = diabetes.target\n\n min_, max_ = np.amin(data), np.amax(data)\n\n # Shuffle data set\n random_indices = np.random.permutation(len(data))\n data, targets = data[random_indices], targets[random_indices]\n\n # Split training and test sets\n split_index = int((1 - test_set) * len(data))\n x_train = data[:split_index]\n y_train = targets[:split_index]\n x_test = data[split_index:]\n y_test = targets[split_index:]\n\n return (x_train, y_train), (x_test, y_test), min_, max_\n\n\ndef load_nursery(\n raw: bool = False, scaled: bool = True, test_set: float = 0.2, transform_social: bool = False\n) -> DATASET_TYPE:\n \"\"\"\n Loads the UCI Nursery dataset from `config.ART_DATA_PATH` or downloads it if necessary.\n\n :param raw: `True` if no preprocessing should be applied to the data. Otherwise, categorical data is one-hot\n encoded and data is scaled using sklearn's StandardScaler according to the value of `scaled`.\n :param scaled: `True` if data should be scaled.\n :param test_set: Proportion of the data to use as validation split. The value should be between 0 and 1.\n :param transform_social: If `True`, transforms the social feature to be binary for the purpose of attribute\n inference. This is done by assigning the original value 'problematic' the new value 1, and\n the other original values are assigned the new value 0.\n :return: Entire dataset and labels as numpy array.\n \"\"\"\n import pandas as pd\n import sklearn.preprocessing\n\n # Download data if needed\n path = get_file(\n \"nursery.data\",\n path=config.ART_DATA_PATH,\n extract=False,\n url=[\n \"https://www.dropbox.com/s/l24hwvkuueor6lp/nursery.data?dl=1\",\n ],\n )\n\n # load data\n features_names = [\"parents\", \"has_nurs\", \"form\", \"children\", \"housing\", \"finance\", \"social\", \"health\", \"label\"]\n categorical_features = [\"parents\", \"has_nurs\", \"form\", \"housing\", \"finance\", \"social\", \"health\"]\n data = pd.read_csv(path, sep=\",\", names=features_names, engine=\"python\")\n # remove rows with missing label or too sparse label\n data = data.dropna(subset=[\"label\"])\n data.drop(data.loc[data[\"label\"] == \"recommend\"].index, axis=0, inplace=True)\n\n # fill missing values\n data[\"children\"] = data[\"children\"].fillna(0)\n\n for col in [\"parents\", \"has_nurs\", \"form\", \"housing\", \"finance\", \"social\", \"health\"]:\n data[col] = data[col].fillna(\"other\")\n\n # make categorical label\n def modify_label(value): # 5 classes\n if value == \"not_recom\":\n return 0\n if value == \"very_recom\":\n return 1\n if value == \"priority\":\n return 2\n if value == \"spec_prior\":\n return 3\n raise Exception(f\"Bad label value: {value}\")\n\n data[\"label\"] = data[\"label\"].apply(modify_label)\n data[\"children\"] = data[\"children\"].apply(lambda x: 4 if x == \"more\" else x)\n\n if transform_social:\n\n def modify_social(value):\n if value == \"problematic\":\n return 1\n return 0\n\n data[\"social\"] = data[\"social\"].apply(modify_social)\n categorical_features.remove(\"social\")\n\n if not raw:\n # one-hot-encode categorical features\n features_to_remove = []\n for feature in categorical_features:\n all_values = data.loc[:, feature]\n values = list(all_values.unique())\n data[feature] = pd.Categorical(data.loc[:, feature], categories=values, ordered=False)\n one_hot_vector = pd.get_dummies(data[feature], prefix=feature)\n data = pd.concat([data, one_hot_vector], axis=1)\n features_to_remove.append(feature)\n data = data.drop(features_to_remove, axis=1)\n\n # normalize data\n if scaled:\n label = data.loc[:, \"label\"]\n features = data.drop([\"label\"], axis=1)\n scaler = sklearn.preprocessing.StandardScaler()\n scaler.fit(features)\n scaled_features = pd.DataFrame(scaler.transform(features), columns=features.columns)\n data = pd.concat([label, scaled_features], axis=1, join=\"inner\")\n\n features = data.drop([\"label\"], axis=1)\n if raw:\n numeric_features = features.drop(categorical_features, axis=1).to_numpy().astype(np.int32)\n min_, max_ = np.amin(numeric_features), np.amax(numeric_features)\n else:\n min_, max_ = np.amin(features.to_numpy().astype(np.float64)), np.amax(features.to_numpy().astype(np.float64))\n\n # Split training and test sets\n stratified = sklearn.model_selection.StratifiedShuffleSplit(n_splits=1, test_size=test_set, random_state=18)\n for train_set_i, test_set_i in stratified.split(data, data[\"label\"]):\n train = data.iloc[train_set_i]\n test = data.iloc[test_set_i]\n x_train = train.drop([\"label\"], axis=1).to_numpy()\n y_train = train.loc[:, \"label\"].to_numpy()\n x_test = test.drop([\"label\"], axis=1).to_numpy()\n y_test = test.loc[:, \"label\"].to_numpy()\n\n if not raw and not scaled:\n x_train = x_train.astype(np.float64)\n x_test = x_test.astype(np.float64)\n\n return (x_train, y_train), (x_test, y_test), min_, max_\n\n\ndef load_dataset(\n name: str,\n) -> DATASET_TYPE:\n \"\"\"\n Loads or downloads the dataset corresponding to `name`. Options are: `mnist`, `cifar10`, `stl10`, `iris`, `nursery`\n and `diabetes`.\n\n :param name: Name of the dataset.\n :return: The dataset separated in training and test sets as `(x_train, y_train), (x_test, y_test), min, max`.\n :raises NotImplementedError: If the dataset is unknown.\n \"\"\"\n if \"mnist\" in name:\n return load_mnist()\n if \"cifar10\" in name:\n return load_cifar10()\n if \"stl10\" in name:\n return load_stl()\n if \"iris\" in name:\n return load_iris()\n if \"nursery\" in name:\n return load_nursery()\n if \"diabetes\" in name:\n return load_diabetes()\n\n raise NotImplementedError(f\"There is no loader for dataset '{name}'.\")\n\n\ndef _extract(full_path: str, path: str) -> bool:\n archive: Union[zipfile.ZipFile, tarfile.TarFile]\n if full_path.endswith(\"tar\"): # pragma: no cover\n if tarfile.is_tarfile(full_path):\n archive = tarfile.open(full_path, \"r:\")\n elif full_path.endswith(\"tar.gz\"): # pragma: no cover\n if tarfile.is_tarfile(full_path):\n archive = tarfile.open(full_path, \"r:gz\")\n elif full_path.endswith(\"zip\"): # pragma: no cover\n if zipfile.is_zipfile(full_path):\n archive = zipfile.ZipFile(full_path) # pylint: disable=consider-using-with\n else:\n return False\n else:\n return False\n\n try:\n for entry in archive.getmembers(): # type: ignore\n if os.path.isabs(entry.name) or \"..\" in entry.name:\n raise ValueError(f\"Illegal tar archive entry: {entry.name}\")\n archive.extractall(path)\n except (tarfile.TarError, RuntimeError, KeyboardInterrupt): # pragma: no cover\n if os.path.exists(path):\n if os.path.isfile(path):\n os.remove(path)\n else:\n shutil.rmtree(path)\n raise\n return True\n\n\ndef get_file(\n filename: str, url: Union[str, list[str]], path: str | None = None, extract: bool = False, verbose: bool = False\n) -> str:\n \"\"\"\n Downloads a file from a URL if it not already in the cache. The file at indicated by `url` is downloaded to the\n path `path` (default is ~/.art/data). and given the name `filename`. Files in tar, tar.gz, tar.bz, and zip formats\n can also be extracted. This is a simplified version of the function with the same name in Keras.\n\n :param filename: Name of the file.\n :param url: Download URL.\n :param path: Folder to store the download. If not specified, `~/.art/data` is used instead.\n :param extract: If true, tries to extract the archive.\n :param verbose: If true, print download progress bar.\n :return: Path to the downloaded file.\n \"\"\"\n if isinstance(url, str):\n url_list = [url]\n else:\n url_list = url\n\n if path is None:\n path_ = os.path.expanduser(config.ART_DATA_PATH)\n else:\n path_ = os.path.expanduser(path)\n if not os.access(path_, os.W_OK):\n path_ = os.path.join(\"/tmp\", \".art\")\n\n if not os.path.exists(path_):\n os.makedirs(path_)\n\n target_path = os.path.join(path_, filename)\n\n if extract:\n full_path = target_path + \".tar.gz\"\n else:\n full_path = target_path\n\n # Determine if dataset needs downloading\n download = not os.path.exists(target_path)\n\n if download:\n logger.info(\"Downloading data from %s\", url)\n try:\n for url_i in url_list:\n try:\n from six.moves.urllib.error import HTTPError, URLError\n from six.moves.urllib.request import urlretrieve\n\n # The following two lines should prevent occasionally occurring\n # [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:847)\n import ssl\n\n ssl._create_default_https_context = ssl._create_unverified_context\n\n if verbose:\n with tqdm() as t_bar:\n # pylint: disable=cell-var-from-loop\n last_block = [0]\n\n def progress_bar(blocks: int = 1, block_size: int = 1, total_size: int | None = None):\n \"\"\"\n :param blocks: Number of blocks transferred so far [default: 1].\n :param block_size: Size of each block (in tqdm units) [default: 1].\n :param total_size: Total size (in tqdm units). If [default: None] or -1, remains\n unchanged.\n \"\"\"\n if total_size not in (None, -1):\n t_bar.total = total_size\n displayed = t_bar.update((blocks - last_block[0]) * block_size)\n last_block[0] = blocks\n return displayed\n\n urlretrieve(url_i, full_path, reporthook=progress_bar)\n else:\n urlretrieve(url_i, full_path)\n\n except HTTPError as exception: # pragma: no cover\n logger.error(url_i, exception)\n except URLError as exception: # pragma: no cover\n logger.error(url_i, exception)\n except (Exception, KeyboardInterrupt): # pragma: no cover\n if os.path.exists(full_path):\n os.remove(full_path)\n raise\n\n if extract:\n if not os.path.exists(target_path):\n _extract(full_path, path_)\n return target_path\n\n return full_path\n\n\ndef make_directory(dir_path: str) -> None:\n \"\"\"\n Creates the specified tree of directories if needed.\n\n :param dir_path: Folder or file path.\n \"\"\"\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n\ndef clip_and_round(x: np.ndarray, clip_values: \"CLIP_VALUES_TYPE\" | None, round_samples: float) -> np.ndarray:\n \"\"\"\n Rounds the input to the correct level of granularity.\n Useful to ensure data passed to classifier can be represented\n in the correct domain, e.g., [0, 255] integers verses [0,1]\n or [0, 255] floating points.\n\n :param x: Sample input with shape as expected by the model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features, or `None` if no clipping should be performed.\n :param round_samples: The resolution of the input domain to round the data to, e.g., 1.0, or 1/255. Set to 0 to\n disable.\n \"\"\"\n if round_samples == 0.0:\n return x\n if clip_values is not None:\n np.clip(x, clip_values[0], clip_values[1], out=x)\n x = np.around(x / round_samples) * round_samples\n return x\n\n\ndef preprocess(\n x: np.ndarray,\n y: np.ndarray,\n nb_classes: int = 10,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Scales `x` to [0, 1] and converts `y` to class categorical confidences.\n\n :param x: Data instances.\n :param y: Labels.\n :param nb_classes: Number of classes in dataset.\n :param clip_values: Original data range allowed value for features, either one respective scalar or one value per\n feature.\n :return: Rescaled values of `x`, `y`.\n \"\"\"\n if clip_values is None:\n min_, max_ = np.amin(x), np.amax(x)\n else:\n min_, max_ = clip_values\n\n normalized_x = (x - min_) / (max_ - min_)\n categorical_y = to_categorical(y, nb_classes)\n\n return normalized_x, categorical_y\n\n\ndef segment_by_class(data: Union[np.ndarray, list[int]], classes: np.ndarray, num_classes: int) -> list[np.ndarray]:\n \"\"\"\n Returns segmented data according to specified features.\n\n :param data: Data to be segmented.\n :param classes: Classes used to segment data, e.g., segment according to predicted label or to `y_train` or other\n array of one hot encodings the same length as data.\n :param num_classes: How many features.\n :return: Segmented data according to specified features.\n \"\"\"\n by_class: list[list[int]] = [[] for _ in range(num_classes)]\n for indx, feature in enumerate(classes):\n if len(classes.shape) == 2 and classes.shape[1] > 1:\n assigned = int(np.argmax(feature))\n else:\n assigned = int(feature)\n by_class[assigned].append(data[indx])\n\n return [np.asarray(i) for i in by_class]\n\n\ndef performance_diff(\n model1: \"CLASSIFIER_TYPE\",\n model2: \"CLASSIFIER_TYPE\",\n test_data: np.ndarray,\n test_labels: np.ndarray,\n perf_function: Union[str, Callable] = \"accuracy\",\n **kwargs,\n) -> float:\n \"\"\"\n Calculates the difference in performance between two models on the test_data with a performance function.\n\n Note: For multi-label classification, f1 scores will use 'micro' averaging unless otherwise specified.\n\n :param model1: A trained ART classifier.\n :param model2: Another trained ART classifier.\n :param test_data: The data to test both model's performance.\n :param test_labels: The labels to the testing data.\n :param perf_function: The performance metric to be used. One of ['accuracy', 'f1'] or a callable function\n `(true_labels, model_labels[, kwargs]) -> float`.\n :param kwargs: Arguments to add to performance function.\n :return: The difference in performance: performance(model1) - performance(model2).\n :raises `ValueError`: If an unsupported performance function is requested.\n \"\"\"\n from sklearn.metrics import accuracy_score, f1_score\n\n model1_labels = model1.predict(test_data)\n model2_labels = model2.predict(test_data)\n\n if perf_function == \"accuracy\":\n model1_acc = accuracy_score(test_labels, model1_labels, **kwargs)\n model2_acc = accuracy_score(test_labels, model2_labels, **kwargs)\n return model1_acc - model2_acc\n\n if perf_function == \"f1\":\n n_classes = test_labels.shape[1]\n if n_classes > 2 and \"average\" not in kwargs:\n kwargs[\"average\"] = \"micro\"\n model1_f1 = f1_score(test_labels, model1_labels, **kwargs)\n model2_f1 = f1_score(test_labels, model2_labels, **kwargs)\n return model1_f1 - model2_f1\n\n if callable(perf_function):\n return perf_function(test_labels, model1_labels, **kwargs) - perf_function(test_labels, model2_labels, **kwargs)\n\n raise ValueError(f\"Performance function '{perf_function}' not supported\")\n\n\ndef is_probability(vector: np.ndarray) -> bool:\n \"\"\"\n Check if an 1D-array is a probability vector.\n\n :param vector: An 1D-array.\n :return: True if it is a probability vector.\n \"\"\"\n is_sum_1 = math.isclose(np.sum(vector), 1.0, rel_tol=1e-03)\n is_smaller_1 = np.amax(vector) <= 1.0\n is_larger_0 = np.amin(vector) >= 0.0\n\n return is_sum_1 and is_smaller_1 and is_larger_0\n\n\ndef is_probability_array(array: np.ndarray) -> bool:\n \"\"\"\n Check if a multidimensional array is an array of probabilities.\n\n :param array: A numpy array.\n :return: True if it is an array of probabilities.\n \"\"\"\n if len(array.shape) == 1:\n return is_probability(array)\n sum_array = np.sum(array, axis=1)\n ones = np.ones_like(sum_array)\n is_sum_1 = np.allclose(sum_array, ones, rtol=1e-03)\n is_smaller_1 = np.amax(array) <= 1.0\n is_larger_0 = np.amin(array) >= 0.0\n\n return is_sum_1 and is_smaller_1 and is_larger_0\n\n\ndef pad_sequence_input(x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Apply padding to a batch of 1-dimensional samples such that it has shape of (batch_size, max_length).\n\n :param x: A batch of 1-dimensional input data, e.g. `np.array([np.array([1,2,3]), np.array([4,5,6,7])])`.\n :return: The padded input batch and its corresponding mask.\n \"\"\"\n max_length = max(map(len, x))\n batch_size = x.shape[0]\n\n # note: use dtype of inner elements\n x_padded = np.zeros((batch_size, max_length), dtype=x[0].dtype)\n x_mask = np.zeros((batch_size, max_length), dtype=bool)\n\n for i, x_i in enumerate(x):\n x_padded[i, : len(x_i)] = x_i\n x_mask[i, : len(x_i)] = 1\n return x_padded, x_mask\n\n\n# -------------------------------------------------------------------------------------------------------- CUDA SUPPORT\n\n\ndef to_cuda(x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Move the tensor from the CPU to the GPU if a GPU is available.\n\n :param x: CPU Tensor to move to GPU if available.\n :return: The CPU Tensor moved to a GPU Tensor.\n \"\"\"\n from torch.cuda import is_available\n\n use_cuda = is_available()\n if use_cuda: # pragma: no cover\n x = x.cuda()\n return x\n\n\ndef from_cuda(x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Move the tensor from the GPU to the CPU if a GPU is available.\n\n :param x: GPU Tensor to move to CPU if available.\n :return: The GPU Tensor moved to a CPU Tensor.\n \"\"\"\n from torch.cuda import is_available\n\n use_cuda = is_available()\n if use_cuda: # pragma: no cover\n x = x.cpu()\n return x\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/visualization.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule providing visualization functions.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport os.path\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art import config\n\nif TYPE_CHECKING:\n import matplotlib\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_sprite(images: np.ndarray) -> np.ndarray:\n \"\"\"\n Creates a sprite of provided images.\n\n :param images: Images to construct the sprite.\n :return: An image array containing the sprite.\n \"\"\"\n shape = np.shape(images)\n\n if len(shape) < 3 or len(shape) > 4:\n raise ValueError(\"Images provided for sprite have wrong dimensions \" + str(len(shape)))\n\n if len(shape) == 3:\n # Check to see if it's MNIST type of images and add axis to show image is gray-scale\n images = np.expand_dims(images, axis=3)\n shape = np.shape(images)\n\n # Change black and white images to RGB\n if shape[3] == 1:\n images = convert_to_rgb(images)\n\n n = int(np.ceil(np.sqrt(images.shape[0])))\n padding = ((0, n**2 - images.shape[0]), (0, 0), (0, 0)) + ((0, 0),) * (images.ndim - 3)\n images = np.pad(images, padding, mode=\"constant\", constant_values=0)\n\n # Tile the individual thumbnails into an image\n images = images.reshape((n, n) + images.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, images.ndim + 1)))\n images = images.reshape((n * images.shape[1], n * images.shape[3]) + images.shape[4:])\n sprite = (images * 255).astype(np.uint8)\n\n return sprite\n\n\ndef convert_to_rgb(images: np.ndarray) -> np.ndarray:\n \"\"\"\n Converts grayscale images to RGB. It changes NxHxWx1 to a NxHxWx3 array, where N is the number of figures,\n H is the high and W the width.\n\n :param images: Grayscale images of shape (NxHxWx1).\n :return: Images in RGB format of shape (NxHxWx3).\n \"\"\"\n dims = np.shape(images)\n if not ((len(dims) == 4 and dims[-1] == 1) or len(dims) == 3):\n raise ValueError(\"Unexpected shape for grayscale images:\" + str(dims))\n\n if dims[-1] == 1:\n # Squeeze channel axis if it exists\n rgb_images = np.squeeze(images, axis=-1)\n else:\n rgb_images = images\n rgb_images = np.stack((rgb_images,) * 3, axis=-1)\n\n return rgb_images\n\n\ndef save_image(image_array: np.ndarray, f_name: str) -> None:\n \"\"\"\n Saves image into a file inside `ART_DATA_PATH` with the name `f_name`.\n\n :param image_array: Image to be saved.\n :param f_name: File name containing extension e.g., my_img.jpg, my_img.png, my_images/my_img.png.\n \"\"\"\n from PIL import Image\n\n file_name = os.path.join(config.ART_DATA_PATH, f_name)\n folder = os.path.split(file_name)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n image = Image.fromarray(image_array)\n image.save(file_name)\n logger.info(\"Image saved to %s.\", file_name)\n\n\ndef plot_3d(\n points: np.ndarray,\n labels: np.ndarray,\n colors: list[str] | None = None,\n save: bool = True,\n f_name: str = \"\",\n) -> \"matplotlib.figure.Figure\": # pragma: no cover\n \"\"\"\n Generates a 3-D plot in of the provided points where the labels define the color that will be used to color each\n data point. Concretely, the color of points[i] is defined by colors(labels[i]). Thus, there should be as many labels\n as colors.\n\n :param points: arrays with 3-D coordinates of the plots to be plotted.\n :param labels: array of integers that determines the color used in the plot for the data point.\n Need to start from 0 and be sequential from there on.\n :param colors: Optional argument to specify colors to be used in the plot. If provided, this array should contain\n as many colors as labels.\n :param save: When set to True, saves image into a file inside `ART_DATA_PATH` with the name `f_name`.\n :param f_name: Name used to save the file when save is set to True.\n :return: A figure object.\n \"\"\"\n # Disable warnings of unused import because all imports in this block are required\n # pylint: disable=unused-import\n # import matplotlib\n import matplotlib.pyplot as plt\n\n from mpl_toolkits import mplot3d # noqa: F401\n\n if colors is None: # pragma: no cover\n colors = []\n for i in range(len(np.unique(labels))):\n colors.append(\"C\" + str(i))\n else:\n if len(colors) != len(np.unique(labels)):\n raise ValueError(\"The amount of provided colors should match the number of labels in the 3pd plot.\")\n\n fig = plt.figure()\n axis = plt.axes(projection=\"3d\")\n\n for i, coord in enumerate(points):\n try:\n color_point = labels[i]\n axis.scatter3D(coord[0], coord[1], coord[2], color=colors[color_point]) # type: ignore\n except IndexError:\n raise ValueError(\n \"Labels outside the range. Should start from zero and be sequential there after\"\n ) from IndexError\n if save: # pragma: no cover\n file_name = os.path.realpath(os.path.join(config.ART_DATA_PATH, f_name))\n folder = os.path.split(file_name)[0]\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n fig.savefig(file_name, bbox_inches=\"tight\")\n logger.info(\"3d-plot saved to %s.\", file_name)\n\n return fig\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing adversarial attacks under a common interface.\n\"\"\"\n\nfrom art.attacks.attack import Attack, EvasionAttack, PoisoningAttack, PoisoningAttackBlackBox, PoisoningAttackWhiteBox\nfrom art.attacks.attack import PoisoningAttackGenerator, PoisoningAttackTransformer, PoisoningAttackObjectDetector\nfrom art.attacks.attack import ExtractionAttack, InferenceAttack, AttributeInferenceAttack\nfrom art.attacks.attack import ReconstructionAttack\n\nfrom art.attacks import evasion\nfrom art.attacks import extraction\nfrom art.attacks import inference\nfrom art.attacks import poisoning\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base classes for all attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.exceptions import EstimatorError\nfrom art.summary_writer import SummaryWriter, SummaryWriterDefault\nfrom art.utils import get_feature_index\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, GENERATOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass InputFilter(abc.ABCMeta): # pragma: no cover\n \"\"\"\n Metaclass to ensure that inputs are ndarray for all the subclass generate and extract calls\n \"\"\"\n\n def __init__(cls, name, bases, clsdict):\n \"\"\"\n This function overrides any existing generate or extract methods with a new method that\n ensures the input is an `np.ndarray`. There is an assumption that the input object has implemented\n __array__ with np.array calls.\n \"\"\"\n\n super().__init__()\n\n def make_replacement(fdict, func_name):\n \"\"\"\n This function overrides creates replacement functions dynamically\n \"\"\"\n\n def replacement_function(self, *args, **kwargs):\n if len(args) > 0:\n lst = list(args)\n else:\n lst = []\n\n if \"x\" in kwargs:\n if not isinstance(kwargs[\"x\"], np.ndarray):\n kwargs[\"x\"] = np.array(kwargs[\"x\"])\n else:\n if not isinstance(args[0], np.ndarray):\n lst[0] = np.array(args[0])\n\n if \"y\" in kwargs:\n if kwargs[\"y\"] is not None and not isinstance(kwargs[\"y\"], np.ndarray):\n kwargs[\"y\"] = np.array(kwargs[\"y\"])\n elif len(args) == 2:\n if not isinstance(args[1], np.ndarray):\n lst[1] = np.array(args[1])\n\n if len(args) > 0:\n args = tuple(lst)\n return fdict[func_name](self, *args, **kwargs)\n\n replacement_function.__doc__ = fdict[func_name].__doc__\n replacement_function.__name__ = \"new_\" + func_name\n return replacement_function\n\n replacement_list = [\"generate\", \"extract\"]\n for item in replacement_list:\n if item in clsdict:\n new_function = make_replacement(clsdict, item)\n setattr(cls, item, new_function)\n\n\nclass Attack(abc.ABC):\n \"\"\"\n Abstract base class for all attack abstract base classes.\n \"\"\"\n\n attack_params: list[str] = []\n # The _estimator_requirements define the requirements an estimator must satisfy to be used as a target for an\n # attack. They should be a tuple of requirements, where each requirement is either a class the estimator must\n # inherit from, or a tuple of classes which define a union, i.e. the estimator must inherit from at least one class\n # in the requirement tuple.\n _estimator_requirements: tuple[Any, ...] | tuple[()] | None = None\n\n def __init__(\n self,\n estimator,\n summary_writer: str | bool | SummaryWriter = False,\n ):\n \"\"\"\n :param estimator: An estimator.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n \"\"\"\n super().__init__()\n\n if self.estimator_requirements is None:\n raise ValueError(\"Estimator requirements have not been defined in `_estimator_requirements`.\")\n\n if not self.is_estimator_valid(estimator, self._estimator_requirements):\n raise EstimatorError(self.__class__, self.estimator_requirements, estimator)\n\n self._estimator = estimator\n self._summary_writer_arg = summary_writer\n self._summary_writer: SummaryWriter | None = None\n\n if isinstance(summary_writer, SummaryWriter): # pragma: no cover\n self._summary_writer = summary_writer\n elif summary_writer:\n self._summary_writer = SummaryWriterDefault(summary_writer)\n\n Attack._check_params(self)\n\n @property\n def estimator(self):\n \"\"\"The estimator.\"\"\"\n return self._estimator\n\n @property\n def summary_writer(self):\n \"\"\"The summary writer.\"\"\"\n return self._summary_writer\n\n @property\n def estimator_requirements(self):\n \"\"\"The estimator requirements.\"\"\"\n return self._estimator_requirements\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and apply attack-specific checks before saving them as attributes.\n\n :param kwargs: A dictionary of attack-specific parameters.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.attack_params:\n setattr(self, key, value)\n else:\n raise ValueError(f'The attribute \"{key}\" cannot be set for this attack.')\n self._check_params()\n\n def _check_params(self) -> None:\n\n if not isinstance(self._summary_writer_arg, (bool, str, SummaryWriter)):\n raise ValueError(\"The argument `summary_writer` has to be either of type bool or str.\")\n\n @staticmethod\n def is_estimator_valid(estimator, estimator_requirements) -> bool:\n \"\"\"\n Checks if the given estimator satisfies the requirements for this attack.\n\n :param estimator: The estimator to check.\n :param estimator_requirements: Estimator requirements.\n :return: True if the estimator is valid for the attack.\n \"\"\"\n\n for req in estimator_requirements:\n # A requirement is either a class which the estimator must inherit from, or a tuple of classes and the\n # estimator is required to inherit from at least one of the classes\n if isinstance(req, tuple):\n if all(p not in type(estimator).__mro__ for p in req):\n return False\n elif req not in type(estimator).__mro__:\n return False\n return True\n\n def __repr__(self):\n \"\"\"\n Returns a string describing the attack class and attack_params\n \"\"\"\n param_str = \"\"\n for param in self.attack_params:\n if hasattr(self, param):\n param_str += f\"{param}={getattr(self, param)}, \"\n elif hasattr(self, \"_attack\"):\n if hasattr(self._attack, param):\n param_str += f\"{param}={getattr(self._attack, param)}, \"\n return f\"{type(self).__name__}({param_str})\"\n\n\nclass EvasionAttack(Attack):\n \"\"\"\n Abstract base class for evasion attack classes.\n \"\"\"\n\n def __init__(self, **kwargs) -> None:\n self._targeted = False\n super().__init__(**kwargs)\n\n @abc.abstractmethod\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial examples and return them as an array. This method should be overridden by all concrete\n evasion attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Correct labels or target labels for `x`, depending on if the attack is targeted\n or not. This parameter is only used by some of the attacks.\n :return: An array holding the adversarial examples.\n \"\"\"\n raise NotImplementedError\n\n @property\n def targeted(self) -> bool:\n \"\"\"\n Return Boolean if attack is targeted. Return None if not applicable.\n \"\"\"\n return self._targeted\n\n @targeted.setter\n def targeted(self, targeted) -> None:\n self._targeted = targeted\n\n\nclass PoisoningAttack(Attack):\n \"\"\"\n Abstract base class for poisoning attack classes\n \"\"\"\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\" | None) -> None:\n \"\"\"\n :param classifier: A trained classifier (or none if no classifier is needed)\n \"\"\"\n super().__init__(classifier)\n\n @abc.abstractmethod\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate poisoning examples and return them as an array. This method should be overridden by all concrete\n poisoning attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target labels for `x`. Untargeted attacks set this value to None.\n :return: A tuple holding the (poisoning examples, poisoning labels).\n \"\"\"\n raise NotImplementedError\n\n\nclass PoisoningAttackGenerator(Attack):\n \"\"\"\n Abstract base class for poisoning attack classes that return a transformed generator.\n These attacks have an additional method, `poison_estimator`, that returns the poisoned generator.\n \"\"\"\n\n def __init__(self, generator: \"GENERATOR_TYPE\") -> None:\n \"\"\"\n :param generator: A generator\n \"\"\"\n super().__init__(generator)\n\n @abc.abstractmethod\n def poison_estimator(\n self,\n z_trigger: np.ndarray,\n x_target: np.ndarray,\n batch_size: int,\n max_iter: int,\n lambda_p: float,\n verbose: int,\n **kwargs,\n ) -> \"GENERATOR_TYPE\":\n \"\"\"\n Returns a poisoned version of the generator used to initialize the attack\n :return: A poisoned generator\n \"\"\"\n raise NotImplementedError\n\n @property\n def z_trigger(self):\n \"\"\"\n Returns the secret attacker trigger\n \"\"\"\n return self._z_trigger\n\n @property\n def x_target(self):\n \"\"\"\n Returns the secret attacker target which the poisoned generator should produce\n \"\"\"\n return self._x_target\n\n\nclass PoisoningAttackTransformer(PoisoningAttack):\n \"\"\"\n Abstract base class for poisoning attack classes that return a transformed classifier.\n These attacks have an additional method, `poison_estimator`, that returns the poisoned classifier.\n \"\"\"\n\n @abc.abstractmethod\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate poisoning examples and return them as an array. This method should be overridden by all concrete\n poisoning attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target labels for `x`. Untargeted attacks set this value to None.\n :return: A tuple holding the (poisoning examples, poisoning labels).\n :rtype: `(np.ndarray, np.ndarray)`\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def poison_estimator(self, x: np.ndarray, y: np.ndarray, **kwargs) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Returns a poisoned version of the classifier used to initialize the attack\n :param x: Training data\n :param y: Training labels\n :return: A poisoned classifier\n \"\"\"\n raise NotImplementedError\n\n\nclass PoisoningAttackObjectDetector(Attack):\n \"\"\"\n Abstract base class for poisoning attack classes on object detection models.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes object detector poisoning attack.\n \"\"\"\n super().__init__(None) # type: ignore\n\n @abc.abstractmethod\n def poison(\n self,\n x: np.ndarray | list[np.ndarray],\n y: list[dict[str, np.ndarray]],\n **kwargs,\n ) -> tuple[np.ndarray | list[np.ndarray], list[dict[str, np.ndarray]]]:\n \"\"\"\n Generate poisoning examples and return them as an array. This method should be overridden by all concrete\n poisoning attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: True labels of type `list[dict[np.ndarray]]`, one dictionary per input image.\n The keys and values of the dictionary are:\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image\n - scores [N]: the scores or each prediction.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n raise NotImplementedError\n\n\nclass PoisoningAttackBlackBox(PoisoningAttack):\n \"\"\"\n Abstract base class for poisoning attack classes that have no access to the model (classifier object).\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes black-box data poisoning attack.\n \"\"\"\n super().__init__(None) # type: ignore\n\n @abc.abstractmethod\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate poisoning examples and return them as an array. This method should be overridden by all concrete\n poisoning attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target labels for `x`. Untargeted attacks set this value to None.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n raise NotImplementedError\n\n\nclass PoisoningAttackWhiteBox(PoisoningAttack):\n \"\"\"\n Abstract base class for poisoning attack classes that have white-box access to the model (classifier object).\n \"\"\"\n\n @abc.abstractmethod\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate poisoning examples and return them as an array. This method should be overridden by all concrete\n poisoning attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Correct labels or target labels for `x`, depending on if the attack is targeted\n or not. This parameter is only used by some of the attacks.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n raise NotImplementedError\n\n\nclass ExtractionAttack(Attack):\n \"\"\"\n Abstract base class for extraction attack classes.\n \"\"\"\n\n @abc.abstractmethod\n def extract(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Extract models and return them as an ART classifier. This method should be overridden by all concrete extraction\n attack implementations.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Correct labels or target labels for `x`, depending on if the attack is targeted\n or not. This parameter is only used by some of the attacks.\n :return: ART classifier of the extracted model.\n \"\"\"\n raise NotImplementedError\n\n\nclass InferenceAttack(Attack):\n \"\"\"\n Abstract base class for inference attack classes.\n \"\"\"\n\n def __init__(self, estimator):\n \"\"\"\n :param estimator: A trained estimator targeted for inference attack.\n :type estimator: :class:`.art.estimators.estimator.BaseEstimator`\n \"\"\"\n super().__init__(estimator)\n\n @abc.abstractmethod\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer sensitive attributes from the targeted estimator. This method\n should be overridden by all concrete inference attack implementations.\n\n :param x: An array with reference inputs to be used in the attack.\n :param y: Labels for `x`. This parameter is only used by some of the attacks.\n :return: An array holding the inferred attribute values.\n \"\"\"\n raise NotImplementedError\n\n\nclass AttributeInferenceAttack(InferenceAttack):\n \"\"\"\n Abstract base class for attribute inference attack classes.\n \"\"\"\n\n attack_params = InferenceAttack.attack_params + [\"attack_feature\"]\n\n def __init__(self, estimator, attack_feature: int | slice = 0):\n \"\"\"\n :param estimator: A trained estimator targeted for inference attack.\n :type estimator: :class:`.art.estimators.estimator.BaseEstimator`\n :param attack_feature: The index of the feature to be attacked.\n \"\"\"\n super().__init__(estimator)\n self._check_attack_feature(attack_feature)\n self.attack_feature = get_feature_index(attack_feature)\n\n @abc.abstractmethod\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer sensitive attributes from the targeted estimator. This method\n should be overridden by all concrete inference attack implementations.\n\n :param x: An array with reference inputs to be used in the attack.\n :param y: Labels for `x`. This parameter is only used by some of the attacks.\n :return: An array holding the inferred attribute values.\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def _check_attack_feature(attack_feature: int | slice) -> None:\n if not isinstance(attack_feature, int) and not isinstance(attack_feature, slice):\n raise ValueError(\"Attack feature must be either an integer or a slice object.\")\n\n if isinstance(attack_feature, int) and attack_feature < 0:\n raise ValueError(\"Attack feature index must be non-negative.\")\n\n def _check_params(self) -> None:\n self._check_attack_feature(self.attack_feature)\n\n\nclass MembershipInferenceAttack(InferenceAttack):\n \"\"\"\n Abstract base class for membership inference attack classes.\n \"\"\"\n\n @abc.abstractmethod\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer membership status of samples from the target estimator. This method\n should be overridden by all concrete inference attack implementations.\n\n :param x: An array with reference inputs to be used in the attack.\n :param y: Labels for `x`. This parameter is only used by some of the attacks.\n :param probabilities: a boolean indicating whether to return the predicted probabilities per class, or just\n the predicted class.\n :return: An array holding the inferred membership status (1 indicates member of training set,\n 0 indicates non-member) or class probabilities.\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.\n \"\"\"\n # Save attack-specific parameters\n super().set_params(**kwargs)\n self._check_params()\n\n\nclass ReconstructionAttack(Attack):\n \"\"\"\n Abstract base class for reconstruction attack classes.\n \"\"\"\n\n attack_params = InferenceAttack.attack_params\n\n def __init__(self, estimator):\n \"\"\"\n :param estimator: A trained estimator targeted for reconstruction attack.\n \"\"\"\n super().__init__(estimator)\n\n @abc.abstractmethod\n def reconstruct(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Reconstruct the training dataset of and from the targeted estimator. This method\n should be overridden by all concrete inference attack implementations.\n\n :param x: An array with known records of the training set of `estimator`.\n :param y: An array with known labels of the training set of `estimator`, if None predicted labels will be used.\n :return: A tuple of two arrays for the reconstructed training input and labels.\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.\n \"\"\"\n # Save attack-specific parameters\n super().set_params(**kwargs)\n self._check_params()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing evasion attacks under a common interface.\n\"\"\"\n\n# pylint: disable=wrong-import-position\nimport importlib\n\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch import AdversarialPatch\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch_numpy import AdversarialPatchNumpy\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch_tensorflow import AdversarialPatchTensorFlowV2\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch_pytorch import AdversarialPatchPyTorch\nfrom art.attacks.evasion.adversarial_texture.adversarial_texture_pytorch import AdversarialTexturePyTorch\nfrom art.attacks.evasion.adversarial_asr import CarliniWagnerASR\nfrom art.attacks.evasion.auto_attack import AutoAttack\nfrom art.attacks.evasion.auto_projected_gradient_descent import AutoProjectedGradientDescent\nfrom art.attacks.evasion.auto_conjugate_gradient import AutoConjugateGradient\nfrom art.attacks.evasion.rescaling_auto_conjugate_gradient import RescalingAutoConjugateGradient\n\nif importlib.util.find_spec(\"numba\") is not None:\n from art.attacks.evasion.brendel_bethge import BrendelBethgeAttack\n\nfrom art.attacks.evasion.boundary import BoundaryAttack\nfrom art.attacks.evasion.composite_adversarial_attack import CompositeAdversarialAttackPyTorch\nfrom art.attacks.evasion.carlini import CarliniL2Method, CarliniLInfMethod, CarliniL0Method\nfrom art.attacks.evasion.decision_tree_attack import DecisionTreeAttack\nfrom art.attacks.evasion.deepfool import DeepFool\nfrom art.attacks.evasion.dpatch import DPatch\nfrom art.attacks.evasion.dpatch_robust import RobustDPatch\nfrom art.attacks.evasion.elastic_net import ElasticNet\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.attacks.evasion.frame_saliency import FrameSaliencyAttack\nfrom art.attacks.evasion.feature_adversaries.feature_adversaries_numpy import FeatureAdversariesNumpy\nfrom art.attacks.evasion.feature_adversaries.feature_adversaries_pytorch import FeatureAdversariesPyTorch\nfrom art.attacks.evasion.feature_adversaries.feature_adversaries_tensorflow import FeatureAdversariesTensorFlowV2\nfrom art.attacks.evasion.geometric_decision_based_attack import GeoDA\nfrom art.attacks.evasion.graphite.graphite_blackbox import GRAPHITEBlackbox\nfrom art.attacks.evasion.graphite.graphite_whitebox_pytorch import GRAPHITEWhiteboxPyTorch\nfrom art.attacks.evasion.hclu import HighConfidenceLowUncertainty\nfrom art.attacks.evasion.hop_skip_jump import HopSkipJump\nfrom art.attacks.evasion.imperceptible_asr.imperceptible_asr import ImperceptibleASR\nfrom art.attacks.evasion.imperceptible_asr.imperceptible_asr_pytorch import ImperceptibleASRPyTorch\nfrom art.attacks.evasion.iterative_method import BasicIterativeMethod\nfrom art.attacks.evasion.laser_attack.laser_attack import LaserAttack\nfrom art.attacks.evasion.lowprofool import LowProFool\nfrom art.attacks.evasion.momentum_iterative_method import MomentumIterativeMethod\nfrom art.attacks.evasion.newtonfool import NewtonFool\nfrom art.attacks.evasion.overload.overload import OverloadPyTorch\nfrom art.attacks.evasion.pe_malware_attack import MalwareGDTensorFlow\nfrom art.attacks.evasion.pixel_threshold import PixelAttack\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_numpy import (\n ProjectedGradientDescentNumpy,\n)\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_pytorch import (\n ProjectedGradientDescentPyTorch,\n)\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_tensorflow_v2 import (\n ProjectedGradientDescentTensorFlowV2,\n)\nfrom art.attacks.evasion.over_the_air_flickering.over_the_air_flickering_pytorch import OverTheAirFlickeringPyTorch\nfrom art.attacks.evasion.saliency_map import SaliencyMapMethod\nfrom art.attacks.evasion.shadow_attack import ShadowAttack\nfrom art.attacks.evasion.simba import SimBA\nfrom art.attacks.evasion.spatial_transformation import SpatialTransformation\nfrom art.attacks.evasion.steal_now_attack_later.steal_now_attack_later import SNAL\nfrom art.attacks.evasion.square_attack import SquareAttack\nfrom art.attacks.evasion.pixel_threshold import ThresholdAttack\nfrom art.attacks.evasion.universal_perturbation import UniversalPerturbation\nfrom art.attacks.evasion.targeted_universal_perturbation import TargetedUniversalPerturbation\nfrom art.attacks.evasion.virtual_adversarial import VirtualAdversarialMethod\nfrom art.attacks.evasion.wasserstein import Wasserstein\nfrom art.attacks.evasion.zoo import ZooAttack\nfrom art.attacks.evasion.sign_opt import SignOPTAttack\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_asr.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the audio adversarial attack on automatic speech recognition systems of Carlini and Wagner\n(2018). It generates an adversarial audio example.\n\n| Paper link: https://arxiv.org/abs/1801.01944\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.imperceptible_asr.imperceptible_asr import ImperceptibleASR\n\nif TYPE_CHECKING:\n from art.utils import SPEECH_RECOGNIZER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass CarliniWagnerASR(ImperceptibleASR):\n \"\"\"\n Implementation of the Carlini and Wagner audio adversarial attack against a speech recognition model.\n\n | Paper link: https://arxiv.org/abs/1801.01944\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"eps\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"decrease_factor_eps\",\n \"num_iter_decrease_eps\",\n ]\n\n def __init__(\n self,\n estimator: \"SPEECH_RECOGNIZER_TYPE\",\n eps: float = 2000.0,\n learning_rate: float = 100.0,\n max_iter: int = 1000,\n decrease_factor_eps: float = 0.8,\n num_iter_decrease_eps: int = 10,\n batch_size: int = 16,\n ):\n \"\"\"\n Create an instance of the :class:`.CarliniWagnerASR`.\n\n :param estimator: A trained speech recognition estimator.\n :param eps: Initial max norm bound for adversarial perturbation.\n :param learning_rate: Learning rate of attack.\n :param max_iter: Number of iterations.\n :param decrease_factor_eps: Decrease factor for epsilon (Paper default: 0.8).\n :param num_iter_decrease_eps: Iterations after which to decrease epsilon if attack succeeds (Paper default: 10).\n :param batch_size: Batch size.\n \"\"\"\n # pylint: disable=super-init-not-called\n\n # re-implement init such that inherited methods work\n EvasionAttack.__init__(self, estimator=estimator) # pylint: disable=non-parent-init-called\n self.masker = None # type: ignore\n self.eps = eps\n self.learning_rate_1 = learning_rate\n self.max_iter_1 = max_iter\n self.max_iter_2 = 0\n self._targeted = True\n self.decrease_factor_eps = decrease_factor_eps\n self.num_iter_decrease_eps = num_iter_decrease_eps\n self.batch_size = batch_size\n\n # set remaining stage 2 params to some random values\n self.alpha = 0.1\n self.learning_rate_2 = 0.1\n self.loss_theta_min = 0.0\n self.increase_factor_alpha: float = 1.0\n self.num_iter_increase_alpha: int = 1\n self.decrease_factor_alpha: float = 1.0\n self.num_iter_decrease_alpha: int = 1\n\n self._check_params()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/auto_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the `AutoAttack` attack.\n\n| Paper link: https://arxiv.org/abs/2003.01690\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.auto_projected_gradient_descent import AutoProjectedGradientDescent\nfrom art.attacks.evasion.deepfool import DeepFool\nfrom art.attacks.evasion.square_attack import SquareAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.estimator import BaseEstimator\nfrom art.utils import check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AutoAttack(EvasionAttack):\n \"\"\"\n Implementation of the `AutoAttack` attack.\n\n | Paper link: https://arxiv.org/abs/2003.01690\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"attacks\",\n \"batch_size\",\n \"estimator_orig\",\n \"targeted\",\n \"parallel\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n # Identify samples yet to have attack metadata identified\n SAMPLE_DEFAULT = -1\n # Identify samples misclassified therefore no attack metadata required\n SAMPLE_MISCLASSIFIED = -2\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\",\n norm: int | float | str = np.inf,\n eps: float = 0.3,\n eps_step: float = 0.1,\n attacks: list[EvasionAttack] | None = None,\n batch_size: int = 32,\n estimator_orig: \"CLASSIFIER_TYPE\" | None = None,\n targeted: bool = False,\n parallel_pool_size: int = 0,\n ):\n \"\"\"\n Create a :class:`.AutoAttack` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param attacks: The list of `art.attacks.EvasionAttack` attacks to be used for AutoAttack. If it is `None` or\n empty the standard attacks (PGD, APGD-ce, APGD-dlr, DeepFool, Square) will be used.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param estimator_orig: Original estimator to be attacked by adversarial examples.\n :param targeted: If False run only untargeted attacks, if True also run targeted attacks against each possible\n target.\n :param parallel_pool_size: Number of parallel threads / pool size in multiprocessing. If parallel_pool_size=0\n computation runs without multiprocessing.\n \"\"\"\n super().__init__(estimator=estimator)\n\n if attacks is None or not attacks:\n attacks = []\n attacks.append(\n AutoProjectedGradientDescent(\n estimator=estimator, # type: ignore\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=100,\n targeted=False,\n nb_random_init=5,\n batch_size=batch_size,\n loss_type=\"cross_entropy\",\n )\n )\n attacks.append(\n AutoProjectedGradientDescent(\n estimator=estimator, # type: ignore\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=100,\n targeted=False,\n nb_random_init=5,\n batch_size=batch_size,\n loss_type=\"difference_logits_ratio\",\n )\n )\n attacks.append(\n (\n DeepFool(\n classifier=estimator, # type: ignore\n max_iter=100,\n epsilon=1e-3,\n nb_grads=10,\n batch_size=batch_size,\n )\n )\n )\n attacks.append(\n SquareAttack(estimator=estimator, norm=norm, max_iter=5000, eps=eps, p_init=0.8, nb_restarts=5)\n )\n\n self.norm = norm\n self.eps = eps\n self.eps_step = eps_step\n self.attacks = attacks\n self.batch_size = batch_size\n if estimator_orig is not None:\n self.estimator_orig = estimator_orig\n else:\n self.estimator_orig = estimator\n\n self._targeted = targeted\n self.parallel_pool_size = parallel_pool_size\n self.best_attacks: np.ndarray = np.array([])\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n import multiprocess\n\n x_adv = x.astype(ART_NUMPY_DTYPE)\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n # Determine correctly predicted samples\n y_pred = self.estimator_orig.predict(x.astype(ART_NUMPY_DTYPE))\n sample_is_robust = np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)\n\n # Set slots for images which have yet to be filled as SAMPLE_DEFAULT\n self.best_attacks = np.array([self.SAMPLE_DEFAULT] * len(x))\n # Set samples that are misclassified and do not need to be filled as SAMPLE_MISCLASSIFIED\n self.best_attacks[np.logical_not(sample_is_robust)] = self.SAMPLE_MISCLASSIFIED\n\n args = []\n # Untargeted attacks\n for attack in self.attacks:\n\n # Stop if all samples are misclassified\n if np.sum(sample_is_robust) == 0:\n break\n\n if attack.targeted:\n attack.set_params(targeted=False)\n\n if self.parallel_pool_size > 0:\n attack.estimator._optimizer = None\n self.estimator._optimizer = None\n\n args.append(\n (\n deepcopy(x_adv),\n deepcopy(y),\n deepcopy(sample_is_robust),\n deepcopy(attack),\n deepcopy(self.estimator),\n deepcopy(self.norm),\n deepcopy(self.eps),\n )\n )\n else:\n x_adv, sample_is_robust = run_attack(\n x=x_adv,\n y=y,\n sample_is_robust=sample_is_robust,\n attack=attack,\n estimator_orig=self.estimator,\n norm=self.norm,\n eps=self.eps,\n **kwargs,\n )\n # create a mask which identifies images which this attack was effective on\n # not including originally misclassified images\n atk_mask = np.logical_and(\n np.array([i == self.SAMPLE_DEFAULT for i in self.best_attacks]), np.logical_not(sample_is_robust)\n )\n # update attack at image index with index of attack that was successful\n self.best_attacks[atk_mask] = self.attacks.index(attack)\n\n # Targeted attacks\n if self.targeted:\n # Labels for targeted attacks\n y_t = np.array([range(y.shape[1])] * y.shape[0])\n y_idx = np.argmax(y, axis=1)\n y_idx = np.expand_dims(y_idx, 1)\n y_t = y_t[y_t != y_idx]\n targeted_labels = np.reshape(y_t, (y.shape[0], self.SAMPLE_DEFAULT))\n\n for attack in self.attacks:\n\n try:\n attack.set_params(targeted=True)\n\n for i in range(self.estimator.nb_classes - 1):\n # Stop if all samples are misclassified\n if np.sum(sample_is_robust) == 0:\n break\n\n target = check_and_transform_label_format(\n targeted_labels[:, i], nb_classes=self.estimator.nb_classes\n )\n\n if self.parallel_pool_size > 0:\n attack.estimator._optimizer = None\n self.estimator._optimizer = None\n\n args.append(\n (\n deepcopy(x_adv),\n deepcopy(target),\n deepcopy(sample_is_robust),\n deepcopy(attack),\n deepcopy(self.estimator),\n deepcopy(self.norm),\n deepcopy(self.eps),\n )\n )\n else:\n x_adv, sample_is_robust = run_attack(\n x=x_adv,\n y=target,\n sample_is_robust=sample_is_robust,\n attack=attack,\n estimator_orig=self.estimator,\n norm=self.norm,\n eps=self.eps,\n **kwargs,\n )\n # create a mask which identifies images which this attack was effective on\n # not including originally misclassified images\n atk_mask = np.logical_and(\n np.array([i == self.SAMPLE_DEFAULT for i in self.best_attacks]),\n np.logical_not(sample_is_robust),\n )\n # update attack at image index with index of attack that was successful\n self.best_attacks[atk_mask] = self.attacks.index(attack)\n except ValueError as error:\n logger.warning(\"Error completing attack: %s}\", str(error))\n\n if self.parallel_pool_size > 0:\n with multiprocess.get_context(\"spawn\").Pool(processes=self.parallel_pool_size) as pool:\n # Results come back in the order that they were issued\n results = pool.starmap(run_attack, args)\n perturbations = []\n is_robust = []\n for img_idx in range(len(x)):\n perturbations.append(np.array([np.linalg.norm(x[img_idx] - i[0][img_idx]) for i in results]))\n is_robust.append([i[1][img_idx] for i in results])\n best_attacks = np.argmin(np.where(np.invert(np.array(is_robust)), np.array(perturbations), np.inf), axis=1)\n x_adv = np.concatenate([results[best_attacks[img]][0][[img]] for img in range(len(x))])\n self.best_attacks = best_attacks\n self.args = args\n return x_adv\n\n def _check_params(self) -> None:\n if self.norm not in [1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, \"inf\".')\n\n if not isinstance(self.eps, (int, float)) or self.eps <= 0.0:\n raise ValueError(\"The argument eps has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.eps_step, (int, float)) or self.eps_step <= 0.0:\n raise ValueError(\"The argument eps_step has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The argument batch_size has to be of type int and larger than zero.\")\n\n def __repr__(self) -> str:\n \"\"\"\n This method returns a summary of the best performing (lowest perturbation in the parallel case) attacks\n per image passed to the AutoAttack class.\n \"\"\"\n if self.parallel_pool_size > 0:\n best_attack_meta = \"\\n\".join(\n [\n f\"image {i+1}: {str(self.args[idx][3])}\" if idx != 0 else f\"image {i+1}: n/a\"\n for i, idx in enumerate(self.best_attacks)\n ]\n )\n auto_attack_meta = (\n f\"AutoAttack(targeted={self.targeted}, parallel_pool_size={self.parallel_pool_size}, \"\n + f\"num_attacks={len(self.args)})\"\n )\n return f\"{auto_attack_meta}\\nBestAttacks:\\n{best_attack_meta}\"\n\n best_attack_meta = \"\\n\".join(\n [\n f\"image {i+1}: {str(self.attacks[idx])}\" if idx != -2 else f\"image {i+1}: n/a\"\n for i, idx in enumerate(self.best_attacks)\n ]\n )\n auto_attack_meta = (\n f\"AutoAttack(targeted={self.targeted}, parallel_pool_size={self.parallel_pool_size}, \"\n + f\"num_attacks={len(self.attacks)})\"\n )\n return f\"{auto_attack_meta}\\nBestAttacks:\\n{best_attack_meta}\"\n\n\ndef run_attack(\n x: np.ndarray,\n y: np.ndarray,\n sample_is_robust: np.ndarray,\n attack: EvasionAttack,\n estimator_orig: \"CLASSIFIER_TYPE\",\n norm: int | float | str = np.inf,\n eps: float = 0.3,\n **kwargs,\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Run attack.\n\n :param x: An array of the original inputs.\n :param y: An array of the labels.\n :param sample_is_robust: Store the initial robustness of examples.\n :param attack: Evasion attack to run.\n :param estimator_orig: Original estimator to be attacked by adversarial examples.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param eps: Maximum perturbation that the attacker can introduce.\n :return: An array holding the adversarial examples.\n \"\"\"\n # Attack only correctly classified samples\n x_robust = x[sample_is_robust]\n y_robust = y[sample_is_robust]\n\n # Generate adversarial examples\n x_robust_adv = attack.generate(x=x_robust, y=y_robust, **kwargs)\n y_pred_robust_adv = estimator_orig.predict(x_robust_adv)\n\n # Check and update successful examples\n rel_acc = 1e-4\n order = np.inf if norm == \"inf\" else norm\n assert isinstance(order, (int, float))\n norm_is_smaller_eps = (1 - rel_acc) * np.linalg.norm(\n (x_robust_adv - x_robust).reshape((x_robust_adv.shape[0], -1)), axis=1, ord=order\n ) <= eps\n\n if attack.targeted:\n samples_misclassified = np.argmax(y_pred_robust_adv, axis=1) == np.argmax(y_robust, axis=1)\n elif not attack.targeted:\n samples_misclassified = np.argmax(y_pred_robust_adv, axis=1) != np.argmax(y_robust, axis=1)\n else: # pragma: no cover\n raise ValueError\n\n sample_is_not_robust = np.logical_and(samples_misclassified, norm_is_smaller_eps)\n\n x_robust[sample_is_not_robust] = x_robust_adv[sample_is_not_robust]\n x[sample_is_robust] = x_robust\n\n sample_is_robust[sample_is_robust] = np.invert(sample_is_not_robust)\n\n return x, sample_is_robust\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/auto_conjugate_gradient.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n\n# Copyright (c) 2022 Keiichiro Yamamura\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the 'Auto Conjugate Gradient' attack.\n\n| Paper link: https://arxiv.org/abs/2206.09628\n\"\"\"\nfrom __future__ import annotations\n\nimport abc\nimport logging\nimport math\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format, projection, random_sphere, is_probability, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AutoConjugateGradient(EvasionAttack):\n \"\"\"\n Implementation of the 'Auto Conjugate Gradient' attack.\n The original implementation is https://github.com/yamamura-k/ACG.\n\n | Paper link: https://arxiv.org/abs/2206.09628\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"max_iter\",\n \"targeted\",\n \"nb_random_init\",\n \"batch_size\",\n \"loss_type\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n _predefined_losses = [None, \"cross_entropy\", \"difference_logits_ratio\"]\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n norm: int | float | str = np.inf,\n eps: float = 0.3,\n eps_step: float = 0.1,\n max_iter: int = 100,\n targeted: bool = False,\n nb_random_init: int = 5,\n batch_size: int = 32,\n loss_type: str | None = None,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.AutoConjugateGradient` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param nb_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0\n starting at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param loss_type: Defines the loss to attack. Available options: None (Use loss defined by estimator),\n \"cross_entropy\", or \"difference_logits_ratio\"\n :param verbose: Show progress bars.\n \"\"\"\n from art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier\n\n if loss_type not in self._predefined_losses:\n raise ValueError(\n f\"The argument loss_type has an invalid value. The following options for `loss_type` are currently \"\n f\"supported: {self._predefined_losses}\"\n )\n\n if loss_type is None:\n if hasattr(estimator, \"predict\") and is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=np.float32))\n ):\n raise ValueError( # pragma: no cover\n \"AutoProjectedGradientDescent is expecting logits as estimator output, the provided \"\n \"estimator seems to predict probabilities.\"\n )\n\n estimator_acg = estimator\n else:\n if isinstance(estimator, TensorFlowV2Classifier):\n import tensorflow as tf\n\n class TensorFlowV2Loss:\n \"\"\"abstract class of loss function of tensorflow v2\"\"\"\n\n @abc.abstractmethod\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n raise NotImplementedError\n\n if loss_type == \"cross_entropy\":\n\n class CrossEntropyLossV2(TensorFlowV2Loss):\n \"\"\"Class defining cross entropy loss with reduction options.\"\"\"\n\n def __init__(self, from_logits, reduction=\"sum\"):\n self.ce_loss = tf.keras.losses.CategoricalCrossentropy(\n from_logits=from_logits,\n reduction=tf.keras.losses.Reduction.NONE,\n )\n self.reduction = reduction\n\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n if self.reduction == \"mean\":\n return tf.reduce_mean(self.ce_loss(y_true, y_pred))\n if self.reduction == \"sum\":\n return tf.reduce_sum(self.ce_loss(y_true, y_pred))\n if self.reduction == \"none\":\n return self.ce_loss(y_true, y_pred)\n raise NotImplementedError()\n\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n _loss_object_tf: TensorFlowV2Loss = CrossEntropyLossV2(from_logits=False)\n else:\n _loss_object_tf = CrossEntropyLossV2(from_logits=True)\n elif loss_type == \"difference_logits_ratio\":\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. \"\n \"If loss_type='difference_logits_ratio' the estimator has to to predict logits.\"\n )\n\n class DifferenceLogitsRatioTensorFlowV2(TensorFlowV2Loss):\n \"\"\"\n Callable class for Difference Logits Ratio loss in TensorFlow v2.\n \"\"\"\n\n def __init__(self):\n self.reduction = \"sum\"\n\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n i_y_true = tf.cast(tf.math.argmax(tf.cast(y_true, tf.int32), axis=1), tf.int32)\n i_y_pred_arg = tf.argsort(y_pred, axis=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = tf.stack(i_z_i_list)\n\n z_1 = tf.gather(y_pred, i_y_pred_arg[:, -1], axis=1, batch_dims=0)\n z_3 = tf.gather(y_pred, i_y_pred_arg[:, -3], axis=1, batch_dims=0)\n z_i = tf.gather(y_pred, i_z_i, axis=1, batch_dims=0)\n z_y = tf.gather(y_pred, i_y_true, axis=1, batch_dims=0)\n\n z_1 = tf.linalg.diag_part(z_1)\n z_3 = tf.linalg.diag_part(z_3)\n z_i = tf.linalg.diag_part(z_i)\n z_y = tf.linalg.diag_part(z_y)\n\n dlr = -(z_y - z_i) / (z_1 - z_3)\n if self.reduction == \"mean\":\n return tf.reduce_mean(dlr)\n if self.reduction == \"sum\":\n return tf.reduce_sum(dlr)\n if self.reduction == \"none\":\n return dlr\n raise NotImplementedError()\n\n _loss_object_tf = DifferenceLogitsRatioTensorFlowV2()\n\n estimator_acg = TensorFlowV2Classifier(\n model=estimator.model,\n nb_classes=estimator.nb_classes,\n input_shape=estimator.input_shape,\n loss_object=_loss_object_tf,\n optimizer=estimator.optimizer,\n train_step=estimator.train_step,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n )\n elif isinstance(estimator, PyTorchClassifier):\n import torch\n\n if loss_type == \"cross_entropy\":\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=np.float32))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. If loss_type='cross_entropy' \"\n \"the estimator has to to predict logits.\"\n )\n\n class CrossEntropyLossTorch(torch.nn.modules.loss._Loss):\n \"\"\"Class defining cross entropy loss with reduction options.\"\"\"\n\n def __init__(self, reduction=\"sum\"):\n super().__init__()\n self.ce_loss = torch.nn.CrossEntropyLoss(reduction=\"none\")\n self.reduction = reduction\n\n def __call__(self, y_true: torch.Tensor, y_pred: torch.Tensor, *args, **kwargs) -> torch.Tensor:\n if self.reduction == \"mean\":\n return self.ce_loss(y_true, y_pred).mean()\n if self.reduction == \"sum\":\n return self.ce_loss(y_true, y_pred).sum()\n if self.reduction == \"none\":\n return self.ce_loss(y_true, y_pred)\n raise NotImplementedError()\n\n def forward(\n self, input: torch.Tensor, target: torch.Tensor # pylint: disable=redefined-builtin\n ) -> torch.Tensor:\n \"\"\"\n Forward method.\n :param input: Predicted labels of shape (nb_samples, nb_classes).\n :param target: Target labels of shape (nb_samples, nb_classes).\n :return: Difference Logits Ratio Loss.\n \"\"\"\n return self.__call__(y_true=target, y_pred=input)\n\n _loss_object_pt: torch.nn.modules.loss._Loss = CrossEntropyLossTorch(reduction=\"mean\")\n\n elif loss_type == \"difference_logits_ratio\":\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=ART_NUMPY_DTYPE))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. \"\n \"If loss_type='difference_logits_ratio' the estimator has to to predict logits.\"\n )\n\n class DifferenceLogitsRatioPyTorch(torch.nn.modules.loss._Loss):\n \"\"\"\n Callable class for Difference Logits Ratio loss in PyTorch.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.reduction = \"sum\"\n\n def __call__(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:\n if isinstance(y_true, np.ndarray):\n y_true = torch.from_numpy(y_true)\n if isinstance(y_pred, np.ndarray):\n y_pred = torch.from_numpy(y_pred)\n\n y_true = y_true.float()\n\n i_y_true = torch.argmax(y_true, dim=1)\n i_y_pred_arg = torch.argsort(y_pred, dim=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = torch.stack(i_z_i_list)\n\n z_1 = y_pred[:, i_y_pred_arg[:, -1]]\n z_3 = y_pred[:, i_y_pred_arg[:, -3]]\n z_i = y_pred[:, i_z_i]\n z_y = y_pred[:, i_y_true]\n\n z_1 = torch.diagonal(z_1)\n z_3 = torch.diagonal(z_3)\n z_i = torch.diagonal(z_i)\n z_y = torch.diagonal(z_y)\n\n dlr = (-(z_y - z_i) / (z_1 - z_3)).float()\n if self.reduction == \"mean\":\n return dlr.mean()\n if self.reduction == \"sum\":\n return dlr.sum()\n if self.reduction == \"none\":\n return dlr\n raise NotImplementedError()\n\n def forward(\n self, input: torch.Tensor, target: torch.Tensor # pylint: disable=redefined-builtin\n ) -> torch.Tensor:\n \"\"\"\n Forward method.\n :param input: Predicted labels of shape (nb_samples, nb_classes).\n :param target: Target labels of shape (nb_samples, nb_classes).\n :return: Difference Logits Ratio Loss.\n \"\"\"\n return self.__call__(y_true=target, y_pred=input)\n\n _loss_object_pt = DifferenceLogitsRatioPyTorch()\n else:\n raise NotImplementedError()\n\n estimator_acg = PyTorchClassifier(\n model=estimator.model,\n loss=_loss_object_pt,\n input_shape=estimator.input_shape,\n nb_classes=estimator.nb_classes,\n optimizer=None,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n device_type=str(estimator._device),\n )\n\n else: # pragma: no cover\n raise ValueError(f\"The loss type {loss_type} is not supported for the provided estimator.\")\n\n super().__init__(estimator=estimator_acg)\n self.norm = norm\n self.eps = eps\n self.eps_step = eps_step\n self.max_iter = max_iter\n self.targeted = targeted\n self.nb_random_init = nb_random_init\n self.batch_size = batch_size\n self.loss_type = loss_type\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = kwargs.get(\"mask\")\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)).astype(int)\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n for _ in trange(max(1, self.nb_random_init), desc=\"ACG - restart\", disable=not self.verbose):\n # Determine correctly predicted samples\n y_pred = self.estimator.predict(x_adv)\n if self.targeted:\n sample_is_robust = np.argmax(y_pred, axis=1) != np.argmax(y, axis=1)\n elif not self.targeted:\n sample_is_robust = np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)\n\n if np.sum(sample_is_robust) == 0:\n break\n\n x_robust = x_adv[sample_is_robust]\n y_robust = y[sample_is_robust]\n x_init = x[sample_is_robust]\n\n n = x_robust.shape[0]\n m = np.prod(x_robust.shape[1:]).item()\n random_perturbation = (\n random_sphere(n, m, self.eps, self.norm).reshape(x_robust.shape).astype(ART_NUMPY_DTYPE)\n )\n\n x_robust = x_robust + random_perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_robust = np.clip(x_robust, clip_min, clip_max)\n\n perturbation = projection(x_robust - x_init, self.eps, self.norm)\n x_robust = x_init + perturbation\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_robust.shape[0] / float(self.batch_size))),\n desc=\"ACG - batch\",\n leave=False,\n disable=not self.verbose,\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_k = x_robust[batch_index_1:batch_index_2].astype(ART_NUMPY_DTYPE)\n x_init_batch = x_init[batch_index_1:batch_index_2].astype(ART_NUMPY_DTYPE)\n y_batch = y_robust[batch_index_1:batch_index_2]\n\n p_0 = 0\n p_1 = 0.22\n var_w = [p_0, p_1]\n\n while True:\n p_j_p_1 = var_w[-1] + max(var_w[-1] - var_w[-2] - 0.03, 0.06)\n if p_j_p_1 > 1:\n break\n var_w.append(p_j_p_1)\n\n var_w = [math.ceil(p * self.max_iter) for p in var_w]\n\n # self.eta = np.full((self.batch_size, 1, 1, 1), 2 * self.eps_step).astype(ART_NUMPY_DTYPE)\n _batch_size = x_k.shape[0]\n eta = np.full((_batch_size,) + (1,) * len(self.estimator.input_shape), self.eps_step).astype(\n ART_NUMPY_DTYPE\n )\n self.count_condition_1 = np.zeros(shape=(_batch_size,))\n gradk_1 = np.zeros_like(x_k)\n cgradk_1 = np.zeros_like(x_k)\n cgradk = np.zeros_like(x_k)\n gradk_1_best = np.zeros_like(x_k)\n cgradk_1_best = np.zeros_like(x_k)\n gradk_1_tmp = np.zeros_like(x_k)\n cgradk_1_tmp = np.zeros_like(x_k)\n\n for k_iter in trange(self.max_iter, desc=\"ACG - iteration\", leave=False, disable=not self.verbose):\n\n # Get perturbation, use small scalar to avoid division by 0\n tol = 10e-8\n\n # Get gradient wrt loss; invert it if attack is targeted\n grad = self.estimator.loss_gradient(x_k, y_batch) * (1 - 2 * int(self.targeted))\n if k_iter == 0:\n gradk_1 = grad.copy()\n cgradk_1 = grad.copy()\n cgradk = grad.copy()\n else:\n beta = get_beta(grad, gradk_1, cgradk_1)\n cgradk = grad + beta * cgradk_1\n\n # Apply norm bound\n if self.norm in [np.inf, \"inf\"]:\n grad = np.sign(cgradk)\n elif self.norm == 1:\n ind = tuple(range(1, len(x_k.shape)))\n cgradk = cgradk / (np.sum(np.abs(cgradk), axis=ind, keepdims=True) + tol)\n elif self.norm == 2:\n ind = tuple(range(1, len(x_k.shape)))\n cgradk = cgradk / (np.sqrt(np.sum(np.square(cgradk), axis=ind, keepdims=True)) + tol)\n assert x_k.shape == cgradk.shape\n\n perturbation = cgradk\n\n if mask is not None:\n perturbation = perturbation * (mask.astype(ART_NUMPY_DTYPE))\n\n # Apply perturbation and clip\n x_k_p_1 = x_k + eta * perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_k_p_1 = np.clip(x_k_p_1, clip_min, clip_max)\n\n if k_iter == 0:\n x_1 = x_k_p_1\n perturbation = projection(x_1 - x_init_batch, self.eps, self.norm)\n x_1 = x_init_batch + perturbation\n\n f_0 = self.estimator.compute_loss(x=x_k, y=y_batch, reduction=\"none\")\n f_1 = self.estimator.compute_loss(x=x_1, y=y_batch, reduction=\"none\")\n\n self.eta_w_j_m_1 = eta.copy()\n self.f_max_w_j_m_1 = f_0.copy()\n\n self.f_max = f_0.copy()\n self.x_max = x_k.copy()\n\n f1_ge_f0 = f_1 >= f_0\n f_1_tmp = f_1[f1_ge_f0].copy()\n self.f_max[f1_ge_f0] = f_1_tmp.copy()\n x_1_tmp = x_1[f1_ge_f0].copy()\n self.x_max[f1_ge_f0] = x_1_tmp.copy()\n self.count_condition_1[f1_ge_f0] += 1\n\n # Settings for next iteration k\n x_k = x_1\n gradk_1_best = gradk_1.copy()\n cgradk_1_best = cgradk_1.copy()\n\n else:\n perturbation = projection(x_k_p_1 - x_init_batch, self.eps, self.norm)\n x_k_p_1 = x_init_batch + perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_k_p_1 = np.clip(x_k_p_1, clip_min, clip_max)\n\n perturbation = projection(x_k_p_1 - x_init_batch, self.eps, self.norm)\n x_k_p_1 = x_init_batch + perturbation\n\n f_k_p_1 = self.estimator.compute_loss(x=x_k_p_1, y=y_batch, reduction=\"none\")\n\n if (f_k_p_1 == 0.0).all():\n x_k = x_k_p_1.copy()\n break\n\n if self.targeted:\n fk_ge_fm = f_k_p_1 < self.f_max # assume the loss function is cross-entropy\n else:\n fk_ge_fm = f_k_p_1 > self.f_max\n\n self.count_condition_1[fk_ge_fm] += 1\n # update the best points\n x_k_p_1_tmp = x_k_p_1[fk_ge_fm].copy()\n self.x_max[fk_ge_fm] = x_k_p_1_tmp.copy()\n f_k_p_1_tmp = f_k_p_1[fk_ge_fm].copy()\n self.f_max[fk_ge_fm] = f_k_p_1_tmp.copy()\n gradk_1_tmp = gradk_1[fk_ge_fm].copy()\n gradk_1_best[fk_ge_fm] = gradk_1_tmp.copy()\n cgradk_1_tmp = cgradk_1[fk_ge_fm].copy()\n cgradk_1_best[fk_ge_fm] = cgradk_1_tmp.copy()\n\n # update the search points\n x_k = x_k_p_1.copy()\n gradk_1 = grad.copy()\n cgradk_1 = cgradk.copy()\n\n if k_iter in var_w:\n\n rho = 0.75\n\n condition_1 = self.count_condition_1 < rho * (k_iter - var_w[var_w.index(k_iter) - 1])\n condition_2 = np.logical_and(\n (self.eta_w_j_m_1 == eta).squeeze(), self.f_max_w_j_m_1 == self.f_max\n )\n condition = np.logical_or(condition_1, condition_2)\n\n # halve the stepsize if the condition is satisfied\n eta[condition] /= 2\n # move to the best point\n x_max_tmp = self.x_max[condition].copy()\n x_k[condition] = x_max_tmp.copy()\n gradk_1_tmp = gradk_1_best[condition].copy()\n gradk_1[condition] = gradk_1_tmp.copy()\n cgradk_1_tmp = cgradk_1_best[condition].copy()\n cgradk_1[condition] = cgradk_1_tmp.copy()\n\n self.count_condition_1[:] = 0\n self.eta_w_j_m_1 = eta.copy()\n self.f_max_w_j_m_1 = self.f_max.copy()\n\n y_pred_adv_k = self.estimator.predict(x_k)\n if self.targeted:\n sample_is_not_robust_k = np.invert(np.argmax(y_pred_adv_k, axis=1) != np.argmax(y_batch, axis=1))\n elif not self.targeted:\n sample_is_not_robust_k = np.invert(np.argmax(y_pred_adv_k, axis=1) == np.argmax(y_batch, axis=1))\n\n x_robust[batch_index_1:batch_index_2][sample_is_not_robust_k] = x_k[sample_is_not_robust_k]\n\n x_adv[sample_is_robust] = x_robust\n\n return x_adv\n\n def _check_params(self) -> None:\n if self.norm not in [1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, or \"inf\".')\n\n if not isinstance(self.eps, (int, float)) or self.eps <= 0.0:\n raise ValueError(\"The argument eps has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.eps_step, (int, float)) or self.eps_step <= 0.0:\n raise ValueError(\"The argument eps_step has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The argument max_iter has to be of type int and larger than zero.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The argument targeted has to be of bool.\")\n\n if not isinstance(self.nb_random_init, int) or self.nb_random_init <= 0:\n raise ValueError(\"The argument nb_random_init has to be of type int and larger than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The argument batch_size has to be of type int and larger than zero.\")\n\n if self.loss_type not in self._predefined_losses:\n raise ValueError(\"The argument loss_type has to be either {}.\".format(self._predefined_losses))\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n\ndef get_beta(gradk, gradk_1, cgradk_1):\n \"\"\"compute the coefficient beta required to update CG direction\"\"\"\n _batch_size = gradk.shape[0]\n _cgradk_1 = cgradk_1.reshape(_batch_size, -1)\n _gradk = -gradk.reshape(_batch_size, -1)\n _gradk_1 = -gradk_1.reshape(_batch_size, -1)\n delta_gradk = _gradk - _gradk_1\n betak = -(_gradk * delta_gradk).sum(axis=1) / (\n (_cgradk_1 * delta_gradk).sum(axis=1) + np.finfo(ART_NUMPY_DTYPE).eps\n )\n return betak.reshape((_batch_size,) + (1,) * (len(gradk.shape) - 1))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/auto_projected_gradient_descent.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the `Auto Projected Gradient Descent` attack.\n\n| Paper link: https://arxiv.org/abs/2003.01690\n\"\"\"\nfrom __future__ import annotations\n\nimport abc\nimport logging\nimport math\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format, projection, random_sphere, is_probability, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AutoProjectedGradientDescent(EvasionAttack):\n \"\"\"\n Implementation of the `Auto Projected Gradient Descent` attack.\n\n | Paper link: https://arxiv.org/abs/2003.01690\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"max_iter\",\n \"targeted\",\n \"nb_random_init\",\n \"batch_size\",\n \"loss_type\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n _predefined_losses = [None, \"cross_entropy\", \"difference_logits_ratio\"]\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n norm: int | float | str = np.inf,\n eps: float = 0.3,\n eps_step: float = 0.1,\n max_iter: int = 100,\n targeted: bool = False,\n nb_random_init: int = 5,\n batch_size: int = 32,\n loss_type: str | None = None,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.AutoProjectedGradientDescent` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param nb_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0\n starting at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param loss_type: Defines the loss to attack. Available options: None (Use loss defined by estimator),\n \"cross_entropy\", or \"difference_logits_ratio\"\n :param verbose: Show progress bars.\n \"\"\"\n from art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier\n\n if loss_type not in self._predefined_losses:\n raise ValueError(\n f\"The argument loss_type has an invalid value. The following options for `loss_type` are currently \"\n f\"supported: {self._predefined_losses}\"\n )\n\n if loss_type is None:\n if hasattr(estimator, \"predict\") and is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=np.float32))\n ):\n raise ValueError( # pragma: no cover\n \"AutoProjectedGradientDescent is expecting logits as estimator output, the provided \"\n \"estimator seems to predict probabilities.\"\n )\n\n estimator_apgd = estimator\n else:\n if isinstance(estimator, TensorFlowV2Classifier):\n import tensorflow as tf\n\n class TensorFlowV2Loss:\n \"\"\"abstract class of loss function of tensorflow v2\"\"\"\n\n @abc.abstractmethod\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n raise NotImplementedError()\n\n if loss_type == \"cross_entropy\":\n # modification for image-wise stepsize update\n class CrossEntropyLossV2(TensorFlowV2Loss):\n \"\"\"Class defining cross entropy loss with reduction options.\"\"\"\n\n def __init__(self, from_logits, reduction=\"mean\"):\n self.ce_loss = tf.keras.losses.CategoricalCrossentropy(\n from_logits=from_logits,\n reduction=tf.keras.losses.Reduction.NONE,\n )\n self.reduction = reduction\n\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n if self.reduction == \"mean\":\n return tf.reduce_mean(self.ce_loss(y_true, y_pred))\n if self.reduction == \"sum\":\n return tf.reduce_sum(self.ce_loss(y_true, y_pred))\n if self.reduction == \"none\":\n return self.ce_loss(y_true, y_pred)\n raise NotImplementedError()\n\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n _loss_object_tf: TensorFlowV2Loss = CrossEntropyLossV2(from_logits=False)\n else:\n _loss_object_tf = CrossEntropyLossV2(from_logits=True)\n elif loss_type == \"difference_logits_ratio\":\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. \"\n \"If loss_type='difference_logits_ratio' the estimator has to to predict logits.\"\n )\n\n class DifferenceLogitsRatioTensorFlowV2(TensorFlowV2Loss):\n \"\"\"\n Callable class for Difference Logits Ratio loss in TensorFlow v2.\n \"\"\"\n\n def __init__(self):\n self.reduction = \"mean\"\n\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n i_y_true = tf.cast(tf.math.argmax(tf.cast(y_true, tf.int32), axis=1), tf.int32)\n i_y_pred_arg = tf.argsort(y_pred, axis=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = tf.stack(i_z_i_list)\n\n z_1 = tf.gather(y_pred, i_y_pred_arg[:, -1], axis=1, batch_dims=0)\n z_3 = tf.gather(y_pred, i_y_pred_arg[:, -3], axis=1, batch_dims=0)\n z_i = tf.gather(y_pred, i_z_i, axis=1, batch_dims=0)\n z_y = tf.gather(y_pred, i_y_true, axis=1, batch_dims=0)\n\n z_1 = tf.linalg.diag_part(z_1)\n z_3 = tf.linalg.diag_part(z_3)\n z_i = tf.linalg.diag_part(z_i)\n z_y = tf.linalg.diag_part(z_y)\n\n dlr = -(z_y - z_i) / (z_1 - z_3)\n\n # modification for image-wise stepsize update\n if self.reduction == \"mean\":\n return tf.reduce_mean(dlr)\n if self.reduction == \"sum\":\n return tf.reduce_sum(dlr)\n if self.reduction == \"none\":\n return dlr\n raise NotImplementedError()\n\n _loss_object_tf = DifferenceLogitsRatioTensorFlowV2()\n\n estimator_apgd = TensorFlowV2Classifier(\n model=estimator.model,\n nb_classes=estimator.nb_classes,\n input_shape=estimator.input_shape,\n loss_object=_loss_object_tf,\n optimizer=estimator.optimizer,\n train_step=estimator.train_step,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n )\n elif isinstance(estimator, PyTorchClassifier):\n import torch\n\n if loss_type == \"cross_entropy\":\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=np.float32))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. If loss_type='cross_entropy' \"\n \"the estimator has to to predict logits.\"\n )\n\n # modification for image-wise stepsize update\n class CrossEntropyLossTorch(torch.nn.modules.loss._Loss):\n \"\"\"Class defining cross entropy loss with reduction options.\"\"\"\n\n def __init__(self, reduction=\"mean\"):\n super().__init__()\n self.ce_loss = torch.nn.CrossEntropyLoss(reduction=\"none\")\n self.reduction = reduction\n\n def __call__(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:\n if self.reduction == \"mean\":\n return self.ce_loss(y_pred, y_true).mean()\n if self.reduction == \"sum\":\n return self.ce_loss(y_pred, y_true).sum()\n if self.reduction == \"none\":\n return self.ce_loss(y_pred, y_true)\n raise NotImplementedError()\n\n def forward(\n self, input: torch.Tensor, target: torch.Tensor # pylint: disable=redefined-builtin\n ) -> torch.Tensor:\n \"\"\"\n Forward method.\n\n :param input: Predicted labels of shape (nb_samples, nb_classes).\n :param target: Target labels of shape (nb_samples, nb_classes).\n :return: Difference Logits Ratio Loss.\n \"\"\"\n return self.__call__(y_pred=input, y_true=target)\n\n _loss_object_pt: torch.nn.modules.loss._Loss = CrossEntropyLossTorch(reduction=\"mean\")\n\n reduce_labels = True\n int_labels = True\n probability_labels = True\n\n elif loss_type == \"difference_logits_ratio\":\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=ART_NUMPY_DTYPE))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. \"\n \"If loss_type='difference_logits_ratio' the estimator has to to predict logits.\"\n )\n\n class DifferenceLogitsRatioPyTorch(torch.nn.modules.loss._Loss):\n \"\"\"\n Callable class for Difference Logits Ratio loss in PyTorch.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.reduction = \"mean\"\n\n def __call__(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:\n if isinstance(y_true, np.ndarray):\n y_true = torch.from_numpy(y_true)\n if isinstance(y_pred, np.ndarray):\n y_pred = torch.from_numpy(y_pred)\n\n y_true = y_true.float()\n\n i_y_true = torch.argmax(y_true, dim=1)\n i_y_pred_arg = torch.argsort(y_pred, dim=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = torch.stack(i_z_i_list)\n\n z_1 = y_pred[:, i_y_pred_arg[:, -1]]\n z_3 = y_pred[:, i_y_pred_arg[:, -3]]\n z_i = y_pred[:, i_z_i]\n z_y = y_pred[:, i_y_true]\n\n z_1 = torch.diagonal(z_1)\n z_3 = torch.diagonal(z_3)\n z_i = torch.diagonal(z_i)\n z_y = torch.diagonal(z_y)\n\n # modification for image-wise stepsize update\n dlr = (-(z_y - z_i) / (z_1 - z_3)).float()\n if self.reduction == \"mean\":\n return dlr.mean()\n if self.reduction == \"sum\":\n return dlr.sum()\n if self.reduction == \"none\":\n return dlr\n raise NotImplementedError()\n\n def forward(\n self, input: torch.Tensor, target: torch.Tensor # pylint: disable=redefined-builtin\n ) -> torch.Tensor:\n \"\"\"\n Forward method.\n\n :param input: Predicted labels of shape (nb_samples, nb_classes).\n :param target: Target labels of shape (nb_samples, nb_classes).\n :return: Difference Logits Ratio Loss.\n \"\"\"\n return self.__call__(y_true=target, y_pred=input)\n\n _loss_object_pt = DifferenceLogitsRatioPyTorch()\n\n reduce_labels = False\n int_labels = False\n probability_labels = False\n else:\n raise NotImplementedError()\n\n estimator_apgd = PyTorchClassifier(\n model=estimator.model,\n loss=_loss_object_pt,\n input_shape=estimator.input_shape,\n nb_classes=estimator.nb_classes,\n optimizer=None,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n device_type=str(estimator._device),\n )\n\n estimator_apgd._reduce_labels = reduce_labels\n estimator_apgd._int_labels = int_labels\n estimator_apgd._probability_labels = probability_labels\n\n else: # pragma: no cover\n raise ValueError(f\"The loss type {loss_type} is not supported for the provided estimator.\")\n\n super().__init__(estimator=estimator_apgd)\n self.norm = norm\n self.eps = eps\n self.eps_step = eps_step\n self.max_iter = max_iter\n self.targeted = targeted\n self.nb_random_init = nb_random_init\n self.batch_size = batch_size\n self.loss_type = loss_type\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = kwargs.get(\"mask\")\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)).astype(int)\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n for _ in trange(max(1, self.nb_random_init), desc=\"AutoPGD - restart\", disable=not self.verbose):\n # Determine correctly predicted samples\n y_pred = self.estimator.predict(x_adv)\n if self.targeted:\n sample_is_robust = np.argmax(y_pred, axis=1) != np.argmax(y, axis=1)\n elif not self.targeted:\n sample_is_robust = np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)\n\n if np.sum(sample_is_robust) == 0:\n break\n\n x_robust = x_adv[sample_is_robust]\n y_robust = y[sample_is_robust]\n x_init = x[sample_is_robust]\n\n n = x_robust.shape[0]\n m = np.prod(x_robust.shape[1:]).item()\n random_perturbation = (\n random_sphere(n, m, self.eps, self.norm).reshape(x_robust.shape).astype(ART_NUMPY_DTYPE)\n )\n\n x_robust = x_robust + random_perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_robust = np.clip(x_robust, clip_min, clip_max)\n\n perturbation = projection(x_robust - x_init, self.eps, self.norm)\n x_robust = x_init + perturbation\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_robust.shape[0] / float(self.batch_size))),\n desc=\"AutoPGD - batch\",\n leave=False,\n disable=not self.verbose,\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_k = x_robust[batch_index_1:batch_index_2].astype(ART_NUMPY_DTYPE)\n x_init_batch = x_init[batch_index_1:batch_index_2].astype(ART_NUMPY_DTYPE)\n y_batch = y_robust[batch_index_1:batch_index_2]\n\n p_0 = 0\n p_1 = 0.22\n var_w = [p_0, p_1]\n\n while True:\n p_j_p_1 = var_w[-1] + max(var_w[-1] - var_w[-2] - 0.03, 0.06)\n if p_j_p_1 > 1:\n break\n var_w.append(p_j_p_1)\n\n var_w = [math.ceil(p * self.max_iter) for p in var_w]\n\n # modification for image-wise stepsize update\n _batch_size = x_k.shape[0]\n eta = np.full((_batch_size,) + (1,) * len(self.estimator.input_shape), self.eps_step).astype(\n ART_NUMPY_DTYPE\n )\n self.count_condition_1 = np.zeros(shape=(_batch_size,))\n\n for k_iter in trange(self.max_iter, desc=\"AutoPGD - iteration\", leave=False, disable=not self.verbose):\n\n # Get perturbation, use small scalar to avoid division by 0\n tol = 10e-8\n\n # Get gradient wrt loss; invert it if attack is targeted\n grad = self.estimator.loss_gradient(x_k, y_batch) * (1 - 2 * int(self.targeted))\n\n # Apply norm bound\n if self.norm in [np.inf, \"inf\"]:\n grad = np.sign(grad)\n elif self.norm == 1:\n ind = tuple(range(1, len(x_k.shape)))\n grad = grad / (np.sum(np.abs(grad), axis=ind, keepdims=True) + tol)\n elif self.norm == 2:\n ind = tuple(range(1, len(x_k.shape)))\n grad = grad / (np.sqrt(np.sum(np.square(grad), axis=ind, keepdims=True)) + tol)\n assert x_k.shape == grad.shape\n\n perturbation = grad\n\n if mask is not None:\n perturbation = perturbation * (mask.astype(ART_NUMPY_DTYPE))\n\n # Apply perturbation and clip\n z_k_p_1 = x_k + eta * perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n z_k_p_1 = np.clip(z_k_p_1, clip_min, clip_max)\n\n if k_iter == 0:\n x_1 = z_k_p_1\n perturbation = projection(x_1 - x_init_batch, self.eps, self.norm)\n x_1 = x_init_batch + perturbation\n\n f_0 = self.estimator.compute_loss(x=x_k, y=y_batch, reduction=\"none\")\n f_1 = self.estimator.compute_loss(x=x_1, y=y_batch, reduction=\"none\")\n\n # modification for image-wise stepsize update\n self.eta_w_j_m_1 = eta.copy()\n self.f_max_w_j_m_1 = f_0.copy()\n self.f_max = f_0.copy()\n self.x_max = x_k.copy()\n self.x_max_m_1 = x_init_batch.copy()\n\n f1_ge_f0 = f_1 >= f_0\n f_1_tmp = f_1[f1_ge_f0].copy()\n self.f_max[f1_ge_f0] = f_1_tmp.copy()\n x_1_tmp = x_1[f1_ge_f0].copy()\n self.x_max[f1_ge_f0] = x_1_tmp.copy()\n self.count_condition_1[f1_ge_f0] += 1\n # Settings for next iteration k\n x_k_m_1 = x_k.copy()\n x_k = x_1.copy()\n\n else:\n perturbation = projection(z_k_p_1 - x_init_batch, self.eps, self.norm)\n z_k_p_1 = x_init_batch + perturbation\n\n alpha = 0.75\n\n x_k_p_1 = x_k + alpha * (z_k_p_1 - x_k) + (1 - alpha) * (x_k - x_k_m_1)\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_k_p_1 = np.clip(x_k_p_1, clip_min, clip_max)\n\n perturbation = projection(x_k_p_1 - x_init_batch, self.eps, self.norm)\n x_k_p_1 = x_init_batch + perturbation\n\n f_k_p_1 = self.estimator.compute_loss(x=x_k_p_1, y=y_batch, reduction=\"none\")\n\n if (f_k_p_1 == 0.0).all(): # modification for image-wise stepsize update\n x_k = x_k_p_1.copy()\n break\n\n if self.targeted:\n fk_ge_fm = f_k_p_1 < self.f_max # assume the loss function is cross-entropy\n else:\n fk_ge_fm = f_k_p_1 > self.f_max\n\n self.count_condition_1[fk_ge_fm] += 1\n # update the best points\n x_k_p_1_tmp = x_k_p_1[fk_ge_fm].copy()\n self.x_max[fk_ge_fm] = x_k_p_1_tmp.copy()\n x_k_tmp = x_k[fk_ge_fm].copy()\n self.x_max_m_1[fk_ge_fm] = x_k_tmp.copy()\n f_k_p_1_tmp = f_k_p_1[fk_ge_fm].copy()\n self.f_max[fk_ge_fm] = f_k_p_1_tmp.copy()\n\n # update the search points\n x_k_m_1 = x_k.copy()\n x_k = x_k_p_1.copy()\n\n if k_iter in var_w:\n\n rho = 0.75\n\n condition_1 = self.count_condition_1 < rho * (k_iter - var_w[var_w.index(k_iter) - 1])\n condition_2 = np.logical_and(\n (self.eta_w_j_m_1 == eta).squeeze(), self.f_max_w_j_m_1 == self.f_max\n )\n condition = np.logical_or(condition_1, condition_2)\n\n # halve the stepsize if the condition is satisfied\n eta[condition] /= 2\n # move to the best point\n x_max_tmp = self.x_max[condition].copy()\n x_k[condition] = x_max_tmp.copy()\n x_max_m_1_tmp = self.x_max_m_1[condition].copy()\n x_k_m_1[condition] = x_max_m_1_tmp.copy()\n\n self.count_condition_1[:] = 0\n self.eta_w_j_m_1 = eta.copy()\n self.f_max_w_j_m_1 = self.f_max.copy()\n\n y_pred_adv_k = self.estimator.predict(x_k)\n if self.targeted:\n sample_is_not_robust_k = np.invert(np.argmax(y_pred_adv_k, axis=1) != np.argmax(y_batch, axis=1))\n elif not self.targeted:\n sample_is_not_robust_k = np.invert(np.argmax(y_pred_adv_k, axis=1) == np.argmax(y_batch, axis=1))\n\n x_robust[batch_index_1:batch_index_2][sample_is_not_robust_k] = x_k[sample_is_not_robust_k]\n\n x_adv[sample_is_robust] = x_robust\n\n return x_adv\n\n def _check_params(self) -> None:\n if self.norm not in [1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, or \"inf\".')\n\n if not isinstance(self.eps, (int, float)) or self.eps <= 0.0:\n raise ValueError(\"The argument eps has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.eps_step, (int, float)) or self.eps_step <= 0.0:\n raise ValueError(\"The argument eps_step has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The argument max_iter has to be of type int and larger than zero.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The argument targeted has to be of bool.\")\n\n if not isinstance(self.nb_random_init, int) or self.nb_random_init <= 0:\n raise ValueError(\"The argument nb_random_init has to be of type int and larger than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The argument batch_size has to be of type int and larger than zero.\")\n\n # if self.loss_type not in self._predefined_losses:\n # raise ValueError(\"The argument loss_type has to be either {}.\".format(self._predefined_losses))\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/boundary.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the boundary attack `BoundaryAttack`. This is a black-box attack which only requires class\npredictions.\n\n| Paper link: https://arxiv.org/abs/1712.04248\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm, trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import compute_success, to_categorical, check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass BoundaryAttack(EvasionAttack):\n \"\"\"\n Implementation of the boundary attack from Brendel et al. (2018). This is a powerful black-box attack that\n only requires final class prediction.\n\n | Paper link: https://arxiv.org/abs/1712.04248\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"targeted\",\n \"delta\",\n \"epsilon\",\n \"step_adapt\",\n \"max_iter\",\n \"num_trial\",\n \"sample_size\",\n \"init_size\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\",\n batch_size: int = 64,\n targeted: bool = True,\n delta: float = 0.01,\n epsilon: float = 0.01,\n step_adapt: float = 0.667,\n max_iter: int = 5000,\n num_trial: int = 25,\n sample_size: int = 20,\n init_size: int = 100,\n min_epsilon: float = 0.0,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a boundary attack instance.\n\n :param estimator: A trained classifier.\n :param batch_size: The size of the batch used by the estimator during inference.\n :param targeted: Should the attack target one specific class.\n :param delta: Initial step size for the orthogonal step.\n :param epsilon: Initial step size for the step towards the target.\n :param step_adapt: Factor by which the step sizes are multiplied or divided, must be in the range (0, 1).\n :param max_iter: Maximum number of iterations.\n :param num_trial: Maximum number of trials per iteration.\n :param sample_size: Number of samples per trial.\n :param init_size: Maximum number of trials for initial generation of adversarial examples.\n :param min_epsilon: Stop attack if perturbation is smaller than `min_epsilon`.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self._targeted = targeted\n self.delta = delta\n self.epsilon = epsilon\n self.step_adapt = step_adapt\n self.max_iter = max_iter\n self.num_trial = num_trial\n self.sample_size = sample_size\n self.init_size = init_size\n self.min_epsilon = min_epsilon\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n self.curr_adv: np.ndarray | None = None\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y` represents the target labels.\n :param x_adv_init: Initial array to act as initial adversarial examples. Same shape as `x`.\n :type x_adv_init: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)) # type: ignore\n\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=False)\n\n # Get clip_min and clip_max from the classifier or infer them from data\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.min(x), np.max(x)\n\n # Prediction from the original images\n preds = np.argmax(self.estimator.predict(x, batch_size=self.batch_size), axis=1)\n\n # Prediction from the initial adversarial examples if not None\n x_adv_init = kwargs.get(\"x_adv_init\")\n\n if x_adv_init is not None:\n init_preds = np.argmax(self.estimator.predict(x_adv_init, batch_size=self.batch_size), axis=1)\n else:\n init_preds = [None] * len(x)\n x_adv_init = [None] * len(x)\n\n # Assert that, if attack is targeted, y is provided\n if self.targeted and y is None: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Some initial setups\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n # Generate the adversarial samples\n for ind, val in enumerate(tqdm(x_adv, desc=\"Boundary attack\", disable=not self.verbose)):\n if self.targeted:\n x_adv[ind] = self._perturb(\n x=val,\n y=y[ind],\n y_p=preds[ind],\n init_pred=init_preds[ind],\n adv_init=x_adv_init[ind],\n clip_min=clip_min,\n clip_max=clip_max,\n )\n else:\n x_adv[ind] = self._perturb(\n x=val,\n y=-1,\n y_p=preds[ind],\n init_pred=init_preds[ind],\n adv_init=x_adv_init[ind],\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n y = to_categorical(y, self.estimator.nb_classes)\n\n logger.info(\n \"Success rate of Boundary attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n return x_adv\n\n def _perturb(\n self,\n x: np.ndarray,\n y: int,\n y_p: int,\n init_pred: int,\n adv_init: np.ndarray,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray:\n \"\"\"\n Internal attack function for one example.\n\n :param x: An array with one original input to be attacked.\n :param y: If `self.targeted` is true, then `y` represents the target label.\n :param y_p: The predicted label of x.\n :param init_pred: The predicted label of the initial image.\n :param adv_init: Initial array to act as an initial adversarial example.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: An adversarial example.\n \"\"\"\n # First, create an initial adversarial sample\n initial_sample = self._init_sample(x, y, y_p, init_pred, adv_init, clip_min, clip_max)\n\n # If an initial adversarial example is not found, then return the original image\n if initial_sample is None:\n return x\n\n # If an initial adversarial example found, then go with boundary attack\n x_adv = self._attack(\n initial_sample[0],\n x,\n y_p,\n initial_sample[1],\n self.delta,\n self.epsilon,\n clip_min,\n clip_max,\n )\n\n return x_adv\n\n def _attack(\n self,\n initial_sample: np.ndarray,\n original_sample: np.ndarray,\n y_p: int,\n target: int,\n initial_delta: float,\n initial_epsilon: float,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray:\n \"\"\"\n Main function for the boundary attack.\n\n :param initial_sample: An initial adversarial example.\n :param original_sample: The original input.\n :param y_p: The predicted label of the original input.\n :param target: The target label.\n :param initial_delta: Initial step size for the orthogonal step.\n :param initial_epsilon: Initial step size for the step towards the target.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: an adversarial example.\n \"\"\"\n # Get initialization for some variables\n x_adv = initial_sample\n self.curr_delta = initial_delta\n self.curr_epsilon = initial_epsilon\n\n self.curr_adv = x_adv\n\n # Main loop to wander around the boundary\n for _ in trange(self.max_iter, desc=\"Boundary attack - iterations\", disable=not self.verbose):\n # Trust region method to adjust delta\n for _ in range(self.num_trial):\n potential_advs_list: list[np.ndarray] = []\n for _ in range(self.sample_size):\n potential_adv = x_adv + self._orthogonal_perturb(self.curr_delta, x_adv, original_sample)\n potential_adv = np.clip(potential_adv, clip_min, clip_max)\n potential_advs_list.append(potential_adv)\n\n preds = np.argmax(\n self.estimator.predict(np.array(potential_advs_list), batch_size=self.batch_size),\n axis=1,\n )\n\n if self.targeted:\n satisfied = preds == target\n else:\n satisfied = preds != y_p\n\n delta_ratio = np.mean(satisfied)\n\n if delta_ratio < 0.2:\n self.curr_delta *= self.step_adapt\n elif delta_ratio > 0.5:\n self.curr_delta /= self.step_adapt\n\n if delta_ratio > 0:\n x_advs = np.array(potential_advs_list)[np.where(satisfied)[0]]\n break\n else: # pragma: no cover\n logger.warning(\"Adversarial example found but not optimal.\")\n return x_adv\n\n # Trust region method to adjust epsilon\n for _ in range(self.num_trial):\n perturb = np.repeat(np.array([original_sample]), len(x_advs), axis=0) - x_advs\n perturb *= self.curr_epsilon\n potential_advs = x_advs + perturb\n potential_advs = np.clip(potential_advs, clip_min, clip_max)\n preds = np.argmax(\n self.estimator.predict(potential_advs, batch_size=self.batch_size),\n axis=1,\n )\n\n if self.targeted:\n satisfied = preds == target\n else:\n satisfied = preds != y_p\n\n epsilon_ratio = np.mean(satisfied)\n\n if epsilon_ratio < 0.2:\n self.curr_epsilon *= self.step_adapt\n elif epsilon_ratio > 0.5:\n self.curr_epsilon /= self.step_adapt\n\n if epsilon_ratio > 0:\n x_adv = self._best_adv(original_sample, potential_advs[np.where(satisfied)[0]])\n self.curr_adv = x_adv\n break\n else: # pragma: no cover\n logger.warning(\"Adversarial example found but not optimal.\")\n return self._best_adv(original_sample, x_advs)\n\n if self.curr_epsilon < self.min_epsilon:\n return x_adv\n\n return x_adv\n\n def _orthogonal_perturb(self, delta: float, current_sample: np.ndarray, original_sample: np.ndarray) -> np.ndarray:\n \"\"\"\n Create an orthogonal perturbation.\n\n :param delta: Initial step size for the orthogonal step.\n :param current_sample: Current adversarial example.\n :param original_sample: The original input.\n :return: a possible perturbation.\n \"\"\"\n # Generate perturbation randomly\n perturb = np.random.randn(*self.estimator.input_shape).astype(ART_NUMPY_DTYPE)\n\n # Rescale the perturbation\n perturb /= np.linalg.norm(perturb)\n perturb *= delta * np.linalg.norm(original_sample - current_sample)\n\n # Project the perturbation onto sphere\n direction = original_sample - current_sample\n\n direction_flat = direction.flatten()\n perturb_flat = perturb.flatten()\n\n direction_flat /= np.linalg.norm(direction_flat)\n perturb_flat -= np.dot(perturb_flat, direction_flat.T) * direction_flat\n perturb = perturb_flat.reshape(self.estimator.input_shape)\n\n hypotenuse = np.sqrt(1 + delta**2)\n perturb = ((1 - hypotenuse) * (current_sample - original_sample) + perturb) / hypotenuse\n return perturb\n\n def _init_sample(\n self,\n x: np.ndarray,\n y: int,\n y_p: int,\n init_pred: int,\n adv_init: np.ndarray,\n clip_min: float,\n clip_max: float,\n ) -> tuple[np.ndarray, int] | None:\n \"\"\"\n Find initial adversarial example for the attack.\n\n :param x: An array with one original input to be attacked.\n :param y: If `self.targeted` is true, then `y` represents the target label.\n :param y_p: The predicted label of x.\n :param init_pred: The predicted label of the initial image.\n :param adv_init: Initial array to act as an initial adversarial example.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: an adversarial example.\n \"\"\"\n nprd = np.random.RandomState()\n initial_sample = None\n\n if self.targeted:\n # Attack satisfied\n if y == y_p:\n return None\n\n # Attack unsatisfied yet and the initial image satisfied\n if adv_init is not None and init_pred == y:\n return adv_init.astype(ART_NUMPY_DTYPE), init_pred\n\n # Attack unsatisfied yet and the initial image unsatisfied\n for _ in range(self.init_size):\n random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)\n random_class = np.argmax(\n self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),\n axis=1,\n )[0]\n\n if random_class == y:\n initial_sample = random_img, random_class\n\n logger.info(\"Found initial adversarial image for targeted attack.\")\n break\n else:\n logger.warning(\"Failed to draw a random image that is adversarial, attack failed.\")\n\n else:\n # The initial image satisfied\n if adv_init is not None and init_pred != y_p:\n return adv_init.astype(ART_NUMPY_DTYPE), init_pred\n\n # The initial image unsatisfied\n for _ in range(self.init_size):\n random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)\n random_class = np.argmax(\n self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),\n axis=1,\n )[0]\n\n if random_class != y_p:\n initial_sample = random_img, random_class\n\n logger.info(\"Found initial adversarial image for untargeted attack.\")\n break\n else: # pragma: no cover\n logger.warning(\"Failed to draw a random image that is adversarial, attack failed.\")\n\n return initial_sample\n\n @staticmethod\n def _best_adv(original_sample: np.ndarray, potential_advs: np.ndarray) -> np.ndarray:\n \"\"\"\n From the potential adversarial examples, find the one that has the minimum L2 distance from the original sample\n\n :param original_sample: The original input.\n :param potential_advs: Array containing the potential adversarial examples\n :return: The adversarial example that has the minimum L2 distance from the original input\n \"\"\"\n shape = potential_advs.shape\n min_idx = np.linalg.norm(original_sample.flatten() - potential_advs.reshape(shape[0], -1), axis=1).argmin()\n return potential_advs[min_idx]\n\n def _check_params(self) -> None:\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.num_trial, int) or self.num_trial < 0:\n raise ValueError(\"The number of trials must be a non-negative integer.\")\n\n if not isinstance(self.sample_size, int) or self.sample_size <= 0:\n raise ValueError(\"The number of samples must be a positive integer.\")\n\n if not isinstance(self.init_size, int) or self.init_size <= 0:\n raise ValueError(\"The number of initial trials must be a positive integer.\")\n\n if self.epsilon <= 0:\n raise ValueError(\"The initial step size for the step towards the target must be positive.\")\n\n if self.delta <= 0:\n raise ValueError(\"The initial step size for the orthogonal step must be positive.\")\n\n if self.step_adapt <= 0 or self.step_adapt >= 1:\n raise ValueError(\"The adaptation factor must be in the range (0, 1).\")\n\n if not isinstance(self.min_epsilon, (float, int)) or self.min_epsilon < 0:\n raise ValueError(\"The minimum epsilon must be non-negative.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/brendel_bethge.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Based on reference implementation: https://github.com/bethgelab/foolbox/blob/master/foolbox/attacks/brendel_bethge.py\n\n# MIT License\n#\n# Copyright (c) 2020 Jonas Rauber et al.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Brendel and Bethge attack.\n\"\"\"\nfrom __future__ import annotations\n\n# pylint: disable=invalid-name,missing-class-docstring,missing-function-docstring,old-non-ascii-name,unused-variable\n# pylint: disable=unused-argument,chained-comparison,no-else-return,no-else-break,no-else-raise\nfrom typing import TYPE_CHECKING\nimport logging\n\nimport numpy as np\nfrom numba.experimental import jitclass\n\nfrom art import config\nfrom art.utils import get_labels_np_array, check_and_transform_label_format, is_probability\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nEPS = 1e-10\n\nlogger = logging.getLogger(__name__)\n\n\n@jitclass(spec=[])\nclass BFGSB: # pragma: no cover\n def __init__(self):\n pass\n\n def solve(self, fun_and_jac, q0, bounds, args, ftol=1e-10, pgtol=-1e-5, maxiter=None):\n N = q0.shape[0]\n\n if maxiter is None:\n maxiter = N * 200\n\n var_l = bounds[:, 0]\n u = bounds[:, 1]\n\n func_calls = 0\n\n old_fval, gfk = fun_and_jac(q0, *args)\n func_calls += 1\n\n k = 0\n Hk = np.eye(N)\n\n # Sets the initial step guess to dx ~ 1\n qk = q0\n old_old_fval = old_fval + np.linalg.norm(gfk) / 2\n\n # gnorm = np.amax(np.abs(gfk))\n _gfk = gfk\n\n # Compare with implementation BFGS-B implementation\n # in https://github.com/andrewhooker/PopED/blob/master/R/bfgsb_min.R\n\n while k < maxiter:\n # check if projected gradient is still large enough\n pg_norm = 0\n for v in range(N):\n if _gfk[v] < 0:\n gv = max(qk[v] - u[v], _gfk[v])\n else:\n gv = min(qk[v] - var_l[v], _gfk[v])\n\n if pg_norm < np.abs(gv):\n pg_norm = np.abs(gv)\n\n if pg_norm < pgtol:\n break\n\n # get cauchy point\n x_cp = self._cauchy_point(qk, var_l, u, _gfk.copy(), Hk)\n qk1 = self._subspace_min(qk, var_l, u, x_cp, _gfk.copy(), Hk)\n pk = qk1 - qk\n\n alpha_k, fc, gc, old_fval, old_old_fval, gfkp1, fnev = self._line_search_wolfe(\n fun_and_jac, qk, pk, _gfk, old_fval, old_old_fval, var_l, u, args\n )\n func_calls += fnev\n\n if alpha_k is None:\n break\n\n if np.abs(old_fval - old_old_fval) <= (ftol + ftol * np.abs(old_fval)):\n break\n\n qkp1 = self._project(qk + alpha_k * pk, var_l, u)\n\n if gfkp1 is None:\n _, gfkp1 = fun_and_jac(qkp1, *args)\n\n sk = qkp1 - qk\n qk = qkp1\n\n yk = np.zeros_like(qk)\n for k3 in range(N):\n yk[k3] = gfkp1[k3] - _gfk[k3]\n\n if np.abs(yk[k3]) < 1e-4:\n yk[k3] = -1e-4\n\n _gfk = gfkp1\n\n k += 1\n\n # update inverse Hessian matrix\n Hk_sk = Hk.dot(sk)\n\n sk_yk = 0\n sk_Hk_sk = 0\n for v in range(N):\n sk_yk += sk[v] * yk[v]\n sk_Hk_sk += sk[v] * Hk_sk[v]\n\n if np.abs(sk_yk) >= 1e-8:\n rhok = 1.0 / sk_yk\n else:\n rhok = 100000.0\n\n if np.abs(sk_Hk_sk) >= 1e-8:\n rsk_Hk_sk = 1.0 / sk_Hk_sk\n else:\n rsk_Hk_sk = 100000.0\n\n for v in range(N):\n for w in range(N):\n Hk[v, w] += yk[v] * yk[w] * rhok - Hk_sk[v] * Hk_sk[w] * rsk_Hk_sk\n\n return qk\n\n def _cauchy_point(self, x, var_l, u, g, B):\n # finds the cauchy point for q(x)=x'Gx+x'd s$t. l<=x<=u\n # g=G*x+d #gradient of q(x)\n # converted from r-code: https://github.com/andrewhooker/PopED/blob/master/R/cauchy_point.R\n n = x.shape[0]\n t = np.zeros_like(x)\n d = np.zeros_like(x)\n\n for i in range(n):\n if g[i] < 0:\n t[i] = (x[i] - u[i]) / g[i]\n elif g[i] > 0:\n t[i] = (x[i] - var_l[i]) / g[i]\n elif g[i] == 0:\n t[i] = np.inf\n\n if t[i] == 0:\n d[i] = 0\n else:\n d[i] = -g[i]\n\n ts = t.copy()\n ts = ts[ts != 0]\n ts = np.sort(ts)\n\n df = g.dot(d)\n d2f = d.dot(B.dot(d))\n\n if d2f < 1e-10:\n return x\n\n dt_min = -df / d2f\n t_old = 0\n i = 0\n z = np.zeros_like(x)\n\n while i < ts.shape[0] and dt_min >= (ts[i] - t_old):\n ind = ts[i] < t\n d[~ind] = 0\n z = z + (ts[i] - t_old) * d\n df = g.dot(d) + d.dot(B.dot(z))\n d2f = d.dot(B.dot(d))\n dt_min = df / (d2f + 1e-8)\n t_old = ts[i]\n i += 1\n\n dt_min = max(dt_min, 0)\n t_old = t_old + dt_min\n x_cp = x - t_old * g\n temp = x - t * g\n x_cp[t_old > t] = temp[t_old > t]\n\n return x_cp\n\n def _subspace_min(self, x, var_l, u, x_cp, d, G):\n # converted from r-code: https://github.com/andrewhooker/PopED/blob/master/R/subspace_min.R\n n = x.shape[0]\n Z = np.eye(n)\n fixed = (x_cp <= var_l + 1e-8) + (x_cp >= u - 1e8)\n\n if np.all(fixed):\n x = x_cp\n return x\n\n Z = Z[:, ~fixed]\n rgc = Z.T.dot(d + G.dot(x_cp - x))\n rB = Z.T.dot(G.dot(Z)) + 1e-10 * np.eye(Z.shape[1])\n d[~fixed] = np.linalg.solve(rB, rgc)\n d[~fixed] = -d[~fixed]\n alpha = 1\n temp1 = alpha\n\n for i in np.arange(n)[~fixed]:\n dk = d[i]\n if dk < 0:\n temp2 = var_l[i] - x_cp[i]\n if temp2 >= 0:\n temp1 = 0\n else:\n if dk * alpha < temp2:\n temp1 = temp2 / dk\n else:\n temp2 = u[i] - x_cp[i]\n else:\n temp2 = u[i] - x_cp[i]\n if temp1 <= 0:\n temp1 = 0\n else:\n if dk * alpha > temp2:\n temp1 = temp2 / dk\n\n alpha = min(temp1, alpha)\n\n return x_cp + alpha * Z.dot(d[~fixed])\n\n def _project(self, q, var_l, u):\n N = q.shape[0]\n for k in range(N):\n if q[k] < var_l[k]:\n q[k] = var_l[k]\n elif q[k] > u[k]:\n q[k] = u[k]\n\n return q\n\n def _line_search_armijo(\n self,\n fun_and_jac,\n pt,\n dpt,\n func_calls,\n m,\n gk,\n var_l,\n u,\n x0,\n x,\n b,\n min_,\n max_,\n c,\n r,\n ):\n ls_rho = 0.6\n ls_c = 1e-4\n ls_alpha = 1\n\n t = m * ls_c\n\n for k2 in range(100):\n ls_pt = self._project(pt + ls_alpha * dpt, var_l, u)\n\n gkp1, dgkp1 = fun_and_jac(ls_pt, x0, x, b, min_, max_, c, r)\n func_calls += 1\n\n if gk - gkp1 >= ls_alpha * t:\n break\n else:\n ls_alpha *= ls_rho\n\n return ls_alpha, ls_pt, gkp1, dgkp1, func_calls\n\n def _line_search_wolfe(\n self,\n fun_and_jac,\n xk,\n pk,\n gfk,\n old_fval,\n old_old_fval,\n var_l,\n u,\n args,\n ):\n \"\"\"Find alpha that satisfies strong Wolfe conditions.\n Uses the line search algorithm to enforce strong Wolfe conditions\n Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-60\n For the zoom phase it uses an algorithm by\n Outputs: (alpha0, gc, fc)\n \"\"\"\n alpha_star = 0.0\n fval_star = 0.0\n fprime_star = None\n\n c1 = 1e-4\n c2 = 0.9\n N = xk.shape[0]\n _ls_fc = 0\n _ls_ingfk = None\n\n alpha0 = 0\n phi0 = old_fval\n\n derphi0 = 0\n for v in range(N):\n derphi0 += gfk[v] * pk[v]\n\n if derphi0 == 0:\n derphi0 = 1e-8\n elif np.abs(derphi0) < 1e-8:\n derphi0 = np.sign(derphi0) * 1e-8\n\n alpha1 = min(1.0, 1.01 * 2 * (phi0 - old_old_fval) / derphi0)\n\n if alpha1 == 0:\n # This shouldn't happen. Perhaps the increment has slipped below\n # machine precision? For now, set the return variables skip the\n # useless while loop, and raise warnflag=2 due to possible imprecision.\n # print(\"Slipped below machine precision.\")\n alpha_star = None\n fval_star = old_fval\n old_fval = old_old_fval\n fprime_star = None\n\n _xkp1 = self._project(xk + alpha1 * pk, var_l, u)\n phi_a1, _ls_ingfk = fun_and_jac(_xkp1, *args)\n _ls_fc += 1\n # derphi_a1 = phiprime(alpha1) evaluated below\n\n phi_a0 = phi0\n derphi_a0 = derphi0\n\n i = 1\n maxiter = 10\n while 1: # bracketing phase\n # print(\" (ls) in while loop: \", alpha1, alpha0)\n if alpha1 == 0:\n break\n if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or ((phi_a1 >= phi_a0) and (i > 1)):\n # inlining zoom for performance reasons\n # alpha0, alpha1, phi_a0, phi_a1, derphi_a0, phi0, derphi0, pk, xk\n # zoom signature: (a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi0, derphi0, pk, xk)\n # INLINE START\n k = 0\n delta1 = 0.2 # cubic interpolant check\n delta2 = 0.1 # quadratic interpolant check\n phi_rec = phi0\n a_rec = 0\n a_hi = alpha1\n a_lo = alpha0\n phi_lo = phi_a0\n phi_hi = phi_a1\n derphi_lo = derphi_a0\n while 1:\n # interpolate to find a trial step length between a_lo and a_hi\n # Need to choose interpolation here. Use cubic interpolation and then if the\n # result is within delta * dalpha or outside the interval bounded by a_lo or a_hi\n # then use quadratic interpolation, if the result is still too close, then use bisection\n\n dalpha = a_hi - a_lo\n if dalpha < 0:\n a, b = a_hi, a_lo\n else:\n a, b = a_lo, a_hi\n\n # minimizer of cubic interpolant\n # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi)\n # if the result is too close to the end points (or out of the interval)\n # then use quadratic interpolation with phi_lo, derphi_lo and phi_hi\n # if the result is stil too close to the end points (or out of the interval)\n # then use bisection\n\n if k > 0:\n cchk = delta1 * dalpha\n a_j = self._cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, a_rec, phi_rec)\n if (k == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk):\n qchk = delta2 * dalpha\n a_j = self._quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi)\n if (a_j is None) or (a_j > b - qchk) or (a_j < a + qchk):\n a_j = a_lo + 0.5 * dalpha\n\n # Check new value of a_j\n _xkp1 = self._project(xk + a_j * pk, var_l, u)\n # if _xkp1[1] < 0:\n # _xkp1[1] = 0\n phi_aj, _ls_ingfk = fun_and_jac(_xkp1, *args)\n\n derphi_aj = 0\n for v in range(N):\n derphi_aj += _ls_ingfk[v] * pk[v]\n\n if (phi_aj > phi0 + c1 * a_j * derphi0) or (phi_aj >= phi_lo):\n phi_rec = phi_hi\n a_rec = a_hi\n a_hi = a_j\n phi_hi = phi_aj\n else:\n if abs(derphi_aj) <= -c2 * derphi0:\n a_star = a_j\n val_star = phi_aj\n valprime_star = _ls_ingfk\n break\n if derphi_aj * (a_hi - a_lo) >= 0:\n phi_rec = phi_hi\n a_rec = a_hi\n a_hi = a_lo\n phi_hi = phi_lo\n else:\n phi_rec = phi_lo\n a_rec = a_lo\n a_lo = a_j\n phi_lo = phi_aj\n derphi_lo = derphi_aj\n k += 1\n if k > maxiter:\n a_star = a_j\n val_star = phi_aj\n valprime_star = None\n break\n\n alpha_star = a_star\n fval_star = val_star\n fprime_star = valprime_star\n fnev = k\n # INLINE END\n\n _ls_fc += fnev\n break\n\n i += 1\n if i > maxiter:\n break\n\n _xkp1 = self._project(xk + alpha1 * pk, var_l, u)\n _, _ls_ingfk = fun_and_jac(_xkp1, *args)\n derphi_a1 = 0\n for v in range(N):\n derphi_a1 += _ls_ingfk[v] * pk[v]\n _ls_fc += 1\n if abs(derphi_a1) <= -c2 * derphi0:\n alpha_star = alpha1\n fval_star = phi_a1\n fprime_star = _ls_ingfk\n break\n\n if derphi_a1 >= 0:\n # alpha_star, fval_star, fprime_star, fnev, _ls_ingfk = _zoom(\n # alpha1, alpha0, phi_a1, phi_a0, derphi_a1, phi0, derphi0, pk, xk\n # )\n #\n # INLINE START\n maxiter = 10\n k = 0\n delta1 = 0.2 # cubic interpolant check\n delta2 = 0.1 # quadratic interpolant check\n phi_rec = phi0\n a_rec = 0\n a_hi = alpha0\n a_lo = alpha1\n phi_lo = phi_a1\n phi_hi = phi_a0\n derphi_lo = derphi_a1\n while 1:\n # interpolate to find a trial step length between a_lo and a_hi\n # Need to choose interpolation here. Use cubic interpolation and then if the\n # result is within delta * dalpha or outside the interval bounded by a_lo or a_hi\n # then use quadratic interpolation, if the result is still too close, then use bisection\n\n dalpha = a_hi - a_lo\n if dalpha < 0:\n a, b = a_hi, a_lo\n else:\n a, b = a_lo, a_hi\n\n # minimizer of cubic interpolant\n # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi)\n # if the result is too close to the end points (or out of the interval)\n # then use quadratic interpolation with phi_lo, derphi_lo and phi_hi\n # if the result is stil too close to the end points (or out of the interval)\n # then use bisection\n\n if k > 0:\n cchk = delta1 * dalpha\n a_j = self._cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, a_rec, phi_rec)\n if (k == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk):\n qchk = delta2 * dalpha\n a_j = self._quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi)\n if (a_j is None) or (a_j > b - qchk) or (a_j < a + qchk):\n a_j = a_lo + 0.5 * dalpha\n\n # Check new value of a_j\n _xkp1 = self._project(xk + a_j * pk, var_l, u)\n phi_aj, _ls_ingfk = fun_and_jac(_xkp1, *args)\n derphi_aj = 0\n for v in range(N):\n derphi_aj += _ls_ingfk[v] * pk[v]\n if (phi_aj > phi0 + c1 * a_j * derphi0) or (phi_aj >= phi_lo):\n phi_rec = phi_hi\n a_rec = a_hi\n a_hi = a_j\n phi_hi = phi_aj\n else:\n if abs(derphi_aj) <= -c2 * derphi0:\n a_star = a_j\n val_star = phi_aj\n valprime_star = _ls_ingfk\n break\n if derphi_aj * (a_hi - a_lo) >= 0:\n phi_rec = phi_hi\n a_rec = a_hi\n a_hi = a_lo\n phi_hi = phi_lo\n else:\n phi_rec = phi_lo\n a_rec = a_lo\n a_lo = a_j\n phi_lo = phi_aj\n derphi_lo = derphi_aj\n k += 1\n if k > maxiter:\n a_star = a_j\n val_star = phi_aj\n valprime_star = None\n break\n\n alpha_star = a_star\n fval_star = val_star\n fprime_star = valprime_star\n fnev = k\n # INLINE END\n\n _ls_fc += fnev\n break\n\n alpha2 = 2 * alpha1 # increase by factor of two on each iteration\n i = i + 1\n alpha0 = alpha1\n alpha1 = alpha2\n phi_a0 = phi_a1\n _xkp1 = self._project(xk + alpha1 * pk, var_l, u)\n phi_a1, _ls_ingfk = fun_and_jac(_xkp1, *args)\n _ls_fc += 1\n derphi_a0 = derphi_a1\n\n # stopping test if lower function not found\n if i > maxiter:\n alpha_star = alpha1\n fval_star = phi_a1\n fprime_star = None\n break\n\n return alpha_star, _ls_fc, _ls_fc, fval_star, old_fval, fprime_star, _ls_fc\n\n def _cubicmin(self, a, fa, fpa, b, fb, c, fc):\n # finds the minimizer for a cubic polynomial that goes through the\n # points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa.\n #\n # if no minimizer can be found return None\n #\n # f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D\n\n C = fpa\n db = b - a\n dc = c - a\n if (db == 0) or (dc == 0) or (b == c):\n return None\n denom = (db * dc) ** 2 * (db - dc)\n A = dc**2 * (fb - fa - C * db) - db**2 * (fc - fa - C * dc)\n B = -(dc**3) * (fb - fa - C * db) + db**3 * (fc - fa - C * dc)\n\n A /= denom\n B /= denom\n radical = B * B - 3 * A * C\n if radical < 0:\n return None\n if A == 0:\n return None\n xmin = a + (-B + np.sqrt(radical)) / (3 * A)\n return xmin\n\n def _quadmin(self, a, fa, fpa, b, fb):\n # finds the minimizer for a quadratic polynomial that goes through\n # the points (a,fa), (b,fb) with derivative at a of fpa\n # f(x) = B*(x-a)^2 + C*(x-a) + D\n D = fa\n C = fpa\n db = b - a * 1.0\n if db == 0:\n return None\n B = (fb - D - C * db) / (db * db)\n if B <= 0:\n return None\n xmin = a - C / (2.0 * B)\n return xmin\n\n\nclass Optimizer: # pragma: no cover\n \"\"\"\n Base class for the trust-region optimization. If feasible, this optimizer solves the problem\n\n min_delta distance(x0, x + delta) s.t. ||delta||_2 <= r AND delta^T b = c AND min_ <= x + delta <= max_\n\n where x0 is the original sample, x is the current optimisation state, r is the trust-region radius,\n b is the current estimate of the normal vector of the decision boundary, c is the estimated distance of x\n to the trust region and [min_, max_] are the value constraints of the input. The function distance(.,.)\n is the distance measure to be optimised (e.g. L2, L1, L0).\n \"\"\"\n\n def __init__(self):\n self.bfgsb = BFGSB() # a box-constrained BFGS solver\n\n def solve(self, x0, x, b, min_, max_, c, r):\n x0, x, b = x0.astype(np.float64), x.astype(np.float64), b.astype(np.float64)\n cmax, cmaxnorm = self._max_logit_diff(x, b, min_, max_, c)\n\n if np.abs(cmax) < np.abs(c):\n # problem not solvable (boundary cannot be reached)\n if np.sqrt(cmaxnorm) < r:\n # make the largest possible step towards boundary while staying within bounds\n _delta = self.optimize_boundary_s_t_trustregion(x0, x, b, min_, max_, c, r)\n else:\n # make the largest possible step towards boundary while staying within trust region\n _delta = self.optimize_boundary_s_t_trustregion(x0, x, b, min_, max_, c, r)\n else:\n if cmaxnorm < r:\n # problem is solvable\n # proceed with standard optimization\n _delta = self.optimize_distance_s_t_boundary_and_trustregion(x0, x, b, min_, max_, c, r)\n else:\n # problem might not be solvable\n bnorm = np.linalg.norm(b)\n minnorm = self._minimum_norm_to_boundary(x, b, min_, max_, c, bnorm)\n\n if minnorm <= r:\n # problem is solvable, proceed with standard optimization\n _delta = self.optimize_distance_s_t_boundary_and_trustregion(x0, x, b, min_, max_, c, r)\n else:\n # problem not solvable (boundary cannot be reached)\n # make the largest step towards boundary within trust region\n _delta = self.optimize_boundary_s_t_trustregion(x0, x, b, min_, max_, c, r)\n\n return _delta\n\n def _max_logit_diff(self, x, b, _ell, _u, c):\n \"\"\"\n Tests whether the (estimated) boundary can be reached within trust region.\n \"\"\"\n N = x.shape[0]\n cmax = 0.0\n norm = 0.0\n\n if c > 0:\n for n in range(N):\n if b[n] > 0:\n cmax += b[n] * (_u - x[n])\n norm += (_u - x[n]) ** 2\n else:\n cmax += b[n] * (_ell - x[n])\n norm += (x[n] - _ell) ** 2\n else:\n for n in range(N):\n if b[n] > 0:\n cmax += b[n] * (_ell - x[n])\n norm += (x[n] - _ell) ** 2\n else:\n cmax += b[n] * (_u - x[n])\n norm += (_u - x[n]) ** 2\n\n return cmax, np.sqrt(norm)\n\n def _minimum_norm_to_boundary(self, x, b, _ell, _u, c, bnorm):\n \"\"\"\n Computes the minimum norm necessary to reach the boundary. More precisely, we aim to solve the following\n optimization problem\n\n min ||delta||_2^2 s.t. lower <= x + delta <= upper AND b.dot(delta) = c\n\n Let's forget about the box constraints for a second, i.e.\n\n min ||delta||_2^2 s.t. b.dot(delta) = c\n\n The dual of this problem is quite straight-forward to solve,\n\n g(lambda, delta) = ||delta||_2^2 + lambda * (c - b.dot(delta))\n\n The minimum of this Lagrangian is delta^* = lambda * b / 2, and so\n\n inf_delta g(lambda, delta) = lambda^2 / 4 ||b||_2^2 + lambda * c\n\n and so the optimal lambda, which maximizes inf_delta g(lambda, delta), is given by\n\n lambda^* = 2c / ||b||_2^2\n\n which in turn yields the optimal delta:\n\n delta^* = c * b / ||b||_2^2\n\n To take into account the box-constraints we perform a binary search over lambda and apply the box\n constraint in each step.\n \"\"\"\n N = x.shape[0]\n\n lambda_lower = 2 * c / (bnorm**2 + EPS)\n lambda_upper = np.sign(c) * np.inf # optimal initial point (if box-constraints are neglected)\n _lambda = lambda_lower\n k = 0\n\n # perform a binary search over lambda\n while True:\n # compute _c = b.dot([- _lambda * b / 2]_clip)\n k += 1\n _c = 0\n norm = 0\n\n if c > 0:\n for n in range(N):\n lam_step = _lambda * b[n] / 2\n if b[n] > 0:\n max_step = _u - x[n]\n delta_step = min(max_step, lam_step)\n _c += b[n] * delta_step\n norm += delta_step**2\n else:\n max_step = _ell - x[n]\n delta_step = max(max_step, lam_step)\n _c += b[n] * delta_step\n norm += delta_step**2\n else:\n for n in range(N):\n lam_step = _lambda * b[n] / 2\n if b[n] > 0:\n max_step = _ell - x[n]\n delta_step = max(max_step, lam_step)\n _c += b[n] * delta_step\n norm += delta_step**2\n else:\n max_step = _u - x[n]\n delta_step = min(max_step, lam_step)\n _c += b[n] * delta_step\n norm += delta_step**2\n\n # adjust lambda\n if np.abs(_c) < np.abs(c):\n # increase absolute value of lambda\n if np.isinf(lambda_upper):\n _lambda *= 2\n else:\n lambda_lower = _lambda\n _lambda = (lambda_upper - lambda_lower) / 2 + lambda_lower\n else:\n # decrease lambda\n lambda_upper = _lambda\n _lambda = (lambda_upper - lambda_lower) / 2 + lambda_lower\n\n # stopping condition\n if 0.999 * np.abs(c) - EPS < np.abs(_c) < 1.001 * np.abs(c) + EPS:\n break\n\n return np.sqrt(norm)\n\n def optimize_distance_s_t_boundary_and_trustregion(self, x0, x, b, min_, max_, c, r):\n \"\"\"\n Find the solution to the optimization problem\n\n min_delta ||dx - delta||_p^p s.t. ||delta||_2^2 <= r^2 AND b^T delta = c AND min_ <= x + delta <= max_\n \"\"\"\n params0 = np.array([0.0, 0.0])\n bounds = np.array([(-np.inf, np.inf), (0, np.inf)])\n args = (x0, x, b, min_, max_, c, r)\n\n qk = self.bfgsb.solve(self.fun_and_jac, params0, bounds, args)\n return self._get_final_delta(qk[0], qk[1], x0, x, b, min_, max_, c, r, touchup=True)\n\n def optimize_boundary_s_t_trustregion_fun_and_jac(self, params, x0, x, b, min_, max_, c, r):\n N = x0.shape[0]\n s = -np.sign(c)\n _mu = params[0]\n t = 1 / (2 * _mu + EPS)\n\n g = -_mu * r**2\n grad_mu = -(r**2)\n\n for n in range(N):\n d = -s * b[n] * t\n\n if d < min_ - x[n]:\n d = min_ - x[n]\n elif d > max_ - x[n]:\n d = max_ - x[n]\n else:\n grad_mu += (b[n] + 2 * _mu * d) * (b[n] / (2 * _mu**2 + EPS))\n\n grad_mu += d**2\n g += (b[n] + _mu * d) * d\n\n return -g, -np.array([grad_mu])\n\n def safe_div(self, nominator, denominator):\n if np.abs(denominator) > EPS:\n return nominator / denominator\n elif denominator >= 0:\n return nominator / EPS\n else:\n return -nominator / EPS\n\n def optimize_boundary_s_t_trustregion(self, x0, x, b, min_, max_, c, r):\n \"\"\"\n Find the solution to the optimization problem\n\n min_delta sign(c) b^T delta s.t. ||delta||_2^2 <= r^2 AND min_ <= x + delta <= max_\n\n Note: this optimization problem is independent of the Lp norm being optimized.\n\n Lagrangian: g(delta) = sign(c) b^T delta + mu * (||delta||_2^2 - r^2)\n Optimal delta: delta = - sign(c) * b / (2 * mu)\n \"\"\"\n params0 = np.array([1.0])\n args = (x0, x, b, min_, max_, c, r)\n bounds = np.array([(0, np.inf)])\n\n qk = self.bfgsb.solve(self.optimize_boundary_s_t_trustregion_fun_and_jac, params0, bounds, args)\n\n _delta = self.safe_div(-b, 2 * qk[0])\n\n for n in range(x0.shape[0]):\n if _delta[n] < min_ - x[n]:\n _delta[n] = min_ - x[n]\n elif _delta[n] > max_ - x[n]:\n _delta[n] = max_ - x[n]\n\n return _delta\n\n\nspec = [(\"bfgsb\", BFGSB.class_type.instance_type)] # type: ignore\n\n\n@jitclass(spec=spec)\nclass L2Optimizer(Optimizer): # pragma: no cover\n def optimize_distance_s_t_boundary_and_trustregion(self, x0, x, b, min_, max_, c, r):\n \"\"\"\n Solves the L2 trust region problem\n\n min ||x0 - x - delta||_2 s.t. b^top delta = c\n & ell <= x + delta <= u\n & ||delta||_2 <= r\n\n This is a specialised solver that does not use the generic BFGS-B solver.\n Instead, this active-set solver computes the active set of indices (those that\n do not hit the bounds) and then computes that optimal step size in the direction\n of the boundary and the direction of the original sample over the active indices.\n\n Parameters\n ----------\n x0 : `numpy.ndarray`\n The original image against which we minimize the perturbation\n (flattened).\n x : `numpy.ndarray`\n The current perturbation (flattened).\n b : `numpy.ndarray`\n Normal vector of the local decision boundary (flattened).\n min_ : float\n Lower bound on the pixel values.\n max_ : float\n Upper bound on the pixel values.\n c : float\n Logit difference between the ground truth class of x0 and the\n leading class different from the ground truth.\n r : float\n Size of the trust region.\n \"\"\"\n N = x0.shape[0]\n clamp_c = 0\n clamp_norm = 0\n ck = c\n rk = r\n masked_values = 0\n\n mask = np.zeros(N, dtype=np.uint8)\n delta = np.empty_like(x0)\n dx = x0 - x\n\n for k in range(20):\n # inner optimization that solves subproblem\n bnorm = 1e-8\n bdotDx = 0\n\n for i in range(N):\n if mask[i] == 0:\n bnorm += b[i] * b[i]\n bdotDx += b[i] * dx[i]\n\n bdotDx = bdotDx / bnorm\n ck_bnorm = ck / bnorm\n b_scale = -bdotDx + ck / bnorm\n new_masked_values = 0\n delta_norm = 0\n descent_norm = 0\n boundary_step_norm = 0\n\n # make optimal step towards boundary AND minimum\n for i in range(N):\n if mask[i] == 0:\n delta[i] = dx[i] + b[i] * b_scale\n boundary_step_norm = boundary_step_norm + b[i] * ck_bnorm * b[i] * ck_bnorm\n delta_norm = delta_norm + delta[i] * delta[i]\n descent_norm = descent_norm + (dx[i] - b[i] * bdotDx) * (dx[i] - b[i] * bdotDx)\n\n # check of step to boundary is already larger than trust region\n if boundary_step_norm > rk * rk:\n for i in range(N):\n if mask[i] == 0:\n delta[i] = b[i] * ck_bnorm\n else:\n # check if combined step to large and correct step to minimum if necessary\n if delta_norm > rk * rk:\n region_correct = np.sqrt(rk * rk - boundary_step_norm)\n region_correct = region_correct / (np.sqrt(descent_norm) + 1e-8)\n b_scale = -region_correct * bdotDx + ck / bnorm\n\n for i in range(N):\n if mask[i] == 0:\n delta[i] = region_correct * dx[i] + b[i] * b_scale\n\n for i in range(N):\n if mask[i] == 0:\n if x[i] + delta[i] <= min_:\n mask[i] = 1\n delta[i] = min_ - x[i]\n new_masked_values = new_masked_values + 1\n clamp_norm = clamp_norm + delta[i] * delta[i]\n clamp_c = clamp_c + b[i] * delta[i]\n\n if x[i] + delta[i] >= max_:\n mask[i] = 1\n delta[i] = max_ - x[i]\n new_masked_values = new_masked_values + 1\n clamp_norm = clamp_norm + delta[i] * delta[i]\n clamp_c = clamp_c + b[i] * delta[i]\n\n # should no additional variable get out of bounds, stop optimization\n if new_masked_values == 0:\n break\n\n masked_values = masked_values + new_masked_values\n\n if clamp_norm < r * r:\n rk = np.sqrt(r * r - clamp_norm)\n else:\n rk = 0\n\n ck = c - clamp_c\n\n if masked_values == N:\n break\n\n return delta\n\n def fun_and_jac(self, params, x0, x, b, min_, max_, c, r):\n # we need to compute the loss function\n # g = distance + mu * (norm_d - r ** 2) + lam * (b_dot_d - c)\n # and its derivative d g / d lam and d g / d mu\n lam, mu = params\n\n N = x0.shape[0]\n\n g = 0\n d_g_d_lam = 0\n d_g_d_mu = 0\n\n distance = 0\n b_dot_d = 0\n d_norm = 0\n\n t = 1 / (2 * mu + 2)\n\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n xn = x[n]\n\n d = (2 * dx - lam * bn) * t\n\n if d + xn > max_:\n d = max_ - xn\n elif d + xn < min_:\n d = min_ - xn\n else:\n prefac = 2 * (d - dx) + 2 * mu * d + lam * bn\n d_g_d_lam -= prefac * bn * t\n d_g_d_mu -= prefac * 2 * d * t\n\n distance += (d - dx) ** 2\n b_dot_d += bn * d\n d_norm += d**2\n\n g += (dx - d) ** 2 + mu * d**2 + lam * bn * d\n d_g_d_lam += bn * d\n d_g_d_mu += d**2\n\n g += -mu * r**2 - lam * c\n d_g_d_lam -= c\n d_g_d_mu -= r**2\n\n return -g, -np.array([d_g_d_lam, d_g_d_mu])\n\n def _get_final_delta(self, lam, mu, x0, x, b, min_, max_, c, r, touchup=True):\n delta = np.empty_like(x0)\n N = x0.shape[0]\n\n t = 1 / (2 * mu + 2)\n\n for n in range(N):\n d = (2 * (x0[n] - x[n]) - lam * b[n]) * t\n\n if d + x[n] > max_:\n d = max_ - x[n]\n elif d + x[n] < min_:\n d = min_ - x[n]\n\n delta[n] = d\n\n return delta\n\n def _distance(self, x0, x):\n return np.linalg.norm(x0 - x) ** 2\n\n\n@jitclass(spec=spec)\nclass L1Optimizer(Optimizer): # pragma: no cover\n def fun_and_jac(self, params, x0, x, b, min_, max_, c, r):\n lam, mu = params\n # arg min_delta ||delta - dx||_1 + lam * b^T delta + mu * ||delta||_2^2 s.t. min <= delta + x <= max\n N = x0.shape[0]\n\n g = 0\n d_g_d_lam = 0\n d_g_d_mu = 0\n\n if mu > 0:\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n t = 1 / (2 * mu)\n u = -lam * bn * t - dx\n\n if np.abs(u) - t < 0:\n # value and grad = 0\n d = dx\n else:\n d = np.sign(u) * (np.abs(u) - t) + dx\n\n if d + x[n] < min_:\n d = min_ - x[n]\n elif d + x[n] > max_:\n d = max_ - x[n]\n else:\n prefac = np.sign(d - dx) + 2 * mu * d + lam * bn\n d_g_d_lam -= prefac * bn * t\n d_g_d_mu -= prefac * 2 * d * t\n\n g += np.abs(dx - d) + mu * d**2 + lam * bn * d\n d_g_d_lam += bn * d\n d_g_d_mu += d**2\n else: # mu == 0\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n if np.abs(lam * bn) < 1:\n d = dx\n elif np.sign(lam * bn) < 0:\n d = max_ - x[n]\n else:\n d = min_ - x[n]\n\n g += np.abs(dx - d) + mu * d**2 + lam * bn * d\n d_g_d_lam += bn * d\n d_g_d_mu += d**2\n\n g += -mu * r**2 - lam * c\n d_g_d_lam -= c\n d_g_d_mu -= r**2\n\n return -g, -np.array([d_g_d_lam, d_g_d_mu])\n\n def _get_final_delta(self, lam, mu, x0, x, b, min_, max_, c, r, touchup=True):\n delta = np.empty_like(x0)\n N = x0.shape[0]\n\n b_dot_d = 0\n norm_d = 0\n distance = 0\n\n if mu > 0:\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n t = 1 / (2 * mu)\n u = -lam * bn * t - dx\n\n if np.abs(u) - t < 0:\n # value and grad = 0\n d = dx\n else:\n d = np.sign(u) * (np.abs(u) - t) + dx\n\n if d + x[n] < min_:\n # grad = 0\n d = min_ - x[n]\n elif d + x[n] > max_:\n # grad = 0\n d = max_ - x[n]\n\n delta[n] = d\n b_dot_d += b[n] * d\n norm_d += d**2\n distance += np.abs(d - dx)\n else: # mu == 0\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n if np.abs(lam * bn) < 1:\n d = dx\n elif np.sign(lam * bn) < 0:\n d = max_ - x[n]\n else:\n d = min_ - x[n]\n\n delta[n] = d\n b_dot_d += b[n] * d\n norm_d += d**2\n distance += np.abs(d - dx)\n\n if touchup:\n # search for the one index that (a) we can modify to match boundary constraint, (b) stays within our\n # trust region and (c) minimize the distance to the original image\n dc = c - b_dot_d\n k = 0\n min_distance = np.inf\n min_distance_idx = 0\n for n in range(N):\n if np.abs(b[n]) > 0:\n dx = x0[n] - x[n]\n old_d = delta[n]\n new_d = old_d + dc / b[n]\n\n if x[n] + new_d <= max_ and x[n] + new_d >= min_ and norm_d - old_d**2 + new_d**2 <= r**2:\n # conditions (a) and (b) are fulfilled\n if k == 0:\n min_distance = distance - np.abs(old_d - dx) + np.abs(new_d - dx)\n min_distance_idx = n\n k += 1\n else:\n new_distance = distance - np.abs(old_d - dx) + np.abs(new_d - dx)\n if min_distance > new_distance:\n min_distance = new_distance\n min_distance_idx = n\n\n if k > 0:\n # touchup successful\n idx = min_distance_idx\n old_d = delta[idx]\n\n new_d = old_d + dc / b[idx]\n delta[idx] = new_d\n\n return delta\n\n def _distance(self, x0, x):\n return np.abs(x0 - x).sum()\n\n\n@jitclass(spec=spec)\nclass LinfOptimizer(Optimizer): # pragma: no cover\n def optimize_distance_s_t_boundary_and_trustregion(self, x0, x, b, min_, max_, c, r):\n \"\"\"\n Find the solution to the optimization problem\n\n min_delta ||dx - delta||_p^p s.t. ||delta||_2^2 <= r^2 AND b^T delta = c AND min_ <= x + delta <= max_\n \"\"\"\n params0 = np.array([0.0, 0.0])\n bounds = np.array([(-np.inf, np.inf), (0, np.inf)])\n\n return self.binary_search(params0, bounds, x0, x, b, min_, max_, c, r)\n\n def binary_search(self, q0, bounds, x0, x, b, min_, max_, c, r, etol=1e-6, maxiter=1000):\n # perform binary search over epsilon\n epsilon = (max_ - min_) / 2.0\n eps_low = min_\n eps_high = max_\n func_calls = 0\n\n bnorm = np.linalg.norm(b)\n lambda0 = 2 * c / bnorm**2\n\n k = 0\n\n while eps_high - eps_low > etol:\n fun, nfev, _lambda0 = self.fun(epsilon, x0, x, b, min_, max_, c, r, lambda0=lambda0)\n func_calls += nfev\n if fun > -np.inf:\n # decrease epsilon\n eps_high = epsilon\n lambda0 = _lambda0\n else:\n # increase epsilon\n eps_low = epsilon\n\n k += 1\n epsilon = (eps_high - eps_low) / 2.0 + eps_low\n\n if k > 20:\n break\n\n delta = self._get_final_delta(lambda0, eps_high, x0, x, b, min_, max_, c, r, touchup=True)\n return delta\n\n def _Linf_bounds(self, x0, epsilon, ell, u):\n N = x0.shape[0]\n _ell = np.empty_like(x0)\n _u = np.empty_like(x0)\n for i in range(N):\n nx, px = x0[i] - epsilon, x0[i] + epsilon\n if nx > ell:\n _ell[i] = nx\n else:\n _ell[i] = ell\n\n if px < u:\n _u[i] = px\n else:\n _u[i] = u\n\n return _ell, _u\n\n def fun(self, epsilon, x0, x, b, ell, u, c, r, lambda0=None):\n \"\"\"\n Computes the minimum norm necessary to reach the boundary. More precisely, we aim to solve the following\n optimization problem\n\n min ||delta||_2^2 s.t. lower <= x + delta <= upper AND b.dot(delta) = c\n\n Let's forget about the box constraints for a second, i.e.\n\n min ||delta||_2^2 s.t. b.dot(delta) = c\n\n The dual of this problem is quite straight-forward to solve,\n\n g(lambda, delta) = ||delta||_2^2 + lambda * (c - b.dot(delta))\n\n The minimum of this Lagrangian is delta^* = lambda * b / 2, and so\n\n inf_delta g(lambda, delta) = lambda^2 / 4 ||b||_2^2 + lambda * c\n\n and so the optimal lambda, which maximizes inf_delta g(lambda, delta), is given by\n\n lambda^* = 2c / ||b||_2^2\n\n which in turn yields the optimal delta:\n\n delta^* = c * b / ||b||_2^2\n\n To take into account the box-constraints we perform a binary search over lambda and apply the box\n constraint in each step.\n \"\"\"\n N = x.shape[0]\n\n # new box constraints\n _ell, _u = self._Linf_bounds(x0, epsilon, ell, u)\n\n # initialize lambda\n _lambda = lambda0\n\n # compute delta and determine active set\n k = 0\n\n lambda_max, lambda_min = 1e10, -1e10\n\n # check whether problem is actually solvable (i.e. check whether boundary constraint can be reached)\n max_c = 0\n min_c = 0\n\n for n in range(N):\n if b[n] > 0:\n max_c += b[n] * (_u[n] - x[n])\n min_c += b[n] * (_ell[n] - x[n])\n else:\n max_c += b[n] * (_ell[n] - x[n])\n min_c += b[n] * (_u[n] - x[n])\n\n if c > max_c or c < min_c:\n return -np.inf, k, _lambda\n\n while True:\n k += 1\n _c = 0\n norm = 0\n _active_bnorm = 0\n\n for n in range(N):\n lam_step = _lambda * b[n] / 2\n if lam_step + x[n] < _ell[n]:\n delta_step = _ell[n] - x[n]\n elif lam_step + x[n] > _u[n]:\n delta_step = _u[n] - x[n]\n else:\n delta_step = lam_step\n _active_bnorm += b[n] ** 2\n\n _c += b[n] * delta_step\n norm += delta_step**2\n\n if 0.9999 * np.abs(c) - EPS < np.abs(_c) < 1.0001 * np.abs(c) + EPS:\n if norm > r**2:\n return -np.inf, k, _lambda\n else:\n return -epsilon, k, _lambda\n else:\n # update lambda according to active variables\n if _c > c:\n lambda_max = _lambda\n else:\n lambda_min = _lambda\n #\n if _active_bnorm == 0:\n # update is stepping out of feasible region, fallback to binary search\n _lambda = (lambda_max - lambda_min) / 2 + lambda_min\n else:\n _lambda += 2 * (c - _c) / _active_bnorm\n\n dlambda = lambda_max - lambda_min\n if _lambda > lambda_max - 0.1 * dlambda or _lambda < lambda_min + 0.1 * dlambda:\n # update is stepping out of feasible region, fallback to binary search\n _lambda = (lambda_max - lambda_min) / 2 + lambda_min\n\n def _get_final_delta(self, lam, eps, x0, x, b, min_, max_, c, r, touchup=True):\n N = x.shape[0]\n delta = np.empty_like(x0)\n\n # new box constraints\n _ell, _u = self._Linf_bounds(x0, eps, min_, max_)\n\n for n in range(N):\n lam_step = lam * b[n] / 2\n if lam_step + x[n] < _ell[n]:\n delta[n] = _ell[n] - x[n]\n elif lam_step + x[n] > _u[n]:\n delta[n] = _u[n] - x[n]\n else:\n delta[n] = lam_step\n\n return delta\n\n def _distance(self, x0, x):\n return np.abs(x0 - x).max()\n\n\n@jitclass(spec=spec)\nclass L0Optimizer(Optimizer): # pragma: no cover\n def optimize_distance_s_t_boundary_and_trustregion(self, x0, x, b, min_, max_, c, r):\n \"\"\"\n Find the solution to the optimization problem\n\n min_delta ||dx - delta||_p^p s.t. ||delta||_2^2 <= r^2 AND b^T delta = c AND min_ <= x + delta <= max_\n \"\"\"\n params0 = np.array([0.0, 0.0])\n bounds = np.array([(-np.inf, np.inf), (0, np.inf)])\n\n return self.minimize(params0, bounds, x0, x, b, min_, max_, c, r)\n\n def minimize(\n self,\n q0,\n bounds,\n x0,\n x,\n b,\n min_,\n max_,\n c,\n r,\n ftol=1e-9,\n xtol=-1e-5,\n maxiter=1000,\n ):\n # First check whether solution can be computed without trust region\n delta, delta_norm = self.minimize_without_trustregion(x0, x, b, c, r, min_, max_)\n\n if delta_norm <= r:\n return delta\n else:\n # perform Nelder-Mead optimization\n args = (x0, x, b, min_, max_, c, r)\n\n results = self._nelder_mead_algorithm(q0, bounds, args=args, tol_f=ftol, tol_x=xtol, max_iter=maxiter)\n\n delta = self._get_final_delta(results[0], results[1], x0, x, b, min_, max_, c, r, touchup=True)\n\n return delta\n\n def minimize_without_trustregion(self, x0, x, b, c, r, ell, u):\n # compute maximum direction to b.dot(delta) within box-constraints\n delta = x0 - x\n total = np.empty_like(x0)\n total_b = np.empty_like(x0)\n bdotdelta = b.dot(delta)\n delta_bdotdelta = c - bdotdelta\n\n for k in range(x0.shape[0]):\n if b[k] > 0 and delta_bdotdelta > 0:\n total_b[k] = (u - x0[k]) * b[k] # pos\n total[k] = u - x0[k]\n elif b[k] > 0 and delta_bdotdelta < 0:\n total_b[k] = (ell - x0[k]) * b[k] # neg\n total[k] = ell - x0[k]\n elif b[k] < 0 and delta_bdotdelta > 0:\n total_b[k] = (ell - x0[k]) * b[k] # pos\n total[k] = ell - x0[k]\n else:\n total_b[k] = (u - x0[k]) * b[k] # neg\n total[k] = u - x0[k]\n\n b_argsort = np.argsort(np.abs(total_b))[::-1]\n\n for idx in b_argsort:\n if np.abs(c - bdotdelta) > np.abs(total_b[idx]):\n delta[idx] += total[idx]\n bdotdelta += total_b[idx]\n else:\n delta[idx] += (c - bdotdelta) / (b[idx] + 1e-20)\n break\n\n delta_norm = np.linalg.norm(delta)\n\n return delta, delta_norm\n\n def _nelder_mead_algorithm(\n self,\n q0,\n bounds,\n args=(),\n \u03c1=1.0,\n \u03c7=2.0,\n \u03b3=0.5,\n \u03c3=0.5,\n tol_f=1e-8,\n tol_x=1e-8,\n max_iter=1000,\n ):\n \"\"\"\n Implements the Nelder-Mead algorithm described in Lagarias et al. (1998)\n modified to maximize instead of minimizing.\n\n Parameters\n ----------\n vertices : ndarray(float, ndim=2)\n Initial simplex with shape (n+1, n) to be modified in-place.\n\n args : tuple, optional\n Extra arguments passed to the objective function.\n\n \u03c1 : scalar(float), optional(default=1.)\n Reflection parameter. Must be strictly greater than 0.\n\n \u03c7 : scalar(float), optional(default=2.)\n Expansion parameter. Must be strictly greater than max(1, \u03c1).\n\n \u03b3 : scalar(float), optional(default=0.5)\n Contraction parameter. Must be stricly between 0 and 1.\n\n \u03c3 : scalar(float), optional(default=0.5)\n Shrinkage parameter. Must be strictly between 0 and 1.\n\n tol_f : scalar(float), optional(default=1e-10)\n Tolerance to be used for the function value convergence test.\n\n tol_x : scalar(float), optional(default=1e-10)\n Tolerance to be used for the function domain convergence test.\n\n max_iter : scalar(float), optional(default=1000)\n The maximum number of allowed iterations.\n\n Returns\n ----------\n x : Approximate solution\n\n \"\"\"\n vertices = self._initialize_simplex(q0)\n n = vertices.shape[1]\n self._check_params(\u03c1, \u03c7, \u03b3, \u03c3, bounds, n)\n\n nit = 0\n\n \u03c1\u03b3 = \u03c1 * \u03b3\n \u03c1\u03c7 = \u03c1 * \u03c7\n \u03c3_n = \u03c3**n\n\n f_val = np.empty(n + 1, dtype=np.float64)\n for i in range(n + 1):\n f_val[i] = self._neg_bounded_fun(bounds, vertices[i], args=args)\n\n # Step 1: Sort\n sort_ind = f_val.argsort()\n LV_ratio = 1\n\n # Compute centroid\n x_bar = vertices[sort_ind[:n]].sum(axis=0) / n\n\n while True:\n shrink = False\n\n # Check termination\n fail = nit >= max_iter\n\n best_val_idx = sort_ind[0]\n worst_val_idx = sort_ind[n]\n\n term_f = f_val[worst_val_idx] - f_val[best_val_idx] < tol_f\n\n # Linearized volume ratio test (see [2])\n term_x = LV_ratio < tol_x\n\n if term_x or term_f or fail:\n break\n\n # Step 2: Reflection\n x_r = x_bar + \u03c1 * (x_bar - vertices[worst_val_idx])\n f_r = self._neg_bounded_fun(bounds, x_r, args=args)\n\n if f_r >= f_val[best_val_idx] and f_r < f_val[sort_ind[n - 1]]:\n # Accept reflection\n vertices[worst_val_idx] = x_r\n LV_ratio *= \u03c1\n\n # Step 3: Expansion\n elif f_r < f_val[best_val_idx]:\n x_e = x_bar + \u03c7 * (x_r - x_bar)\n f_e = self._neg_bounded_fun(bounds, x_e, args=args)\n if f_e < f_r: # Greedy minimization\n vertices[worst_val_idx] = x_e\n LV_ratio *= \u03c1\u03c7\n else:\n vertices[worst_val_idx] = x_r\n LV_ratio *= \u03c1\n\n # Step 4 & 5: Contraction and Shrink\n else:\n # Step 4: Contraction\n if f_r < f_val[worst_val_idx]: # Step 4.a: Outside Contraction\n x_c = x_bar + \u03b3 * (x_r - x_bar)\n LV_ratio_update = \u03c1\u03b3\n else: # Step 4.b: Inside Contraction\n x_c = x_bar - \u03b3 * (x_r - x_bar)\n LV_ratio_update = \u03b3\n\n f_c = self._neg_bounded_fun(bounds, x_c, args=args)\n if f_c < min(f_r, f_val[worst_val_idx]): # Accept contraction\n vertices[worst_val_idx] = x_c\n LV_ratio *= LV_ratio_update\n\n # Step 5: Shrink\n else:\n shrink = True\n for i in sort_ind[1:]:\n vertices[i] = vertices[best_val_idx] + \u03c3 * (vertices[i] - vertices[best_val_idx])\n f_val[i] = self._neg_bounded_fun(bounds, vertices[i], args=args)\n\n sort_ind[1:] = f_val[sort_ind[1:]].argsort() + 1\n\n x_bar = (\n vertices[best_val_idx]\n + \u03c3 * (x_bar - vertices[best_val_idx])\n + (vertices[worst_val_idx] - vertices[sort_ind[n]]) / n\n )\n\n LV_ratio *= \u03c3_n\n\n if not shrink: # Nonshrink ordering rule\n f_val[worst_val_idx] = self._neg_bounded_fun(bounds, vertices[worst_val_idx], args=args)\n\n for i, j in enumerate(sort_ind):\n if f_val[worst_val_idx] < f_val[j]:\n sort_ind[i + 1 :] = sort_ind[i:-1]\n sort_ind[i] = worst_val_idx\n break\n\n x_bar += (vertices[worst_val_idx] - vertices[sort_ind[n]]) / n\n\n nit += 1\n\n return vertices[sort_ind[0]]\n\n def _initialize_simplex(self, x0):\n \"\"\"\n Generates an initial simplex for the Nelder-Mead method.\n\n Parameters\n ----------\n x0 : ndarray(float, ndim=1)\n Initial guess. Array of real elements of size (n,), where \u2018n\u2019 is the\n number of independent variables.\n\n bounds: ndarray(float, ndim=2)\n Sequence of (min, max) pairs for each element in x0.\n\n Returns\n ----------\n vertices : ndarray(float, ndim=2)\n Initial simplex with shape (n+1, n).\n \"\"\"\n n = x0.size\n\n vertices = np.empty((n + 1, n), dtype=np.float64)\n\n # Broadcast x0 on row dimension\n vertices[:] = x0\n\n nonzdelt = 0.05\n zdelt = 0.00025\n\n for i in range(n):\n # Generate candidate coordinate\n if vertices[i + 1, i] != 0.0:\n vertices[i + 1, i] *= 1 + nonzdelt\n else:\n vertices[i + 1, i] = zdelt\n\n return vertices\n\n def _check_params(self, \u03c1, \u03c7, \u03b3, \u03c3, bounds, n):\n \"\"\"\n Checks whether the parameters for the Nelder-Mead algorithm are valid.\n JIT-compiled in `nopython` mode using Numba.\n\n Parameters\n ----------\n \u03c1 : scalar(float)\n Reflection parameter. Must be strictly greater than 0.\n\n \u03c7 : scalar(float)\n Expansion parameter. Must be strictly greater than max(1, \u03c1).\n\n \u03b3 : scalar(float)\n Contraction parameter. Must be stricly between 0 and 1.\n\n \u03c3 : scalar(float)\n Shrinkage parameter. Must be strictly between 0 and 1.\n\n bounds: ndarray(float, ndim=2)\n Sequence of (min, max) pairs for each element in x.\n\n n : scalar(int)\n Number of independent variables.\n \"\"\"\n if \u03c1 < 0:\n raise ValueError(\"\u03c1 must be strictly greater than 0.\")\n if \u03c7 < 1:\n raise ValueError(\"\u03c7 must be strictly greater than 1.\")\n if \u03c7 < \u03c1:\n raise ValueError(\"\u03c7 must be strictly greater than \u03c1.\")\n if \u03b3 < 0 or \u03b3 > 1:\n raise ValueError(\"\u03b3 must be strictly between 0 and 1.\")\n if \u03c3 < 0 or \u03c3 > 1:\n raise ValueError(\"\u03c3 must be strictly between 0 and 1.\")\n\n if bounds.shape not in ((0, 2), (n, 2)):\n raise ValueError(\"The shape of `bounds` is not valid.\")\n if (np.atleast_2d(bounds)[:, 0] > np.atleast_2d(bounds)[:, 1]).any():\n raise ValueError(\"Lower bounds must be greater than upper bounds.\")\n\n def _check_bounds(self, x, bounds):\n \"\"\"\n Checks whether `x` is within `bounds`. JIT-compiled in `nopython` mode\n using Numba.\n\n Parameters\n ----------\n x : ndarray(float, ndim=1)\n 1-D array with shape (n,) of independent variables.\n\n bounds: ndarray(float, ndim=2)\n Sequence of (min, max) pairs for each element in x.\n\n Returns\n ----------\n bool\n `True` if `x` is within `bounds`, `False` otherwise.\n\n \"\"\"\n if bounds.shape == (0, 2):\n return True\n else:\n return (np.atleast_2d(bounds)[:, 0] <= x).all() and (x <= np.atleast_2d(bounds)[:, 1]).all()\n\n def _neg_bounded_fun(self, bounds, x, args=()):\n \"\"\"\n Wrapper for bounding and taking the negative of `fun` for the\n Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba.\n\n Parameters\n ----------\n bounds: ndarray(float, ndim=2)\n Sequence of (min, max) pairs for each element in x.\n\n x : ndarray(float, ndim=1)\n 1-D array with shape (n,) of independent variables at which `fun` is\n to be evaluated.\n\n args : tuple, optional\n Extra arguments passed to the objective function.\n\n Returns\n ----------\n scalar\n `-fun(x, *args)` if x is within `bounds`, `np.inf` otherwise.\n\n \"\"\"\n if self._check_bounds(x, bounds):\n return -self.fun(x, *args)\n else:\n return np.inf\n\n def fun(self, params, x0, x, b, min_, max_, c, r):\n # arg min_delta ||delta - dx||_0 + lam * b^T delta + mu * ||delta||_2^2 s.t. min <= delta + x <= max\n lam, mu = params\n N = x0.shape[0]\n\n g = -mu * r**2 - lam * c\n\n if mu > 0:\n t = 1 / (2 * mu)\n\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n\n case1 = lam * bn * dx + mu * dx**2\n\n optd = -lam * bn * t\n if optd < min_ - x[n]:\n optd = min_ - x[n]\n elif optd > max_ - x[n]:\n optd = max_ - x[n]\n\n case2 = 1 + lam * bn * optd + mu * optd**2\n\n if case1 <= case2:\n g += mu * dx**2 + lam * bn * dx\n else:\n g += 1 + mu * optd**2 + lam * bn * optd\n else:\n # arg min_delta ||delta - dx||_0 + lam * b^T delta\n # case delta[n] = dx[n]: lam * b[n] * dx[n]\n # case delta[n] != dx[n]: lam * b[n] * [min_ - x[n], max_ - x[n]]\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n case1 = lam * bn * dx\n case2 = 1 + lam * bn * (min_ - x[n])\n case3 = 1 + lam * bn * (max_ - x[n])\n if case1 <= case2 and case1 <= case3:\n g += mu * dx**2 + lam * bn * dx\n elif case2 < case3:\n g += 1 + mu * (min_ - x[n]) ** 2 + lam * bn * (min_ - x[n])\n else:\n g += 1 + mu * (max_ - x[n]) ** 2 + lam * bn * (max_ - x[n])\n\n return g\n\n def _get_final_delta(self, lam, mu, x0, x, b, min_, max_, c, r, touchup=True):\n if touchup:\n delta = self.__get_final_delta(lam, mu, x0, x, b, min_, max_, c, r)\n if delta is not None:\n return delta\n else:\n # fallback\n params = [\n (lam + 1e-5, mu),\n (lam, mu + 1e-5),\n (lam - 1e-5, mu),\n (lam, mu - 1e-5),\n (lam + 1e-5, mu + 1e-5),\n (lam - 1e-5, mu - 1e-5),\n (lam + 1e-5, mu - 1e-5),\n (lam - 1e-5, mu + 1e-5),\n ]\n for param in params:\n delta = self.__get_final_delta(param[0], param[1], x0, x, b, min_, max_, c, r)\n if delta is not None:\n return delta\n\n # 2nd fallback\n return self.__get_final_delta(lam, mu, x0, x, b, min_, max_, c, r, False)\n else:\n return self.__get_final_delta(lam, mu, x0, x, b, min_, max_, c, r, False)\n\n def __get_final_delta(self, lam, mu, x0, x, b, min_, max_, c, r, touchup=True):\n delta = np.empty_like(x0)\n N = x0.shape[0]\n\n b_dot_d = 0\n norm_d = 0\n distance = 0\n\n if mu > 0:\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n t = 1 / (2 * mu)\n\n case1 = lam * bn * dx + mu * dx**2\n\n optd = -lam * bn * t\n if optd < min_ - x[n]:\n optd = min_ - x[n]\n elif optd > max_ - x[n]:\n optd = max_ - x[n]\n\n case2 = 1 + lam * bn * optd + mu * optd**2\n\n if case1 <= case2:\n d = dx\n else:\n d = optd\n distance += 1\n\n delta[n] = d\n b_dot_d += bn * d\n norm_d += d**2\n else: # mu == 0\n for n in range(N):\n dx = x0[n] - x[n]\n bn = b[n]\n case1 = lam * bn * dx\n case2 = 1 + lam * bn * (min_ - x[n])\n case3 = 1 + lam * bn * (max_ - x[n])\n if case1 <= case2 and case1 <= case3:\n d = dx\n elif case2 < case3:\n d = min_ - x[n]\n distance += 1\n else:\n d = max_ - x[n]\n distance += 1\n\n delta[n] = d\n norm_d += d**2\n b_dot_d += bn * d\n\n if touchup:\n # search for the one index that\n # (a) we can modify to match boundary constraint\n # (b) stays within our trust region and\n # (c) minimize the distance to the original image.\n dc = c - b_dot_d\n k = 0\n min_distance = np.inf\n min_norm = np.inf\n min_distance_idx = 0\n for n in range(N):\n if np.abs(b[n]) > 0:\n dx = x0[n] - x[n]\n old_d = delta[n]\n new_d = old_d + dc / b[n]\n\n if x[n] + new_d <= max_ and x[n] + new_d >= min_ and norm_d - old_d**2 + new_d**2 <= r**2:\n # conditions (a) and (b) are fulfilled\n if k == 0:\n min_distance = distance - (np.abs(old_d - dx) > 1e-10) + (np.abs(new_d - dx) > 1e-10)\n min_distance_idx = n\n min_norm = norm_d - old_d**2 + new_d**2\n k += 1\n else:\n new_distance = distance - (np.abs(old_d - dx) > 1e-10) + (np.abs(new_d - dx) > 1e-10)\n if (\n min_distance > new_distance\n or min_distance == new_distance\n and min_norm > norm_d - old_d**2 + new_d**2\n ):\n min_distance = new_distance\n min_norm = norm_d - old_d**2 + new_d**2\n min_distance_idx = n\n\n if k > 0:\n # touchup successful\n idx = min_distance_idx\n old_d = delta[idx]\n\n new_d = old_d + dc / b[idx]\n delta[idx] = new_d\n\n return delta\n else:\n return None\n\n return delta\n\n def _distance(self, x0, x):\n return np.sum(np.abs(x - x0) > EPS)\n\n\nclass BrendelBethgeAttack(EvasionAttack):\n \"\"\"\n Base class for the Brendel & Bethge adversarial attack [#Bren19]_, a powerful gradient-based adversarial attack that\n follows the adversarial boundary (the boundary between the space of adversarial and non-adversarial images as\n defined by the adversarial criterion) to find the minimum distance to the clean image.\n\n This is implementation of the Brendel & Bethge attack follows the reference implementation at\n https://github.com/bethgelab/foolbox/blob/master/foolbox/attacks/brendel_bethge.py.\n\n Implementation differs from the attack used in the paper in two ways:\n\n * The initial binary search is always using the full 10 steps (for ease of implementation).\n * The adaptation of the trust region over the course of optimisation is less\n greedy but is more robust, reliable and simpler (decay every K steps)\n\n References:\n .. [#Bren19] Wieland Brendel, Jonas Rauber, Matthias K\u00fcmmerer, Ivan Ustyuzhaninov, Matthias Bethge,\n \"Accurate, reliable and fast robustness evaluation\",\n 33rd Conference on Neural Information Processing Systems (2019)\n https://arxiv.org/abs/1907.01003\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"targeted\",\n \"init_attack\",\n \"overshoot\",\n \"steps\",\n \"lr\",\n \"lr_decay\",\n \"lr_num_decay\",\n \"momentum\",\n \"binary_search_steps\",\n \"init_size\",\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n norm: int | float | str = np.inf,\n targeted: bool = False,\n overshoot: float = 1.1,\n steps: int = 1000,\n lr: float = 1e-3,\n lr_decay: float = 0.5,\n lr_num_decay: int = 20,\n momentum: float = 0.8,\n binary_search_steps: int = 10,\n init_size: int = 100,\n batch_size: int = 32,\n ):\n \"\"\"\n :param estimator: A trained ART classifier providing loss gradients.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param targeted: Flag determining if attack is targeted.\n :param overshoot: If 1 the attack tries to return exactly to the adversarial boundary in each iteration. For\n higher values the attack tries to overshoot over the boundary to ensure that the perturbed\n sample in each iteration is adversarial.\n :param steps: Maximum number of iterations to run. Might converge and stop before that.\n :param lr: Trust region radius, behaves similar to a learning rate. Smaller values decrease the step size in\n each iteration and ensure that the attack follows the boundary more faithfully.\n :param lr_decay: The trust region lr is multiplied with lr_decay in regular intervals (see lr_num_decay).\n :param lr_num_decay: Number of learning rate decays in regular intervals of length steps / lr_num_decay.\n :param momentum: Averaging of the boundary estimation over multiple steps. A momentum of zero would always take\n the current estimate while values closer to one average over a larger number of iterations.\n :param binary_search_steps: Number of binary search steps used to find the adversarial boundary between the\n starting point and the clean image.\n :param init_size: Maximum number of random search steps to find initial adversarial example.\n :param batch_size: Batch size for evaluating the model for predictions and gradients.\n \"\"\"\n from art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier\n\n if isinstance(estimator, TensorFlowV2Classifier):\n import tensorflow as tf\n\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. If loss_type='difference_logits_ratio' \"\n \"the estimator has to to predict logits.\"\n )\n else:\n\n def logits_difference(y_true, y_pred):\n i_y_true = tf.cast(tf.math.argmax(tf.cast(y_true, tf.int32), axis=1), tf.int32)\n i_y_pred_arg = tf.argsort(y_pred, axis=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = tf.stack(i_z_i_list)\n\n z_i = tf.gather(y_pred, i_z_i, axis=1, batch_dims=0)\n z_y = tf.gather(y_pred, i_y_true, axis=1, batch_dims=0)\n\n z_i = tf.linalg.diag_part(z_i)\n z_y = tf.linalg.diag_part(z_y)\n\n logits_diff = z_y - z_i\n\n return tf.reduce_mean(logits_diff)\n\n self._loss_fn = logits_difference\n self._loss_object = logits_difference\n\n estimator_bb: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\" = TensorFlowV2Classifier(\n model=estimator.model,\n nb_classes=estimator.nb_classes,\n input_shape=estimator.input_shape,\n loss_object=self._loss_object,\n optimizer=estimator.optimizer,\n train_step=estimator.train_step,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n )\n\n elif isinstance(estimator, PyTorchClassifier):\n import torch\n\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=config.ART_NUMPY_DTYPE))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. If loss_type='difference_logits_ratio' \"\n \"the estimator has to to predict logits.\"\n )\n else:\n\n # def difference_logits_ratio(y_true, y_pred):\n def logits_difference(y_pred, y_true): # type: ignore\n if isinstance(y_true, np.ndarray): # pragma: no cover\n y_true = torch.from_numpy(y_true)\n if isinstance(y_pred, np.ndarray): # pragma: no cover\n y_pred = torch.from_numpy(y_pred)\n\n y_true = y_true.float()\n\n i_y_true = torch.argmax(y_true, axis=1)\n i_y_pred_arg = torch.argsort(y_pred, axis=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = torch.stack(i_z_i_list)\n\n z_i = y_pred[:, i_z_i]\n z_y = y_pred[:, i_y_true]\n\n z_i = torch.diagonal(z_i)\n z_y = torch.diagonal(z_y)\n\n logits_diff = z_y - z_i\n\n return torch.mean(logits_diff.float())\n\n self._loss_fn = logits_difference\n self._loss_object = logits_difference\n\n estimator_bb = PyTorchClassifier(\n model=estimator.model,\n loss=self._loss_object, # type: ignore\n input_shape=estimator.input_shape,\n nb_classes=estimator.nb_classes,\n optimizer=None,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n device_type=str(estimator._device),\n )\n\n else:\n logger.warning(\n \"The type of the provided estimator is not yet support for automated setting of logits \"\n \"difference loss. Therefore, this attack is defaulting to attacking the loss provided by \"\n \"the model in the provided estimator.\"\n )\n estimator_bb = estimator\n\n super().__init__(estimator=estimator_bb)\n\n self.norm = norm\n self._targeted = targeted\n self.overshoot = overshoot\n self.steps = steps\n self.lr = lr\n self.lr_decay = lr_decay\n self.lr_num_decay = lr_num_decay\n self.momentum = momentum\n self.binary_search_steps = binary_search_steps\n self.init_size = init_size\n self.batch_size = batch_size\n self._check_params()\n\n self._optimizer: Optimizer\n if norm == 0:\n self._optimizer = L0Optimizer()\n if norm == 1:\n self._optimizer = L1Optimizer()\n elif norm == 2:\n self._optimizer = L2Optimizer()\n elif norm in [\"inf\", np.inf]:\n self._optimizer = LinfOptimizer()\n\n # Set binary search threshold\n if norm == 2:\n self.theta = 0.01 / np.sqrt(np.prod(self.estimator.input_shape))\n else:\n self.theta = 0.01 / np.prod(self.estimator.input_shape)\n\n def generate(\n self,\n x: np.ndarray,\n y: np.ndarray | None = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Applies the Brendel & Bethge attack.\n\n :param x: The original clean inputs.\n :param y: The labels for inputs `x`.\n\n :Keyword Arguments:\n * *starting_points* (``np.ndarray``)\n Optional. Adversarial inputs to use as a starting points, in particular for targeted attacks.\n \"\"\"\n starting_points = kwargs.get(\"starting_points\")\n # early_stop = kwargs.get(\"early_stop\")\n\n originals = x.copy()\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n logger.info(\"Using model predictions as correct labels for FGM.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)) # type: ignore\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Prediction from the initial adversarial examples if not None\n x_adv_init = kwargs.get(\"x_adv_init\")\n\n if x_adv_init is not None:\n init_preds = np.argmax(self.estimator.predict(x_adv_init, batch_size=self.batch_size), axis=1)\n else:\n init_preds = [None] * len(x)\n x_adv_init = [None] * len(x)\n\n classes = y\n\n if starting_points is None:\n\n starting_points = np.zeros_like(x)\n # First, create an initial adversarial sample\n clip_min, clip_max = self.estimator.clip_values\n # Prediction from the original images\n preds = np.argmax(self.estimator.predict(x, batch_size=self.batch_size), axis=1)\n y_index = np.argmax(y, axis=1)\n\n for i_x in range(x.shape[0]):\n initial_sample = self._init_sample(\n x=x[i_x],\n y=y_index[i_x],\n y_p=preds[i_x],\n init_pred=init_preds[i_x],\n adv_init=x_adv_init[i_x],\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n if initial_sample is None:\n starting_points[i_x] = x[i_x]\n else:\n starting_points[i_x] = initial_sample[0]\n\n best_advs = starting_points\n\n if self.targeted:\n assert (np.argmax(self.estimator.predict(x=best_advs), axis=1) == np.argmax(y, axis=1)).all()\n else:\n assert (np.argmax(self.estimator.predict(x=best_advs), axis=1) != np.argmax(y, axis=1)).all()\n\n # perform binary search to find adversarial boundary\n # TODO: Implement more efficient search with breaking condition\n N = len(originals)\n rows = range(N)\n\n bounds = self.estimator.clip_values\n min_, max_ = bounds\n\n x0 = originals\n x0_np_flatten = x0.reshape((N, -1))\n x1 = best_advs\n\n lower_bound = np.zeros(shape=(N,))\n upper_bound = np.ones(shape=(N,))\n\n for _ in range(self.binary_search_steps):\n epsilons = (lower_bound + upper_bound) / 2\n mid_points = self.mid_points(x0, x1, epsilons, bounds)\n if self.targeted:\n is_advs = (np.argmax(self.estimator.predict(x=mid_points), axis=1) == np.argmax(y, axis=1)).all()\n else:\n is_advs = (np.argmax(self.estimator.predict(x=mid_points), axis=1) != np.argmax(y, axis=1)).all()\n lower_bound = np.where(is_advs, lower_bound, epsilons)\n upper_bound = np.where(is_advs, epsilons, upper_bound)\n\n starting_points = self.mid_points(x0, x1, upper_bound, bounds)\n\n x = starting_points.astype(config.ART_NUMPY_DTYPE)\n lrs = self.lr * np.ones(N)\n lr_reduction_interval = max(1, int(self.steps / self.lr_num_decay))\n converged = np.zeros(N, dtype=bool)\n rate_normalization = np.prod(x.shape) * (max_ - min_)\n original_shape = x.shape\n _best_advs = best_advs.copy()\n\n from tqdm.auto import trange\n\n for step in trange(1, self.steps + 1):\n if converged.all():\n break # pragma: no cover\n\n # get logits and local boundary geometry\n # TODO: only perform forward pass on non-converged samples\n\n logits = self.estimator.predict(x=x)\n\n exclude = classes\n logits_exclude = logits.copy()\n\n logits_exclude[:, np.argmax(exclude, axis=1)] = -np.inf\n\n best_other_classes = np.argmax(logits_exclude, axis=1)\n\n if self.targeted:\n c_minimize = best_other_classes\n c_maximize = np.argmax(classes, axis=1)\n else:\n c_minimize = np.argmax(classes, axis=1)\n c_maximize = best_other_classes\n\n logits_diffs = logits[rows, c_minimize] - logits[rows, c_maximize]\n\n _boundary = self.estimator.loss_gradient(x=x, y=y)\n\n if self.targeted:\n _boundary = -_boundary\n\n # record optimal adversarials\n distances = self.norms(originals - x)\n source_norms = self.norms(originals - best_advs)\n\n closer = distances < source_norms\n closer = np.squeeze(closer)\n is_advs = logits_diffs < 0\n closer = np.logical_and(closer, is_advs)\n\n x_np_flatten = x.reshape((N, -1))\n\n if closer.any():\n _best_advs = best_advs.copy()\n _closer = closer.flatten()\n for idx in np.arange(N)[_closer]:\n _best_advs[idx] = x_np_flatten[idx].reshape(original_shape[1:])\n\n best_advs = _best_advs.copy()\n\n # denoise estimate of boundary using a short history of the boundary\n if step == 1:\n boundary = _boundary\n else:\n boundary = (1 - self.momentum) * _boundary + self.momentum * boundary\n\n # learning rate adaptation\n if (step + 1) % lr_reduction_interval == 0:\n lrs *= self.lr_decay\n\n # compute optimal step within trust region depending on metric\n x = x.reshape((N, -1))\n region = lrs * rate_normalization\n\n # we aim to slight overshoot over the boundary to stay within the adversarial region\n corr_logits_diffs = np.where(\n -logits_diffs < 0,\n -self.overshoot * logits_diffs,\n -(2 - self.overshoot) * logits_diffs,\n )\n\n # employ solver to find optimal step within trust region for each sample\n deltas, k = [], 0\n\n for sample in range(N):\n if converged[sample]:\n # don't perform optimisation on converged samples\n deltas.append(np.zeros_like(x0_np_flatten[sample])) # pragma: no cover\n else:\n _x0 = x0_np_flatten[sample]\n _x = x_np_flatten[sample]\n _b = boundary[k].flatten()\n _c = corr_logits_diffs[k]\n r = region[sample]\n\n delta = self._optimizer.solve(_x0, _x, _b, bounds[0], bounds[1], _c, r) # type: ignore\n deltas.append(delta)\n\n k += 1 # idx of masked sample\n\n deltas_array = np.stack(deltas).astype(np.float32)\n\n # add step to current perturbation\n x = (x + deltas_array).reshape(original_shape)\n\n return best_advs.astype(config.ART_NUMPY_DTYPE)\n\n def norms(self, x: np.ndarray) -> np.ndarray:\n order = float(self.norm) if self.norm != \"inf\" else np.inf\n norm = np.linalg.norm(x=x.reshape(x.shape[0], -1), ord=order, axis=1)\n return norm\n\n def mid_points(\n self,\n x0: np.ndarray,\n x1: np.ndarray,\n epsilons: np.ndarray,\n bounds: tuple[float, float],\n ) -> np.ndarray:\n \"\"\"\n returns a point between x0 and x1 where epsilon = 0 returns x0 and epsilon = 1 returns x1\n \"\"\"\n if self.norm == 0:\n # get epsilons in right shape for broadcasting\n epsilons = epsilons.reshape(epsilons.shape + (1,) * (x0.ndim - 1))\n\n threshold = (bounds[1] - bounds[0]) * epsilons\n mask = np.abs(x1 - x0) < threshold\n new_x = np.where(mask, x1, x0)\n elif self.norm == 1:\n # get epsilons in right shape for broadcasting\n epsilons = epsilons.reshape(epsilons.shape + (1,) * (x0.ndim - 1))\n\n threshold = (bounds[1] - bounds[0]) * (1 - epsilons)\n mask = np.abs(x1 - x0) > threshold\n new_x = np.where(mask, x0 + np.sign(x1 - x0) * (np.abs(x1 - x0) - threshold), x0)\n elif self.norm == 2:\n # get epsilons in right shape for broadcasting\n epsilons = epsilons.reshape(epsilons.shape + (1,) * (x0.ndim - 1))\n new_x = epsilons * x1 + (1 - epsilons) * x0\n elif self.norm in [\"inf\", np.inf]:\n delta = x1 - x0\n min_, max_ = bounds\n s = max_ - min_\n # get epsilons in right shape for broadcasting\n epsilons = epsilons.reshape(epsilons.shape + (1,) * (x0.ndim - 1))\n\n clipped_delta = np.where(delta < -epsilons * s, -epsilons * s, delta)\n clipped_delta = np.where(clipped_delta > epsilons * s, epsilons * s, clipped_delta)\n new_x = x0 + clipped_delta\n else:\n raise ValueError(\"Value of `norm` is not supported.\")\n\n return new_x.astype(config.ART_NUMPY_DTYPE)\n\n def _init_sample(\n self,\n x: np.ndarray,\n y: int,\n y_p: int,\n init_pred: int,\n adv_init: np.ndarray,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray | tuple[np.ndarray, int] | None:\n \"\"\"\n Find initial adversarial example for the attack.\n\n :param x: An array with 1 original input to be attacked.\n :param y: If `self.targeted` is true, then `y` represents the target label.\n :param y_p: The predicted label of x.\n :param init_pred: The predicted label of the initial image.\n :param adv_init: Initial array to act as an initial adversarial example.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: An adversarial example.\n \"\"\"\n nprd = np.random.RandomState()\n initial_sample = None\n\n if self.targeted:\n # Attack satisfied\n if y == y_p:\n return None\n\n # Attack unsatisfied yet and the initial image satisfied\n if adv_init is not None and init_pred == y:\n return adv_init.astype(config.ART_NUMPY_DTYPE), init_pred\n\n # Attack unsatisfied yet and the initial image unsatisfied\n for _ in range(self.init_size):\n random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)\n random_class = np.argmax(\n self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),\n axis=1,\n )[0]\n\n if random_class == y:\n # Binary search to reduce the l2 distance to the original image\n random_img = self._binary_search(\n current_sample=random_img,\n original_sample=x,\n target=y,\n norm=2,\n clip_min=clip_min,\n clip_max=clip_max,\n threshold=0.001,\n )\n initial_sample = random_img, random_class\n\n logger.info(\"Found initial adversarial image for targeted attack.\")\n break\n else:\n logger.warning(\"Failed to draw a random image that is adversarial, attack failed.\")\n\n else:\n # The initial image satisfied\n if adv_init is not None and init_pred != y_p:\n return adv_init.astype(config.ART_NUMPY_DTYPE), y_p\n\n # The initial image unsatisfied\n for _ in range(self.init_size):\n random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)\n random_class = np.argmax(\n self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),\n axis=1,\n )[0]\n\n if random_class != y_p:\n # Binary search to reduce the l2 distance to the original image\n random_img = self._binary_search(\n current_sample=random_img,\n original_sample=x,\n target=y_p,\n norm=2,\n clip_min=clip_min,\n clip_max=clip_max,\n threshold=0.001,\n )\n initial_sample = random_img, y_p\n\n logger.info(\"Found initial adversarial image for untargeted attack.\")\n break\n else: # pragma: no cover\n logger.warning(\"Failed to draw a random image that is adversarial, attack failed.\")\n\n return initial_sample\n\n def _binary_search(\n self,\n current_sample: np.ndarray,\n original_sample: np.ndarray,\n target: int,\n norm: int | float | str,\n clip_min: float,\n clip_max: float,\n threshold: float | None = None,\n ) -> np.ndarray:\n \"\"\"\n Binary search to approach the boundary.\n\n :param current_sample: Current adversarial example.\n :param original_sample: The original input.\n :param target: The target label.\n :param norm: Order of the norm. Possible values: \"inf\", np.inf or 2.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param threshold: The upper threshold in binary search.\n :return: an adversarial example.\n \"\"\"\n # First set upper and lower bounds as well as the threshold for the binary search\n if norm == 2:\n (upper_bound, lower_bound) = (np.array(1.0), np.array(0.0))\n\n if threshold is None:\n threshold = self.theta\n\n else:\n (upper_bound, lower_bound) = (\n np.max(abs(original_sample - current_sample)),\n np.array(0.0),\n )\n\n if threshold is None:\n threshold = np.minimum(upper_bound * self.theta, self.theta)\n\n # Then start the binary search\n while (upper_bound - lower_bound) > threshold:\n # Interpolation point\n alpha = (upper_bound + lower_bound) / 2.0\n interpolated_sample = self._interpolate(\n current_sample=current_sample,\n original_sample=original_sample,\n alpha=alpha,\n norm=norm,\n )\n\n # Update upper_bound and lower_bound\n satisfied = self._adversarial_satisfactory(\n samples=interpolated_sample[None],\n target=target,\n clip_min=clip_min,\n clip_max=clip_max,\n )[0]\n lower_bound = np.where(satisfied == 0, alpha, lower_bound)\n upper_bound = np.where(satisfied == 1, alpha, upper_bound)\n\n result = self._interpolate(\n current_sample=current_sample,\n original_sample=original_sample,\n alpha=float(upper_bound),\n norm=norm,\n )\n\n return result\n\n @staticmethod\n def _interpolate(\n current_sample: np.ndarray, original_sample: np.ndarray, alpha: float, norm: int | float | str\n ) -> np.ndarray:\n \"\"\"\n Interpolate a new sample based on the original and the current samples.\n\n :param current_sample: Current adversarial example.\n :param original_sample: The original input.\n :param alpha: The coefficient of interpolation.\n :param norm: Order of the norm. Possible values: \"inf\", np.inf or 2.\n :return: An adversarial example.\n \"\"\"\n if norm == 2:\n result = (1 - alpha) * original_sample + alpha * current_sample\n else:\n result = np.clip(current_sample, original_sample - alpha, original_sample + alpha)\n\n return result\n\n def _adversarial_satisfactory(\n self, samples: np.ndarray, target: int, clip_min: float, clip_max: float\n ) -> np.ndarray:\n \"\"\"\n Check whether an image is adversarial.\n\n :param samples: A batch of examples.\n :param target: The target label.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: An array of 0/1.\n \"\"\"\n samples = np.clip(samples, clip_min, clip_max)\n preds = np.argmax(self.estimator.predict(samples, batch_size=self.batch_size), axis=1)\n\n if self.targeted:\n result = preds == target\n else:\n result = preds != target\n\n return result\n\n def _check_params(self) -> None:\n\n if self.norm not in [0, 1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, or \"inf\".')\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The argument `targeted` has to be of type `bool`.\")\n\n if not isinstance(self.overshoot, float) or self.overshoot < 1.0:\n raise ValueError(\"The argument `overshoot` has to be of `float` and larger than 1.\")\n\n if not isinstance(self.steps, int) or self.steps < 1:\n raise ValueError(\"The argument `steps` has to be of `int` and larger than 0.\")\n\n if not isinstance(self.lr, float) or self.lr <= 0.0:\n raise ValueError(\"The argument `lr` has to be of `float` and larger than 0.0.\")\n\n if not isinstance(self.lr_decay, float) or self.lr_decay <= 0.0:\n raise ValueError(\"The argument `lr_decay` has to be of `float` and larger than 0.0.\")\n\n if not isinstance(self.lr_num_decay, int) or self.lr_num_decay < 1:\n raise ValueError(\"The argument `lr_num_decay` has to be of `int` and larger than 0.\")\n\n if not isinstance(self.momentum, float) or self.momentum <= 0.0:\n raise ValueError(\"The argument `momentum` has to be of `float` and larger than 0.0.\")\n\n if not isinstance(self.binary_search_steps, int) or self.binary_search_steps < 1:\n raise ValueError(\"The argument `binary_search_steps` has to be of `int` and larger than 0.\")\n\n if not isinstance(self.init_size, int) or self.init_size < 1:\n raise ValueError(\"The argument `init_size` has to be of `int` and larger than 0.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/carlini.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the L2, LInf and L0 optimized attacks `CarliniL2Method`, `CarliniLInfMethod` and `CarliniL0Method\nof Carlini and Wagner (2016). These attacks are among the most effective white-box attacks and should be used among the\nprimary attacks to evaluate potential defences. A major difference with respect to the original implementation\n(https://github.com/carlini/nn_robust_attacks) is that this implementation uses line search in the optimization of the\nattack objective.\n\n| Paper link: https://arxiv.org/abs/1608.04644\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.optimizers import Adam\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import (\n compute_success,\n get_labels_np_array,\n tanh_to_original,\n original_to_tanh,\n)\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass CarliniL2Method(EvasionAttack):\n \"\"\"\n The L_2 optimized attack of Carlini and Wagner (2016). This attack is among the most effective and should be used\n among the primary attacks to evaluate potential defences. A major difference wrt to the original implementation\n (https://github.com/carlini/nn_robust_attacks) is that we use line search in the optimization of the attack\n objective.\n\n | Paper link: https://arxiv.org/abs/1608.04644\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"confidence\",\n \"targeted\",\n \"learning_rate\",\n \"max_iter\",\n \"binary_search_steps\",\n \"initial_const\",\n \"max_halving\",\n \"max_doubling\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n confidence: float = 0.0,\n targeted: bool = False,\n learning_rate: float = 0.01,\n binary_search_steps: int = 10,\n max_iter: int = 10,\n initial_const: float = 0.01,\n max_halving: int = 5,\n max_doubling: int = 5,\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a Carlini&Wagner L_2 attack instance.\n\n :param classifier: A trained classifier.\n :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away,\n from the original input, but classified with higher confidence as the target class.\n :param targeted: Should the attack target one specific class.\n :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better results\n but are slower to converge.\n :param binary_search_steps: Number of times to adjust constant with binary search (positive value). If\n `binary_search_steps` is large, then the algorithm is not very sensitive to the\n value of `initial_const`. Note that the values gamma=0.999999 and c_upper=10e10 are\n hardcoded with the same values used by the authors of the method.\n :param max_iter: The maximum number of iterations.\n :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance and\n confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in\n Carlini and Wagner (2016).\n :param max_halving: Maximum number of halving steps in the line search optimization.\n :param max_doubling: Maximum number of doubling steps in the line search optimization.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.confidence = confidence\n self._targeted = targeted\n self.learning_rate = learning_rate\n self.binary_search_steps = binary_search_steps\n self.max_iter = max_iter\n self.initial_const = initial_const\n self.max_halving = max_halving\n self.max_doubling = max_doubling\n self.batch_size = batch_size\n self.verbose = verbose\n CarliniL2Method._check_params(self)\n\n # There are internal hyperparameters:\n # Abort binary search for c if it exceeds this threshold (suggested in Carlini and Wagner (2016)):\n self._c_upper_bound = 10e10\n\n # Smooth arguments of arctanh by multiplying with this constant to avoid division by zero.\n # It appears this is what Carlini and Wagner (2016) are alluding to in their footnote 8. However, it is not\n # clear how their proposed trick (\"instead of scaling by 1/2 we scale by 1/2 + eps\") works in detail.\n self._tanh_smoother = 0.999999\n\n def _loss(\n self, x: np.ndarray, x_adv: np.ndarray, target: np.ndarray, c_weight: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Compute the objective function value.\n\n :param x: An array with the original input.\n :param x_adv: An array with the adversarial input.\n :param target: An array with the target class (one-hot encoded).\n :param c_weight: Weight of the loss term aiming for classification as target.\n :return: A tuple holding the current logits, l2 distance and overall loss.\n \"\"\"\n l2dist = np.sum(np.square(x - x_adv).reshape(x.shape[0], -1), axis=1)\n z_predicted = self.estimator.predict(\n np.array(x_adv, dtype=ART_NUMPY_DTYPE),\n logits=True,\n batch_size=self.batch_size,\n )\n z_target = np.sum(z_predicted * target, axis=1)\n z_other = np.max(\n z_predicted * (1 - target) + (np.min(z_predicted, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n\n # The following differs from the exact definition given in Carlini and Wagner (2016). There (page 9, left\n # column, last equation), the maximum is taken over Z_other - Z_target (or Z_target - Z_other respectively)\n # and -confidence. However, it doesn't seem that that would have the desired effect (loss term is <= 0 if and\n # only if the difference between the logit of the target and any other class differs by at least confidence).\n # Hence, the rearrangement here.\n\n if self.targeted:\n # if targeted, optimize for making the target class most likely\n loss = np.maximum(z_other - z_target + self.confidence, np.zeros(x.shape[0]))\n else:\n # if untargeted, optimize for making any other class most likely\n loss = np.maximum(z_target - z_other + self.confidence, np.zeros(x.shape[0]))\n\n return z_predicted, l2dist, c_weight * loss + l2dist\n\n def _loss_gradient(\n self,\n z_logits: np.ndarray,\n target: np.ndarray,\n x: np.ndarray,\n x_adv: np.ndarray,\n x_adv_tanh: np.ndarray,\n c_weight: np.ndarray,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function.\n\n :param z_logits: An array with the current logits.\n :param target: An array with the target class (one-hot encoded).\n :param x: An array with the original input.\n :param x_adv: An array with the adversarial input.\n :param x_adv_tanh: An array with the adversarial input in tanh space.\n :param c_weight: Weight of the loss term aiming for classification as target.\n :param clip_min: Minimum clipping value.\n :param clip_max: Maximum clipping value.\n :return: An array with the gradient of the loss function.\n \"\"\"\n if self.targeted:\n i_sub = np.argmax(target, axis=1)\n i_add = np.argmax(\n z_logits * (1 - target) + (np.min(z_logits, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n else:\n i_add = np.argmax(target, axis=1)\n i_sub = np.argmax(\n z_logits * (1 - target) + (np.min(z_logits, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n\n loss_gradient = self.estimator.class_gradient(x_adv, label=i_add)\n loss_gradient -= self.estimator.class_gradient(x_adv, label=i_sub)\n loss_gradient = loss_gradient.reshape(x.shape)\n\n c_mult = c_weight\n for _ in range(len(x.shape) - 1):\n c_mult = c_mult[:, np.newaxis]\n\n loss_gradient *= c_mult\n loss_gradient += 2 * (x_adv - x)\n loss_gradient *= clip_max - clip_min\n loss_gradient *= (1 - np.square(np.tanh(x_adv_tanh))) / (2 * self._tanh_smoother)\n\n return loss_gradient\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y` represents the target labels. If `self.targeted`\n is true, then `y_val` represents the target labels. Otherwise, the targets are the original class\n labels.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.amin(x), np.amax(x)\n\n # Assert that, if attack is targeted, y_val is provided:\n if self.targeted and y is None:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # No labels provided, use model prediction as correct class\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError( # pragma: no cover\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Compute perturbation with implicit batching\n nb_batches = int(np.ceil(x_adv.shape[0] / float(self.batch_size)))\n for batch_id in trange(nb_batches, desc=\"C&W L_2\", disable=not self.verbose):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_batch = x_adv[batch_index_1:batch_index_2]\n y_batch = y[batch_index_1:batch_index_2]\n\n # The optimization is performed in tanh space to keep the adversarial images bounded in correct range\n x_batch_tanh = original_to_tanh(x_batch, clip_min, clip_max, self._tanh_smoother)\n\n # Initialize binary search:\n c_current = self.initial_const * np.ones(x_batch.shape[0])\n c_lower_bound = np.zeros(x_batch.shape[0])\n c_double = np.ones(x_batch.shape[0]) > 0\n\n # Initialize placeholders for best l2 distance and attack found so far\n best_l2dist = np.inf * np.ones(x_batch.shape[0])\n best_x_adv_batch = x_batch.copy()\n\n for bss in range(self.binary_search_steps):\n logger.debug(\n \"Binary search step %i out of %i (c_mean==%f)\",\n bss,\n self.binary_search_steps,\n np.mean(c_current),\n )\n nb_active = int(np.sum(c_current < self._c_upper_bound))\n logger.debug(\n \"Number of samples with c_current < _c_upper_bound: %i out of %i\",\n nb_active,\n x_batch.shape[0],\n )\n if nb_active == 0: # pragma: no cover\n break\n learning_rate = self.learning_rate * np.ones(x_batch.shape[0])\n\n # Initialize perturbation in tanh space:\n x_adv_batch = x_batch.copy()\n x_adv_batch_tanh = x_batch_tanh.copy()\n\n z_logits, l2dist, loss = self._loss(x_batch, x_adv_batch, y_batch, c_current) # type: ignore\n attack_success = loss - l2dist <= 0\n overall_attack_success = attack_success\n\n for i_iter in range(self.max_iter):\n logger.debug(\"Iteration step %i out of %i\", i_iter, self.max_iter)\n logger.debug(\"Average Loss: %f\", np.mean(loss))\n logger.debug(\"Average L2Dist: %f\", np.mean(l2dist))\n logger.debug(\"Average Margin Loss: %f\", np.mean(loss - l2dist))\n logger.debug(\n \"Current number of succeeded attacks: %i out of %i\",\n int(np.sum(attack_success)),\n len(attack_success),\n )\n\n improved_adv = attack_success & (l2dist < best_l2dist)\n logger.debug(\"Number of improved L2 distances: %i\", int(np.sum(improved_adv)))\n if np.sum(improved_adv) > 0:\n best_l2dist[improved_adv] = l2dist[improved_adv]\n best_x_adv_batch[improved_adv] = x_adv_batch[improved_adv]\n\n active = (c_current < self._c_upper_bound) & (learning_rate > 0)\n nb_active = int(np.sum(active))\n logger.debug(\n \"Number of samples with c_current < _c_upper_bound and learning_rate > 0: %i out of %i\",\n nb_active,\n x_batch.shape[0],\n )\n if nb_active == 0: # pragma: no cover\n break\n\n # compute gradient:\n logger.debug(\"Compute loss gradient\")\n perturbation_tanh = -self._loss_gradient(\n z_logits[active],\n y_batch[active],\n x_batch[active],\n x_adv_batch[active],\n x_adv_batch_tanh[active],\n c_current[active],\n clip_min,\n clip_max,\n )\n\n # perform line search to optimize perturbation\n # first, halve the learning rate until perturbation actually decreases the loss:\n prev_loss = loss.copy()\n best_loss = loss.copy()\n best_lr = np.zeros(x_batch.shape[0])\n halving = np.zeros(x_batch.shape[0])\n\n for i_halve in range(self.max_halving):\n logger.debug(\n \"Perform halving iteration %i out of %i\",\n i_halve,\n self.max_halving,\n )\n do_halving = loss[active] >= prev_loss[active]\n logger.debug(\n \"Halving to be performed on %i samples\",\n int(np.sum(do_halving)),\n )\n if np.sum(do_halving) == 0:\n break\n active_and_do_halving = active.copy()\n active_and_do_halving[active] = do_halving\n\n lr_mult = learning_rate[active_and_do_halving]\n for _ in range(len(x.shape) - 1):\n lr_mult = lr_mult[:, np.newaxis]\n\n x_adv1 = x_adv_batch_tanh[active_and_do_halving]\n new_x_adv_batch_tanh = x_adv1 + lr_mult * perturbation_tanh[do_halving]\n new_x_adv_batch = tanh_to_original(new_x_adv_batch_tanh, clip_min, clip_max)\n _, l2dist[active_and_do_halving], loss[active_and_do_halving] = self._loss(\n x_batch[active_and_do_halving],\n new_x_adv_batch,\n y_batch[active_and_do_halving],\n c_current[active_and_do_halving],\n )\n\n logger.debug(\"New Average Loss: %f\", np.mean(loss))\n logger.debug(\"New Average L2Dist: %f\", np.mean(l2dist))\n logger.debug(\"New Average Margin Loss: %f\", np.mean(loss - l2dist))\n\n best_lr[loss < best_loss] = learning_rate[loss < best_loss]\n best_loss[loss < best_loss] = loss[loss < best_loss]\n learning_rate[active_and_do_halving] /= 2\n halving[active_and_do_halving] += 1\n learning_rate[active] *= 2\n\n # if no halving was actually required, double the learning rate as long as this\n # decreases the loss:\n for i_double in range(self.max_doubling):\n logger.debug(\n \"Perform doubling iteration %i out of %i\",\n i_double,\n self.max_doubling,\n )\n do_doubling = (halving[active] == 1) & (loss[active] <= best_loss[active])\n logger.debug(\n \"Doubling to be performed on %i samples\",\n int(np.sum(do_doubling)),\n )\n if np.sum(do_doubling) == 0:\n break\n active_and_do_doubling = active.copy()\n active_and_do_doubling[active] = do_doubling\n learning_rate[active_and_do_doubling] *= 2\n\n lr_mult = learning_rate[active_and_do_doubling]\n for _ in range(len(x.shape) - 1):\n lr_mult = lr_mult[:, np.newaxis]\n\n x_adv2 = x_adv_batch_tanh[active_and_do_doubling]\n new_x_adv_batch_tanh = x_adv2 + lr_mult * perturbation_tanh[do_doubling]\n new_x_adv_batch = tanh_to_original(new_x_adv_batch_tanh, clip_min, clip_max)\n _, l2dist[active_and_do_doubling], loss[active_and_do_doubling] = self._loss(\n x_batch[active_and_do_doubling],\n new_x_adv_batch,\n y_batch[active_and_do_doubling],\n c_current[active_and_do_doubling],\n )\n logger.debug(\"New Average Loss: %f\", np.mean(loss))\n logger.debug(\"New Average L2Dist: %f\", np.mean(l2dist))\n logger.debug(\"New Average Margin Loss: %f\", np.mean(loss - l2dist))\n best_lr[loss < best_loss] = learning_rate[loss < best_loss]\n best_loss[loss < best_loss] = loss[loss < best_loss]\n\n learning_rate[halving == 1] /= 2\n\n update_adv = best_lr[active] > 0\n logger.debug(\n \"Number of adversarial samples to be finally updated: %i\",\n int(np.sum(update_adv)),\n )\n\n if np.sum(update_adv) > 0:\n active_and_update_adv = active.copy()\n active_and_update_adv[active] = update_adv\n best_lr_mult = best_lr[active_and_update_adv]\n for _ in range(len(x.shape) - 1):\n best_lr_mult = best_lr_mult[:, np.newaxis]\n\n x_adv4 = x_adv_batch_tanh[active_and_update_adv]\n best_lr1 = best_lr_mult * perturbation_tanh[update_adv]\n x_adv_batch_tanh[active_and_update_adv] = x_adv4 + best_lr1\n\n x_adv6 = x_adv_batch_tanh[active_and_update_adv]\n x_adv_batch[active_and_update_adv] = tanh_to_original(x_adv6, clip_min, clip_max)\n (\n z_logits[active_and_update_adv],\n l2dist[active_and_update_adv],\n loss[active_and_update_adv],\n ) = self._loss(\n x_batch[active_and_update_adv],\n x_adv_batch[active_and_update_adv],\n y_batch[active_and_update_adv],\n c_current[active_and_update_adv],\n )\n attack_success = loss - l2dist <= 0\n overall_attack_success = overall_attack_success | attack_success\n\n # Update depending on attack success:\n improved_adv = attack_success & (l2dist < best_l2dist)\n logger.debug(\"Number of improved L2 distances: %i\", int(np.sum(improved_adv)))\n\n if np.sum(improved_adv) > 0:\n best_l2dist[improved_adv] = l2dist[improved_adv]\n best_x_adv_batch[improved_adv] = x_adv_batch[improved_adv]\n\n c_double[overall_attack_success] = False\n c_current[overall_attack_success] = (c_lower_bound + c_current)[overall_attack_success] / 2\n\n c_old = c_current\n c_current[~overall_attack_success & c_double] *= 2\n\n c_current1 = (c_current - c_lower_bound)[~overall_attack_success & ~c_double]\n c_current[~overall_attack_success & ~c_double] += c_current1 / 2\n c_lower_bound[~overall_attack_success] = c_old[~overall_attack_success]\n\n x_adv[batch_index_1:batch_index_2] = best_x_adv_batch\n\n logger.info(\n \"Success rate of C&W L_2 attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n return x_adv\n\n def _check_params(self) -> None:\n if (\n not isinstance(\n self.binary_search_steps,\n int,\n )\n or self.binary_search_steps < 0\n ):\n raise ValueError(\"The number of binary search steps must be a non-negative integer.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.max_halving, int) or self.max_halving < 1:\n raise ValueError(\"The number of halving steps must be an integer greater than zero.\")\n\n if not isinstance(self.max_doubling, int) or self.max_doubling < 1:\n raise ValueError(\"The number of doubling steps must be an integer greater than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size < 1:\n raise ValueError(\"The batch size must be an integer greater than zero.\")\n\n\nclass CarliniLInfMethod(EvasionAttack):\n \"\"\"\n This is a modified version of the L_2 optimized attack of Carlini and Wagner (2016). It controls the L_Inf\n norm, i.e. the maximum perturbation applied to each pixel.\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"confidence\",\n \"targeted\",\n \"learning_rate\",\n \"max_iter\",\n \"decrease_factor\",\n \"initial_const\",\n \"largest_const\",\n \"const_factor\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n confidence: float = 0.0,\n targeted: bool = False,\n learning_rate: float = 0.01,\n max_iter: int = 10,\n decrease_factor: float = 0.9,\n initial_const: float = 1e-5,\n largest_const: float = 20.0,\n const_factor: float = 2.0,\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a Carlini&Wagner L_Inf attack instance.\n\n :param classifier: A trained classifier.\n :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away,\n from the original input, but classified with higher confidence as the target class.\n :param targeted: Should the attack target one specific class.\n :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better\n results but are slower to converge.\n :param max_iter: The maximum number of iterations.\n :param decrease_factor: The rate of shrinking tau, values in `0 < decrease_factor < 1` where larger is more\n accurate.\n :param initial_const: The initial value of constant `c`.\n :param largest_const: The largest value of constant `c`.\n :param const_factor: The rate of increasing constant `c` with `const_factor > 1`, where smaller more accurate.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.confidence = confidence\n self._targeted = targeted\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.decrease_factor = decrease_factor\n self.initial_const = initial_const\n self.largest_const = largest_const\n self.const_factor = const_factor\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n # There is one internal hyperparameter:\n # Smooth arguments of arctanh by multiplying with this constant to avoid division by zero:\n self._tanh_smoother = 0.999999\n\n def _loss(\n self, x_adv: np.ndarray, target: np.ndarray, x, const, tau\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Compute the objective function value.\n\n :param x_adv: An array with the adversarial examples.\n :param target: An array with the target class (one-hot encoded).\n :param x: Benign samples.\n :param const: Current constant `c`.\n :param tau: Current limit `tau`.\n :return: A tuple of current predictions, total loss, logits loss and regularisation loss.\n \"\"\"\n z_predicted = self.estimator.predict(np.array(x_adv, dtype=ART_NUMPY_DTYPE), batch_size=self.batch_size)\n z_target = np.sum(z_predicted * target, axis=1)\n z_other = np.max(\n z_predicted * (1 - target) + (np.min(z_predicted, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n\n if self.targeted:\n # if targeted, optimize for making the target class most likely\n loss_1 = np.maximum(z_other - z_target + self.confidence, np.zeros(x_adv.shape[0]))\n else:\n # if untargeted, optimize for making any other class most likely\n loss_1 = np.maximum(z_target - z_other + self.confidence, np.zeros(x_adv.shape[0]))\n\n loss_2 = np.sum(np.maximum(0.0, np.abs(x_adv - x) - tau))\n\n loss = loss_1 * const + loss_2\n\n return z_predicted, loss, loss_1, loss_2\n\n def _loss_gradient(\n self,\n z_logits: np.ndarray,\n target: np.ndarray,\n x_adv: np.ndarray,\n x_adv_tanh: np.ndarray,\n clip_min: np.ndarray,\n clip_max: np.ndarray,\n x,\n tau,\n ) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function.\n\n :param z_logits: An array with the current predictions.\n :param target: An array with the target class (one-hot encoded).\n :param x_adv: An array with the adversarial input.\n :param x_adv_tanh: An array with the adversarial input in tanh space.\n :param clip_min: Minimum clipping values.\n :param clip_max: Maximum clipping values.\n :param x: Benign samples.\n :param tau: Current limit `tau`.\n :return: An array with the gradient of the loss function.\n \"\"\"\n if self.targeted:\n i_sub = np.argmax(target, axis=1)\n i_add = np.argmax(\n z_logits * (1 - target) + (np.min(z_logits, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n else:\n i_add = np.argmax(target, axis=1)\n i_sub = np.argmax(\n z_logits * (1 - target) + (np.min(z_logits, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n\n loss_gradient = self.estimator.class_gradient(x_adv, label=i_add)\n loss_gradient -= self.estimator.class_gradient(x_adv, label=i_sub)\n loss_gradient = loss_gradient.reshape(x_adv.shape)\n\n loss_gradient_2 = np.sign(np.maximum(0.0, np.abs(x_adv - x) - tau)) * np.sign(x_adv - x)\n loss_gradient_2 *= clip_max - clip_min\n loss_gradient_2 *= (1 - np.square(np.tanh(x_adv_tanh))) / (2 * self._tanh_smoother)\n\n loss_gradient *= clip_max - clip_min\n loss_gradient *= (1 - np.square(np.tanh(x_adv_tanh))) / (2 * self._tanh_smoother)\n\n loss_gradient = loss_gradient + loss_gradient_2\n\n return loss_gradient\n\n def _generate_single(self, x_batch, y_batch, clip_min, clip_max, const, tau):\n \"\"\"\n Generate a single adversarial example.\n\n :param x_batch: Current benign sample.\n :param y_batch: Current label.\n :param clip_min: Minimum clipping values.\n :param clip_max: Maximum clipping values.\n :param const: Current constant `c`.\n :param tau: Current limit `tau`.\n \"\"\"\n\n # The optimization is performed in tanh space to keep the adversarial images bounded from clip_min and clip_max.\n x_adv_batch_tanh = original_to_tanh(x_batch, clip_min, clip_max, self._tanh_smoother)\n\n def func(x_i):\n x_adv_batch_tanh = x_i\n\n x_adv_batch = tanh_to_original(\n x_adv_batch_tanh,\n clip_min,\n clip_max,\n )\n\n _, loss, _, _ = self._loss(x_adv_batch, y_batch, x_batch, const, tau)\n\n return loss\n\n def func_der(x_i):\n x_adv_batch_tanh = x_i\n\n x_adv_batch = tanh_to_original(\n x_adv_batch_tanh,\n clip_min,\n clip_max,\n )\n\n z_logits, _, _, _ = self._loss(x_adv_batch, y_batch, x_batch, const, tau)\n\n perturbation_tanh = self._loss_gradient(\n z_logits,\n y_batch,\n x_adv_batch,\n x_adv_batch_tanh,\n clip_min,\n clip_max,\n x_batch,\n tau,\n )\n\n return perturbation_tanh\n\n x_0 = x_adv_batch_tanh.copy()\n\n adam = Adam(alpha=self.learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-8)\n x_adv_batch_tanh = adam.optimize(func=func, jac=func_der, x_0=x_0, max_iter=self.max_iter, loss_converged=0.001)\n\n x_adv_batch = tanh_to_original(\n x_adv_batch_tanh,\n clip_min,\n clip_max,\n )\n\n return x_adv_batch\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y_val` represents the target labels. Otherwise, the\n targets are the original class labels.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.amin(x), np.amax(x)\n\n # Assert that, if attack is targeted, y_val is provided:\n if self.targeted and y is None:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # No labels provided, use model prediction as correct class\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError( # pragma: no cover\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Compute perturbation with implicit batching\n for sample_id in trange(x.shape[0], desc=\"C&W L_inf\", disable=not self.verbose):\n\n sample_done = False\n tau = 1.0\n delta_i_best = 1.0\n while tau > 1.0 / 256.0 and not sample_done:\n\n sample_done = True\n\n const = self.initial_const\n while const < self.largest_const:\n\n x_batch = x[[sample_id]]\n y_batch = y[[sample_id]]\n\n x_adv_batch = self._generate_single(x_batch, y_batch, clip_min, clip_max, const=const, tau=tau)\n\n # Update depending on attack success:\n _, loss, loss_1, loss_2 = self._loss(x_adv_batch, y_batch, x_batch, const, tau)\n\n delta_i = np.max(np.abs(x_adv_batch - x[sample_id]))\n\n logger.debug(\n \"tau: %4.3f, const: %4.5f, loss: %4.3f, loss_1: %4.3f, loss_2: %4.3f, delta_i: %4.3f\",\n tau,\n const,\n loss,\n loss_1,\n loss_2,\n delta_i,\n )\n\n if (\n np.argmax(self.estimator.predict(x_adv_batch), axis=1) != np.argmax(y_batch, axis=1)\n and delta_i < delta_i_best\n ):\n x_adv[sample_id] = x_adv_batch\n delta_i_best = delta_i\n sample_done = False\n\n const *= self.const_factor\n\n tau_actual = np.max(np.abs(x_adv[sample_id] - x[sample_id]))\n\n if tau_actual < tau:\n tau = tau_actual\n\n tau *= self.decrease_factor\n\n return x_adv\n\n def _check_params(self) -> None:\n\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.decrease_factor, (int, float)) or not 0.0 < self.decrease_factor < 1.0:\n raise ValueError(\"The decrease factor must be a float between 0 and 1.\")\n\n if not isinstance(self.initial_const, (int, float)) or self.initial_const < 0:\n raise ValueError(\"The initial constant value must be a positive float.\")\n\n if not isinstance(self.largest_const, (int, float)) or self.largest_const < 0:\n raise ValueError(\"The largest constant value must be a positive float.\")\n\n if not isinstance(self.const_factor, (int, float)) or self.const_factor < 0:\n raise ValueError(\"The constant factor value must be a float and greater than 1.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size < 1:\n raise ValueError(\"The batch size must be an integer greater than zero.\")\n\n\nclass CarliniL0Method(CarliniL2Method):\n \"\"\"\n The L_0 distance metric is non-differentiable and therefore is ill-suited for standard gradient descent.\n Instead, we use an iterative algorithm that, in each iteration, identifies some features that don\u2019t have much effect\n on the classifier output and then fixes those features, so their value will never be changed.\n The set of fixed features grows in each iteration until we have, by process of elimination, identified a minimal\n (but possibly not minimum) subset of features that can be modified to generate an adversarial example.\n In each iteration, we use our L_2 attack to identify which features are unimportant [Carlini and Wagner, 2016].\n\n | Paper link: https://arxiv.org/abs/1608.04644\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"confidence\",\n \"targeted\",\n \"learning_rate\",\n \"max_iter\",\n \"binary_search_steps\",\n \"initial_const\",\n \"mask\",\n \"warm_start\",\n \"max_halving\",\n \"max_doubling\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n confidence: float = 0.0,\n targeted: bool = False,\n learning_rate: float = 0.01,\n binary_search_steps: int = 10,\n max_iter: int = 10,\n initial_const: float = 0.01,\n mask: np.ndarray | None = None,\n warm_start: bool = True,\n max_halving: int = 5,\n max_doubling: int = 5,\n batch_size: int = 1,\n verbose: bool = True,\n ):\n \"\"\"\n Create a Carlini&Wagner L_0 attack instance.\n\n :param classifier: A trained classifier.\n :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther away,\n from the original input, but classified with higher confidence as the target class.\n :param targeted: Should the attack target one specific class.\n :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better results\n but are slower to converge.\n :param binary_search_steps: Number of times to adjust constant with binary search (positive value). If\n `binary_search_steps` is large, then the algorithm is not very sensitive to the\n value of `initial_const`. Note that the values gamma=0.999999 and c_upper=10e10 are\n hardcoded with the same values used by the authors of the method.\n :param max_iter: The maximum number of iterations.\n :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance and\n confidence. If `binary_search_steps` is large, the initial constant is not important, as\n discussed in Carlini and Wagner (2016).\n :param mask: The initial features that can be modified by the algorithm. If not specified, the\n algorithm uses the full feature set.\n :param warm_start: Instead of starting gradient descent in each iteration from the initial image. we start the\n gradient descent from the solution found on the previous iteration.\n :param max_halving: Maximum number of halving steps in the line search optimization.\n :param max_doubling: Maximum number of doubling steps in the line search optimization.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n classifier=classifier,\n confidence=confidence,\n targeted=targeted,\n learning_rate=learning_rate,\n max_iter=max_iter,\n max_halving=max_halving,\n max_doubling=max_doubling,\n batch_size=batch_size,\n verbose=verbose,\n )\n\n self.binary_search_steps = binary_search_steps\n self.initial_const = initial_const\n self.mask = mask\n self.warm_start = warm_start\n self._check_params()\n\n # There are internal hyperparameters:\n # Abort binary search for c if it exceeds this threshold (suggested in Carlini and Wagner (2016)):\n self._c_upper_bound = 10e10\n\n # Smooth arguments of arctanh by multiplying with this constant to avoid division by zero.\n # It appears this is what Carlini and Wagner (2016) are alluding to in their footnote 8. However, it is not\n # clear how their proposed trick (\"instead of scaling by 1/2 we scale by 1/2 + eps\") works in detail.\n self._tanh_smoother = 0.999999\n\n # The tanh transformation does not always map inputs back to their original values event if they are unmodified\n # To overcome this problem, we set a threshold of minimal difference considered as perturbation\n # Below this threshold, a difference between values is considered as tanh transformation difference.\n self._perturbation_threshold = 1e-06\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y` represents the target labels. If `self.targeted`\n is true, then `y_val` represents the target labels. Otherwise, the targets are the original class\n labels.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.amin(x), np.amax(x)\n\n # Assert that, if attack is targeted, y_val is provided:\n if self.targeted and y is None:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # No labels provided, use model prediction as correct class\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if self.mask is None:\n # No initial activation provided, use the full feature set\n activation = np.ones(x.shape)\n else:\n # Check if the initial activation has the same dimension as the input data\n if self.mask.shape != x.shape: # pragma: no cover\n raise ValueError(\"The mask must have the same dimensions as the input data.\")\n activation = np.array(self.mask).astype(float)\n\n # L_0 attack specific variables\n final_adversarial_example = x.astype(ART_NUMPY_DTYPE)\n old_activation = activation.copy()\n c_final = np.ones(x.shape[0])\n best_l0dist = np.inf * np.ones(x.shape[0])\n\n # Main loop of the L_0 attack.\n # For each iteration :\n # - Calls the L_2 attack to compute an adversarial example\n # - Computes the gradients of the objective function evaluated at the adversarial instance\n # - Fix the attribute with the lowest value (gradient * perturbation)\n # Repeat until the L_2 attack fails to find an adversarial examples.\n for _ in range(x.shape[1] + 1):\n # Compute perturbation with implicit batching\n nb_batches = int(np.ceil(x_adv.shape[0] / float(self.batch_size)))\n for batch_id in range(nb_batches):\n logger.debug(\"Processing batch %i out of %i\", batch_id, nb_batches)\n\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n if self.warm_start:\n # Start the gradient descent from the solution found on the previous iteration\n x_batch = x_adv[batch_index_1:batch_index_2]\n else:\n x_batch = x[batch_index_1:batch_index_2]\n y_batch = y[batch_index_1:batch_index_2]\n activation_batch = activation[batch_index_1:batch_index_2]\n\n # The optimization is performed in tanh space to keep the adversarial images bounded in correct range\n x_batch_tanh = original_to_tanh(x_batch, clip_min, clip_max, self._tanh_smoother)\n\n # Initialize binary search:\n c_current = self.initial_const * np.ones(x_batch.shape[0])\n c_lower_bound = np.zeros(x_batch.shape[0])\n c_double = np.ones(x_batch.shape[0]) > 0\n\n # Initialize placeholders for best l2 distance and attack found so far\n best_l0dist_batch = np.inf * np.ones(x_batch.shape[0])\n best_x_adv_batch = x_batch.copy()\n\n for bss in range(self.binary_search_steps):\n logger.debug(\n \"Binary search step %i / %i (c_mean==%f)\", bss, self.binary_search_steps, np.mean(c_current)\n )\n nb_active = int(np.sum(c_current < self._c_upper_bound))\n logger.debug(\n \"Number of samples with c_current < _c_upper_bound: %i out of %i\", nb_active, x_batch.shape[0]\n )\n if nb_active == 0:\n break\n learning_rate = self.learning_rate * np.ones(x_batch.shape[0])\n\n # Initialize perturbation in tanh space:\n x_adv_batch = x_batch.copy()\n x_adv_batch_tanh = x_batch_tanh.copy()\n\n z_logits, l2dist, loss = self._loss(x_batch, x_adv_batch, y_batch, c_current) # type: ignore\n attack_success = loss - l2dist <= 0\n overall_attack_success = attack_success\n\n for i_iter in range(self.max_iter):\n logger.debug(\"Iteration step %i out of %i\", i_iter, self.max_iter)\n logger.debug(\"Average Loss: %f\", np.mean(loss))\n logger.debug(\"Average L2Dist: %f\", np.mean(l2dist))\n logger.debug(\"Average Margin Loss: %f\", np.mean(loss - l2dist))\n logger.debug(\n \"Current number of succeeded attacks: %i out of %i\",\n int(np.sum(attack_success)),\n len(attack_success),\n )\n\n l0dist = np.sum(\n (np.abs(x_batch - x_adv_batch) > self._perturbation_threshold).astype(int), axis=(1, 2, 3)\n )\n improved_adv = attack_success & (l0dist < best_l0dist_batch)\n logger.debug(\"Number of improved L0 distances: %i\", int(np.sum(improved_adv)))\n if np.sum(improved_adv) > 0:\n best_l0dist_batch[improved_adv] = l0dist[improved_adv]\n best_x_adv_batch[improved_adv] = x_adv_batch[improved_adv]\n\n active = (c_current < self._c_upper_bound) & (learning_rate > 0)\n nb_active = int(np.sum(active))\n logger.debug(\n \"Number of samples with c_current < _c_upper_bound and learning_rate > 0: %i out of %i\",\n nb_active,\n x_batch.shape[0],\n )\n if nb_active == 0: # pragma: no cover\n break\n\n # compute gradient:\n logger.debug(\"Compute loss gradient\")\n perturbation_tanh = -self._loss_gradient(\n z_logits[active],\n y_batch[active],\n x_batch[active],\n x_adv_batch[active],\n x_adv_batch_tanh[active],\n c_current[active],\n clip_min,\n clip_max,\n )\n\n # perform line search to optimize perturbation\n # first, halve the learning rate until perturbation actually decreases the loss:\n prev_loss = loss.copy()\n best_loss = loss.copy()\n best_lr = np.zeros(x_batch.shape[0])\n halving = np.zeros(x_batch.shape[0])\n\n for i_halve in range(self.max_halving):\n logger.debug(\"Perform halving iteration %i out of %i\", i_halve, self.max_halving)\n do_halving = loss[active] >= prev_loss[active]\n logger.debug(\"Halving to be performed on %i samples\", int(np.sum(do_halving)))\n if np.sum(do_halving) == 0:\n break\n active_and_do_halving = active.copy()\n active_and_do_halving[active] = do_halving\n\n lr_mult = learning_rate[active_and_do_halving]\n for _ in range(len(x.shape) - 1):\n lr_mult = lr_mult[:, np.newaxis]\n\n x_adv1 = x_adv_batch_tanh[active_and_do_halving]\n new_x_adv_batch_tanh = (\n x_adv1 + lr_mult * perturbation_tanh[do_halving] * activation_batch[do_halving]\n )\n new_x_adv_batch = tanh_to_original(new_x_adv_batch_tanh, clip_min, clip_max)\n _, l2dist[active_and_do_halving], loss[active_and_do_halving] = self._loss(\n x_batch[active_and_do_halving],\n new_x_adv_batch,\n y_batch[active_and_do_halving],\n c_current[active_and_do_halving],\n )\n\n logger.debug(\"New Average Loss: %f\", np.mean(loss))\n logger.debug(\"New Average L2Dist: %f\", np.mean(l2dist))\n logger.debug(\"New Average Margin Loss: %f\", np.mean(loss - l2dist))\n\n best_lr[loss < best_loss] = learning_rate[loss < best_loss]\n best_loss[loss < best_loss] = loss[loss < best_loss]\n learning_rate[active_and_do_halving] /= 2\n halving[active_and_do_halving] += 1\n learning_rate[active] *= 2\n\n # if no halving was actually required, double the learning rate as long as this\n # decreases the loss:\n for i_double in range(self.max_doubling):\n logger.debug(\"Perform doubling iteration %i out of %i\", i_double, self.max_doubling)\n do_doubling = (halving[active] == 1) & (loss[active] <= best_loss[active])\n logger.debug(\"Doubling to be performed on %i samples\", int(np.sum(do_doubling)))\n if np.sum(do_doubling) == 0: # pragma: no cover\n break\n active_and_do_doubling = active.copy()\n active_and_do_doubling[active] = do_doubling\n learning_rate[active_and_do_doubling] *= 2\n\n lr_mult = learning_rate[active_and_do_doubling]\n for _ in range(len(x.shape) - 1):\n lr_mult = lr_mult[:, np.newaxis]\n\n x_adv2 = x_adv_batch_tanh[active_and_do_doubling]\n new_x_adv_batch_tanh = (\n x_adv2 + lr_mult * perturbation_tanh[do_doubling] * activation_batch[do_doubling]\n )\n new_x_adv_batch = tanh_to_original(new_x_adv_batch_tanh, clip_min, clip_max)\n _, l2dist[active_and_do_doubling], loss[active_and_do_doubling] = self._loss(\n x_batch[active_and_do_doubling],\n new_x_adv_batch,\n y_batch[active_and_do_doubling],\n c_current[active_and_do_doubling],\n )\n logger.debug(\"New Average Loss: %f\", np.mean(loss))\n logger.debug(\"New Average L2Dist: %f\", np.mean(l2dist))\n logger.debug(\"New Average Margin Loss: %f\", np.mean(loss - l2dist))\n best_lr[loss < best_loss] = learning_rate[loss < best_loss]\n best_loss[loss < best_loss] = loss[loss < best_loss]\n\n learning_rate[halving == 1] /= 2\n\n update_adv = best_lr[active] > 0\n logger.debug(\"Number of adversarial samples to be finally updated: %i\", int(np.sum(update_adv)))\n\n if np.sum(update_adv) > 0:\n active_and_update_adv = active.copy()\n active_and_update_adv[active] = update_adv\n best_lr_mult = best_lr[active_and_update_adv]\n for _ in range(len(x.shape) - 1):\n best_lr_mult = best_lr_mult[:, np.newaxis]\n\n x_adv4 = x_adv_batch_tanh[active_and_update_adv]\n best_lr1 = best_lr_mult * perturbation_tanh[update_adv]\n x_adv_batch_tanh[active_and_update_adv] = (\n x_adv4 + best_lr1 * activation_batch[active_and_update_adv]\n )\n\n x_adv6 = x_adv_batch_tanh[active_and_update_adv]\n x_adv_batch[active_and_update_adv] = tanh_to_original(x_adv6, clip_min, clip_max)\n (\n z_logits[active_and_update_adv],\n l2dist[active_and_update_adv],\n loss[active_and_update_adv],\n ) = self._loss(\n x_batch[active_and_update_adv],\n x_adv_batch[active_and_update_adv],\n y_batch[active_and_update_adv],\n c_current[active_and_update_adv],\n )\n attack_success = loss - l2dist <= 0\n overall_attack_success = overall_attack_success | attack_success\n\n # Update depending on attack success:\n l0dist = np.sum(\n (np.abs(x_batch - x_adv_batch) > self._perturbation_threshold).astype(int), axis=(1, 2, 3)\n )\n improved_adv = attack_success & (l0dist < best_l0dist_batch)\n logger.debug(\"Number of improved L0 distances: %i\", int(np.sum(improved_adv)))\n if np.sum(improved_adv) > 0:\n best_l0dist_batch[improved_adv] = l0dist[improved_adv]\n best_x_adv_batch[improved_adv] = x_adv_batch[improved_adv]\n\n c_double[overall_attack_success] = False\n c_current[overall_attack_success] = (c_lower_bound + c_current)[overall_attack_success] / 2\n\n c_old = c_current\n c_current[~overall_attack_success & c_double] *= 2\n\n c_current1 = (c_current - c_lower_bound)[~overall_attack_success & ~c_double]\n c_current[~overall_attack_success & ~c_double] += c_current1 / 2\n c_lower_bound[~overall_attack_success] = c_old[~overall_attack_success]\n\n c_final[batch_index_1:batch_index_2] = c_current\n x_adv[batch_index_1:batch_index_2] = best_x_adv_batch\n\n logger.info(\n \"Success rate of C&W L_2 attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n # If the L_2 attack can't find any adversarial examples with the new activation, return the last one\n z_logits, l2dist, loss = self._loss(x, x_adv, y, c_final) # type: ignore\n attack_success = loss - l2dist <= 0\n l0dist = np.sum((np.abs(x - x_adv) > self._perturbation_threshold).astype(int), axis=(1, 2, 3))\n improved_adv = attack_success & (l0dist < best_l0dist)\n if np.sum(improved_adv) > 0:\n final_adversarial_example[improved_adv] = x_adv[improved_adv]\n else:\n return x * (old_activation == 0).astype(int) + final_adversarial_example * old_activation\n\n # Compute the gradients of the objective function evaluated at the adversarial instance\n x_adv_tanh = original_to_tanh(x_adv, clip_min, clip_max, self._tanh_smoother)\n objective_loss_gradient = -self._loss_gradient(\n z_logits,\n y,\n x,\n x_adv,\n x_adv_tanh,\n c_final,\n clip_min,\n clip_max,\n )\n perturbation_l1_norm = np.abs(x_adv - x)\n\n # gradient * perturbation tells how much reduction to the objective function we obtain for each attribute\n objective_reduction = np.abs(objective_loss_gradient) * perturbation_l1_norm\n\n # Assign infinity as the objective_reduction value for fixed feature (in order not to select them again)\n objective_reduction += np.array(np.where(activation == 0, np.inf, 0))\n\n # Fix the feature with the lowest objective_reduction value (only for the examples that succeeded)\n fix_feature_index = np.argmin(objective_reduction.reshape(objective_reduction.shape[0], -1), axis=1)\n fix_feature = np.ones(x.shape)\n fix_feature = fix_feature.reshape(fix_feature.shape[0], -1)\n fix_feature[np.arange(fix_feature_index.size), fix_feature_index] = 0\n fix_feature = fix_feature.reshape(x.shape)\n old_activation[improved_adv] = activation.copy()[improved_adv]\n activation[improved_adv] *= fix_feature[improved_adv]\n logger.info(\n \"L0 norm before fixing :\\n%f\\nNumber active features :\\n%f\\nIndex of fixed feature :\\n%d\",\n np.sum((perturbation_l1_norm > self._perturbation_threshold).astype(int), axis=1),\n np.sum(activation, axis=1),\n fix_feature_index,\n )\n return x_adv\n\n def _check_params(self):\n\n if not isinstance(self.binary_search_steps, int) or self.binary_search_steps < 0:\n raise ValueError(\"The number of binary search steps must be a non-negative integer.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/composite_adversarial_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the composite adversarial attack by sequentially perturbing different components of the inputs.\nIt uses order scheduling to search for the attack sequence and uses the iterative gradient sign method to optimize the\nperturbations in semantic space and Lp-ball (see `FastGradientMethod` and `BasicIterativeMethod`).\n\n| Paper link: https://arxiv.org/abs/2202.04235\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import compute_success, check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n from art.estimators.classification.pytorch import PyTorchClassifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass CompositeAdversarialAttackPyTorch(EvasionAttack):\n \"\"\"\n Implementation of the composite adversarial attack on image classifiers in PyTorch. The attack is constructed by\n adversarially perturbing the hue component of the inputs. It uses order scheduling to search for the attack sequence\n and uses the iterative gradient sign method to optimize the perturbations in semantic space and Lp-ball (see\n `FastGradientMethod` and `BasicIterativeMethod`).\n\n | Note that this attack is intended for only PyTorch image classifiers with RGB images in the range [0, 1] as inputs\n\n | Paper link: https://arxiv.org/abs/2202.04235\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"enabled_attack\",\n \"hue_epsilon\",\n \"sat_epsilon\",\n \"rot_epsilon\",\n \"bri_epsilon\",\n \"con_epsilon\",\n \"pgd_epsilon\",\n \"early_stop\",\n \"max_iter\",\n \"max_inner_iter\",\n \"schedule\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin) # type: ignore\n\n def __init__(\n self,\n classifier: \"PyTorchClassifier\",\n enabled_attack: tuple = (0, 1, 2, 3, 4, 5),\n # Default: Full Attacks; 0: Hue, 1: Saturation, 2: Rotation, 3: Brightness, 4: Contrast, 5: PGD (L-infinity)\n hue_epsilon: tuple[float, float] = (-np.pi, np.pi),\n sat_epsilon: tuple[float, float] = (0.7, 1.3),\n rot_epsilon: tuple[float, float] = (-10.0, 10.0),\n bri_epsilon: tuple[float, float] = (-0.2, 0.2),\n con_epsilon: tuple[float, float] = (0.7, 1.3),\n pgd_epsilon: tuple[float, float] = (-8 / 255, 8 / 255), # L-infinity\n early_stop: bool = True,\n max_iter: int = 5,\n max_inner_iter: int = 10,\n attack_order: str = \"scheduled\",\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of the :class:`.CompositeAdversarialAttackPyTorch`.\n\n :param classifier: A trained PyTorch classifier.\n :param enabled_attack: Attack pool selection, and attack order designation for fixed order. For simplicity,\n we use the following abbreviations to specify each attack types. 0: Hue, 1: Saturation,\n 2: Rotation, 3: Brightness, 4: Contrast, 5: PGD(L-infinity). Therefore, `(0,1,2)` means\n that the attack combines hue, saturation, and rotation; `(0,1,2,3,4)` means the\n semantic attacks; `(0,1,2,3,4,5)` means the full attacks.\n :param hue_epsilon: The boundary of the hue perturbation. The value is expected to be in the interval\n `[-np.pi, np.pi]`. Perturbation of `0` means no shift and `-np.pi` and `np.pi` give a\n complete reversal of the hue channel in the HSV color space in the positive and negative\n directions, respectively. See `kornia.enhance.adjust_hue` for more details.\n :param sat_epsilon: The boundary of the saturation perturbation. The value is expected to be in the interval\n `[0, infinity]`. The perturbation of `0` gives a black-and-white image, `1` gives the\n original image, and `2` enhances the saturation by a factor of 2. See\n `kornia.geometry.transform.rotate` for more details.\n :param rot_epsilon: The boundary of the rotation perturbation (in degrees). Positive values mean\n counter-clockwise rotation. See `kornia.geometry.transform.rotate` for more details.\n :param bri_epsilon: The boundary of the brightness perturbation. The value is expected to be in the interval\n `[-1, 1]`. Perturbation of `0` means no shift, `-1` gives a complete black image, and `1`\n gives a complete white image. See `kornia.enhance.adjust_brightness` for more details.\n :param con_epsilon: The boundary of the contrast perturbation. The value is expected to be in the interval\n `[0, infinity]`. Perturbation of `0` gives a complete black image, `1` does not modify the\n image, and any other value modifies the brightness by this factor. See\n `kornia.enhance.adjust_contrast` for more details.\n :param pgd_epsilon: The maximum perturbation that the attacker can introduce in the L-infinity ball.\n :param early_stop: When True, the attack will stop if the perturbed example is classified incorrectly by the\n classifier.\n :param max_iter: The maximum number of iterations for attack order optimization.\n :param max_inner_iter: The maximum number of iterations for each attack optimization.\n :param attack_order: Specify the scheduling type for composite adversarial attack. The value is expected to be\n `fixed`, `random`, or `scheduled`. `fixed` means the attack order is the same as specified\n in `enabled_attack`. `random` means the attack order is randomly generated at each\n iteration. `scheduled` means to enable the attack order optimization proposed in the paper.\n If only one attack is enabled, `fixed` will be used.\n :param batch_size: The batch size to use during the generation of adversarial samples.\n :param verbose: Show progress bars.\n \"\"\"\n import torch\n\n super().__init__(estimator=classifier)\n self.classifier = classifier\n self.model = classifier.model\n self.device = next(self.model.parameters()).device\n self.fixed_order = enabled_attack\n self.enabled_attack = tuple(sorted(enabled_attack))\n self.epsilons = [hue_epsilon, sat_epsilon, rot_epsilon, bri_epsilon, con_epsilon, pgd_epsilon]\n self.early_stop = early_stop\n self.attack_order = attack_order\n self.max_iter = max_iter if self.attack_order == \"scheduled\" else 1\n self.max_inner_iter = max_inner_iter\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n import kornia\n\n self.seq_num = len(self.enabled_attack) # attack_num\n self.linf_idx = self.enabled_attack.index(5) if 5 in self.enabled_attack else None\n self.attack_pool = (\n self.caa_hue,\n self.caa_saturation,\n self.caa_rotation,\n self.caa_brightness,\n self.caa_contrast,\n self.caa_linf,\n )\n self.eps_pool = torch.tensor(self.epsilons, device=self.device)\n self.attack_pool_base = (\n kornia.enhance.adjust_hue,\n kornia.enhance.adjust_saturation,\n kornia.geometry.transform.rotate,\n kornia.enhance.adjust_brightness,\n kornia.enhance.adjust_contrast,\n )\n self.attack_dict = tuple(self.attack_pool[i] for i in self.enabled_attack)\n self.step_size_pool = [\n 2.5 * ((eps[1] - eps[0]) / 2) / self.max_inner_iter for eps in self.eps_pool\n ] # 2.5 * \u03b5-test / num_steps\n\n self._description = \"Composite Adversarial Attack\"\n self._is_scheduling: bool = False\n self.eps_space: list = []\n self.adv_val_space: list = []\n self.curr_dsm: \"torch.Tensor\" = torch.zeros((len(self.enabled_attack), len(self.enabled_attack)))\n self.curr_seq: \"torch.Tensor\" = torch.zeros(len(self.enabled_attack))\n self.is_attacked: \"torch.Tensor\" = torch.zeros(self.batch_size, device=self.device).bool()\n self.is_not_attacked: \"torch.Tensor\" = torch.ones(self.batch_size, device=self.device).bool()\n\n def _check_params(self) -> None:\n \"\"\"\n Check validity of parameters.\n \"\"\"\n super()._check_params()\n if not isinstance(self.enabled_attack, tuple) or not all(\n value in [0, 1, 2, 3, 4, 5] for value in self.enabled_attack\n ):\n raise ValueError(\n \"The parameter `enabled_attack` must be a tuple specifying the attack to launch. For simplicity, we use\"\n + \" the following abbreviations to specify each attack types. 0: Hue, 1: Saturation, 2: Rotation,\"\n + \" 3: Brightness, 4: Contrast, 5: PGD(L-infinity). Therefore, `(0,1,2)` means that the attack combines\"\n + \" hue, saturation, and rotation; `(0,1,2,3,4)` means the all semantic attacks; `(0,1,2,3,4,5)` means\"\n + \" the full attacks.\"\n )\n _epsilons_range = (\n (\"hue_epsilon\", (-np.pi, np.pi), \"(-np.pi, np.pi)\"),\n (\"sat_epsilon\", (0.0, np.inf), \"(0.0, np.inf)\"),\n (\"rot_epsilon\", (-360.0, 360.0), \"(-360.0, 360.0)\"),\n (\"bri_epsilon\", (-1.0, 1.0), \"(-1.0, 1.0)\"),\n (\"con_epsilon\", (0.0, np.inf), \"(0.0, np.inf)\"),\n (\"pgd_epsilon\", (-1.0, 1.0), \"(-1.0, 1.0)\"),\n )\n for i in range(6):\n if (\n not isinstance(self.epsilons[i], tuple)\n or not len(self.epsilons[i]) == 2\n or not (isinstance(self.epsilons[i][0], float) and isinstance(self.epsilons[i][1], float))\n ):\n logger.info(\n \"The argument `%s` must be an interval within %s of type tuple.\",\n _epsilons_range[i][0],\n _epsilons_range[i][2],\n )\n raise TypeError(\n f\"The argument `{_epsilons_range[i][0]}` must be an interval \"\n f\"within {_epsilons_range[i][2]} of type tuple.\"\n )\n\n if not _epsilons_range[i][1][0] <= self.epsilons[i][0] <= self.epsilons[i][1] <= _epsilons_range[i][1][1]:\n logger.info(\n \"The argument `%s` must be an interval within %s of type tuple.\",\n _epsilons_range[i][0],\n _epsilons_range[i][2],\n )\n raise ValueError(\n f\"The argument `{_epsilons_range[i][0]}` must be an interval \"\n f\"within {_epsilons_range[i][2]} of type tuple.\"\n )\n\n if not isinstance(self.early_stop, bool):\n logger.info(\"The flag `early_stop` has to be of type bool.\")\n raise TypeError(\"The flag `early_stop` has to be of type bool.\")\n\n if not isinstance(self.max_iter, int):\n logger.info(\"The argument `max_iter` must be positive of type int.\")\n raise TypeError(\"The argument `max_iter` must be positive of type int.\")\n\n if self.max_iter <= 0:\n logger.info(\"The argument `max_iter` must be positive of type int.\")\n raise ValueError(\"The argument `max_iter` must be positive of type int.\")\n\n if not isinstance(self.max_inner_iter, int):\n logger.info(\"The argument `max_inner_iter` must be positive of type int.\")\n raise TypeError(\"The argument `max_inner_iter` must be positive of type int.\")\n\n if self.max_inner_iter <= 0:\n logger.info(\"The argument `max_inner_iter` must be positive of type int.\")\n raise ValueError(\"The argument `max_inner_iter` must be positive of type int.\")\n\n if self.attack_order not in (\"fixed\", \"random\", \"scheduled\"):\n logger.info(\"The argument `attack_order` should be either `fixed`, `random`, or `scheduled`.\")\n raise ValueError(\"The argument `attack_order` should be either `fixed`, `random`, or `scheduled`.\")\n\n if self.batch_size <= 0:\n logger.info(\"The batch size has to be positive.\")\n raise ValueError(\"The batch size has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n logger.info(\"The argument `verbose` has to be a Boolean.\")\n raise TypeError(\"The argument `verbose` has to be a Boolean.\")\n\n def _setup_attack(self):\n \"\"\"\n Set up the initial parameter for each attack component.\n \"\"\"\n import torch\n\n hue_space = (\n torch.rand(self.batch_size, device=self.device) * (self.eps_pool[0][1] - self.eps_pool[0][0])\n + self.eps_pool[0][0]\n )\n sat_space = (\n torch.rand(self.batch_size, device=self.device) * (self.eps_pool[1][1] - self.eps_pool[1][0])\n + self.eps_pool[1][0]\n )\n rot_space = (\n torch.rand(self.batch_size, device=self.device) * (self.eps_pool[2][1] - self.eps_pool[2][0])\n + self.eps_pool[2][0]\n )\n bri_space = (\n torch.rand(self.batch_size, device=self.device) * (self.eps_pool[3][1] - self.eps_pool[3][0])\n + self.eps_pool[3][0]\n )\n con_space = (\n torch.rand(self.batch_size, device=self.device) * (self.eps_pool[4][1] - self.eps_pool[4][0])\n + self.eps_pool[4][0]\n )\n pgd_space = 0.001 * torch.randn([self.batch_size, 3, 32, 32], device=self.device)\n\n self.eps_space = [self.eps_pool[i] for i in self.enabled_attack]\n self.adv_val_space = [\n [hue_space, sat_space, rot_space, bri_space, con_space, pgd_space][i] for i in self.enabled_attack\n ]\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate the composite adversarial samples and return them in a Numpy array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the composite adversarial examples.\n \"\"\"\n if y is None:\n raise ValueError(\"The argument `y` must be provided.\")\n\n import torch\n\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n dataset = torch.utils.data.TensorDataset(\n torch.from_numpy(x.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(y.astype(ART_NUMPY_DTYPE)),\n )\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=self.batch_size, shuffle=False, drop_last=False\n )\n\n # Start to compute adversarial examples.\n x_adv = x.copy().astype(ART_NUMPY_DTYPE)\n\n # Compute perturbations with batching.\n for batch_id, batch_all in enumerate(\n tqdm(data_loader, desc=self._description, leave=False, disable=not self.verbose)\n ):\n (batch_x, batch_y) = batch_all[0], batch_all[1]\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n\n x_adv[batch_index_1:batch_index_2] = self._generate_batch(x=batch_x, y=batch_y)\n\n logger.info(\n \"Success rate of attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, batch_size=self.batch_size),\n )\n\n return x_adv\n\n def _generate_batch(self, x: \"torch.Tensor\", y: \"torch.Tensor\") -> np.ndarray:\n \"\"\"\n Generate a batch of composite adversarial examples and return them in a NumPy array.\n\n :param x: A tensor of a batch of original inputs to be attacked.\n :param y: A tensor of a batch of the original labels to be predicted.\n :return: An array holding the composite adversarial examples.\n \"\"\"\n import torch\n\n self.batch_size = x.shape[0]\n self._setup_attack()\n self.is_attacked = torch.zeros(self.batch_size, device=self.device).bool()\n self.is_not_attacked = torch.ones(self.batch_size, device=self.device).bool()\n x, y = x.to(self.device), y.to(self.device)\n\n return self.caa_attack(x, y).cpu().detach().numpy()\n\n def _comp_pgd(\n self,\n data: \"torch.Tensor\",\n labels: \"torch.Tensor\",\n attack_idx: int,\n attack_parameter: \"torch.Tensor\",\n ori_is_attacked: \"torch.Tensor\",\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for each attack component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :param attack_idx: The index of the attack component (one of the enabled attacks) in the attack pool.\n :param attack_parameter: Specify the parameter of the attack component. For example, hue shift angle, saturation\n factor, etc.\n :param ori_is_attacked: Specify whether the perturbed data is already attacked.\n :return: The perturbed data and the corresponding attack parameter.\n \"\"\"\n import torch\n import torch.nn.functional as F\n\n adv_data = self.attack_pool_base[attack_idx](data, attack_parameter)\n for _ in range(self.max_inner_iter):\n outputs = self.model(adv_data)\n\n if not self._is_scheduling and self.early_stop:\n cur_pred = outputs.max(1, keepdim=True)[1].squeeze()\n self.is_attacked = torch.logical_or(\n ori_is_attacked, cur_pred != labels.max(1, keepdim=True)[1].squeeze()\n )\n\n with torch.enable_grad():\n cost = F.cross_entropy(outputs, labels)\n _grad = torch.autograd.grad(cost, attack_parameter)[0]\n if not self._is_scheduling:\n _grad[self.is_attacked] = 0\n attack_parameter = (\n torch.clamp(\n attack_parameter + torch.sign(_grad) * self.step_size_pool[attack_idx],\n self.eps_pool[attack_idx][0],\n self.eps_pool[attack_idx][1],\n )\n .detach()\n .requires_grad_()\n )\n adv_data = self.attack_pool_base[attack_idx](data, attack_parameter)\n\n return adv_data, attack_parameter\n\n def caa_hue(\n self, data: \"torch.Tensor\", hue: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for hue component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param hue: Specify the hue shift angle.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data and the corresponding hue shift angle.\n \"\"\"\n hue = hue.detach().clone()\n hue[self.is_attacked] = 0\n hue.requires_grad_()\n sur_data = data.detach().requires_grad_()\n\n return self._comp_pgd(\n data=sur_data, labels=labels, attack_idx=0, attack_parameter=hue, ori_is_attacked=self.is_attacked.clone()\n )\n\n def caa_saturation(\n self, data: \"torch.Tensor\", saturation: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for saturation component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param saturation: Specify the saturation factor.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data and the corresponding saturation factor.\n \"\"\"\n saturation = saturation.detach().clone()\n saturation[self.is_attacked] = 1\n saturation.requires_grad_()\n sur_data = data.detach().requires_grad_()\n\n return self._comp_pgd(\n data=sur_data,\n labels=labels,\n attack_idx=1,\n attack_parameter=saturation,\n ori_is_attacked=self.is_attacked.clone(),\n )\n\n def caa_rotation(\n self, data: \"torch.Tensor\", theta: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for rotation component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param theta: Specify the rotation angle.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data and the corresponding rotation angle.\n \"\"\"\n theta = theta.detach().clone()\n theta[self.is_attacked] = 0\n theta.requires_grad_()\n sur_data = data.detach().requires_grad_()\n\n return self._comp_pgd(\n data=sur_data, labels=labels, attack_idx=2, attack_parameter=theta, ori_is_attacked=self.is_attacked.clone()\n )\n\n def caa_brightness(\n self, data: \"torch.Tensor\", brightness: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for brightness component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param brightness: Specify the brightness factor.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data and the corresponding brightness factor.\n \"\"\"\n brightness = brightness.detach().clone()\n brightness[self.is_attacked] = 0\n brightness.requires_grad_()\n sur_data = data.detach().requires_grad_()\n\n return self._comp_pgd(\n data=sur_data,\n labels=labels,\n attack_idx=3,\n attack_parameter=brightness,\n ori_is_attacked=self.is_attacked.clone(),\n )\n\n def caa_contrast(\n self, data: \"torch.Tensor\", contrast: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for contrast component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param contrast: Specify the contrast factor.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data and the corresponding contrast factor.\n \"\"\"\n contrast = contrast.detach().clone()\n contrast[self.is_attacked] = 1\n contrast.requires_grad_()\n sur_data = data.detach().requires_grad_()\n\n return self._comp_pgd(\n data=sur_data,\n labels=labels,\n attack_idx=4,\n attack_parameter=contrast,\n ori_is_attacked=self.is_attacked.clone(),\n )\n\n def caa_linf(\n self, data: \"torch.Tensor\", eta: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the adversarial examples for L-infinity (PGD) component.\n\n :param data: A tensor of a batch of original inputs to be attacked.\n :param eta: The perturbation in the L-infinity ball.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data.\n \"\"\"\n import torch\n import torch.nn.functional as F\n\n sur_data = data.detach()\n adv_data = data.detach().requires_grad_()\n ori_is_attacked = self.is_attacked.clone()\n for _ in range(self.max_inner_iter):\n outputs = self.model(adv_data)\n\n if not self._is_scheduling and self.early_stop:\n cur_pred = outputs.max(1, keepdim=True)[1].squeeze()\n self.is_attacked = torch.logical_or(\n ori_is_attacked, cur_pred != labels.max(1, keepdim=True)[1].squeeze()\n )\n\n with torch.enable_grad():\n cost = F.cross_entropy(outputs, labels)\n _grad = torch.autograd.grad(cost, adv_data)[0]\n if not self._is_scheduling:\n _grad[self.is_attacked] = 0\n adv_data = adv_data + self.step_size_pool[5] * torch.sign(_grad)\n eta = torch.clamp(adv_data - sur_data, min=self.eps_pool[5][0], max=self.eps_pool[5][1])\n adv_data = torch.clamp(sur_data + eta, min=0.0, max=1.0).detach_().requires_grad_()\n\n return adv_data, eta\n\n def update_attack_order(self, images: \"torch.Tensor\", labels: \"torch.Tensor\", adv_val: list) -> None:\n \"\"\"\n Update the specified attack ordering.\n\n :param images: A tensor of a batch of original inputs to be attacked.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :param adv_val: Optional; A list of a batch of current attack parameters.\n \"\"\"\n import torch\n import torch.nn.functional as F\n\n def hungarian(matrix_batch):\n sol = torch.tensor([-i for i in range(1, matrix_batch.shape[0] + 1)], dtype=torch.int32)\n for i in range(matrix_batch.shape[0]):\n topk = 1\n sol[i] = torch.topk(matrix_batch[i], topk)[1][topk - 1]\n while sol.shape != torch.unique(sol).shape:\n topk = topk + 1\n sol[i] = torch.topk(matrix_batch[i], topk)[1][topk - 1]\n return sol\n\n def sinkhorn_normalization(ori_dsm, n_iters=20):\n for _ in range(n_iters):\n ori_dsm /= ori_dsm.sum(dim=0, keepdim=True)\n ori_dsm /= ori_dsm.sum(dim=1, keepdim=True)\n return ori_dsm\n\n if self.attack_order == \"fixed\":\n if self.curr_seq.sum() == 0:\n self.fixed_order = tuple(self.enabled_attack.index(i) for i in self.fixed_order)\n self.curr_seq = torch.tensor(self.fixed_order, device=self.device)\n elif self.attack_order == \"random\":\n self.curr_seq = torch.randperm(self.seq_num)\n elif self.attack_order == \"scheduled\":\n if self.curr_seq.sum() == 0:\n self.curr_dsm = sinkhorn_normalization(torch.rand((self.seq_num, self.seq_num)))\n self.curr_seq = hungarian(self.curr_dsm)\n self.curr_dsm = self.curr_dsm.detach().requires_grad_()\n adv_img = images.clone().detach().requires_grad_()\n original_iter_num = self.max_inner_iter\n self.max_inner_iter = 3\n self._is_scheduling = True\n for tdx in range(self.seq_num):\n prev_img = adv_img.clone()\n adv_img = torch.zeros_like(adv_img)\n for idx in range(self.seq_num):\n _adv_img, _ = self.attack_dict[idx](prev_img, adv_val[idx], labels)\n adv_img = adv_img + self.curr_dsm[tdx][idx] * _adv_img\n self._is_scheduling = False\n self.max_inner_iter = original_iter_num\n outputs = self.model(adv_img)\n with torch.enable_grad():\n cost = F.cross_entropy(outputs, labels)\n\n dsm_grad = torch.autograd.grad(cost, self.curr_dsm)[0]\n\n prev_seq = self.curr_seq.clone()\n dsm_noise = torch.zeros_like(self.curr_dsm)\n while torch.equal(prev_seq, self.curr_seq):\n self.curr_dsm = sinkhorn_normalization(torch.exp(self.curr_dsm + dsm_grad + dsm_noise).detach())\n self.curr_seq = hungarian(self.curr_dsm.detach())\n dsm_noise = (torch.randn_like(self.curr_dsm) + 1) * 2 # Escaping local optimum\n else:\n raise ValueError()\n\n def caa_attack(self, images: \"torch.Tensor\", labels: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n The main algorithm to generate the adversarial examples for composite adversarial attack.\n\n :param images: A tensor of a batch of original inputs to be attacked.\n :param labels: A tensor of a batch of the original labels to be predicted.\n :return: The perturbed data.\n \"\"\"\n import torch\n\n adv_img = images.detach().clone()\n adv_val_saved = torch.zeros((self.seq_num, self.batch_size), device=self.device)\n adv_val = [self.adv_val_space[idx] for idx in range(self.seq_num)]\n\n if self.is_attacked.sum() > 0:\n for att_id in range(self.seq_num):\n if att_id == self.linf_idx:\n continue\n adv_val[att_id].detach()\n adv_val[att_id][self.is_attacked] = adv_val_saved[att_id][self.is_attacked]\n adv_val[att_id].requires_grad_()\n\n for _ in range(self.max_iter):\n self.update_attack_order(images, labels, adv_val)\n\n adv_img = adv_img.detach().clone()\n self.is_not_attacked = torch.logical_not(self.is_attacked)\n adv_img[self.is_not_attacked] = images[self.is_not_attacked].clone()\n adv_img.requires_grad = True\n\n for tdx in range(self.seq_num):\n idx = self.curr_seq[tdx]\n adv_img, adv_val_updated = self.attack_dict[idx](adv_img, adv_val[idx], labels) # type: ignore\n if idx != self.linf_idx:\n adv_val[idx] = adv_val_updated\n\n outputs = self.model(adv_img)\n cur_pred = outputs.max(1, keepdim=True)[1].squeeze()\n self.is_attacked = torch.logical_or(self.is_attacked, cur_pred != labels.max(1, keepdim=True)[1].squeeze())\n\n if self.is_attacked.sum() > 0:\n for att_id in range(self.seq_num):\n if att_id == self.linf_idx:\n continue\n adv_val_saved[att_id][self.is_attacked] = adv_val[att_id][self.is_attacked].detach()\n\n if self.is_attacked.sum() == self.batch_size:\n break\n\n return adv_img\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/decision_tree_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attacks on Decision Trees.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\nfrom art.utils import check_and_transform_label_format\n\nlogger = logging.getLogger(__name__)\n\n\nclass DecisionTreeAttack(EvasionAttack):\n \"\"\"\n Close implementation of Papernot's attack on decision trees following Algorithm 2 and communication with the\n authors.\n\n | Paper link: https://arxiv.org/abs/1605.07277\n \"\"\"\n\n attack_params = [\"classifier\", \"offset\", \"verbose\"]\n _estimator_requirements = (ScikitlearnDecisionTreeClassifier,)\n\n def __init__(\n self,\n classifier: ScikitlearnDecisionTreeClassifier,\n offset: float = 0.001,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n :param classifier: A trained scikit-learn decision tree model.\n :param offset: How much the value is pushed away from tree's threshold.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.offset = offset\n self.verbose = verbose\n self._check_params()\n\n def _df_subtree(\n self,\n position: int,\n original_class: int | np.ndarray,\n target: int | None = None,\n ) -> list[int]:\n \"\"\"\n Search a decision tree for a mis-classifying instance.\n\n :param position: An array with the original inputs to be attacked.\n :param original_class: original label for the instances we are searching mis-classification for.\n :param target: If the provided, specifies which output the leaf has to have to be accepted.\n :return: An array specifying the path to the leaf where the classification is either != original class or\n ==target class if provided.\n \"\"\"\n # base case, we're at a leaf\n if self.estimator.get_left_child(position) == self.estimator.get_right_child(position):\n if target is None: # untargeted case\n if self.estimator.get_classes_at_node(position) != original_class:\n path = [position]\n else:\n path = [-1]\n else: # targeted case\n if self.estimator.get_classes_at_node(position) == target:\n path = [position]\n else:\n path = [-1]\n else: # go deeper, depths first\n res = self._df_subtree(self.estimator.get_left_child(position), original_class, target)\n if res[0] == -1:\n # no result, try right subtree\n res = self._df_subtree(self.estimator.get_right_child(position), original_class, target)\n if res[0] == -1:\n # no desired result\n path = [-1]\n else:\n res.append(position)\n path = res\n else:\n # done, it is returning a path\n res.append(position)\n path = res\n\n return path\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial examples and return them as an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=False)\n x_adv = x.copy()\n\n for index in trange(x_adv.shape[0], desc=\"Decision tree attack\", disable=not self.verbose):\n path = self.estimator.get_decision_path(x_adv[index])\n legitimate_class = int(np.argmax(self.estimator.predict(x_adv[index].reshape(1, -1))))\n position = -2\n adv_path = [-1]\n ancestor = path[position]\n while np.abs(position) < (len(path) - 1) or adv_path[0] == -1:\n ancestor = path[position]\n current_child = path[position + 1]\n # search in right subtree\n if current_child == self.estimator.get_left_child(ancestor):\n if y is None:\n adv_path = self._df_subtree(self.estimator.get_right_child(ancestor), legitimate_class)\n else:\n adv_path = self._df_subtree(\n self.estimator.get_right_child(ancestor),\n legitimate_class,\n y[index],\n )\n else: # search in left subtree\n if y is None:\n adv_path = self._df_subtree(self.estimator.get_left_child(ancestor), legitimate_class)\n else:\n adv_path = self._df_subtree(\n self.estimator.get_left_child(ancestor),\n legitimate_class,\n y[index],\n )\n position = position - 1 # we are going the decision path upwards\n adv_path.append(ancestor)\n # we figured out which is the way to the target, now perturb\n # first one is leaf-> no threshold, cannot be perturbed\n for i in range(1, 1 + len(adv_path[1:])):\n go_for = adv_path[i - 1]\n threshold = self.estimator.get_threshold_at_node(adv_path[i])\n feature = self.estimator.get_feature_at_node(adv_path[i])\n # only perturb if the feature is actually wrong\n if x_adv[index][feature] > threshold and go_for == self.estimator.get_left_child(adv_path[i]):\n x_adv[index][feature] = threshold - self.offset\n elif x_adv[index][feature] <= threshold and go_for == self.estimator.get_right_child(adv_path[i]):\n x_adv[index][feature] = threshold + self.offset\n\n return x_adv\n\n def _check_params(self) -> None:\n\n if self.offset <= 0:\n raise ValueError(\"The offset parameter must be strictly positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/deepfool.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the white-box attack `DeepFool`.\n\n| Paper link: https://arxiv.org/abs/1511.04599\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import is_probability\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass DeepFool(EvasionAttack):\n \"\"\"\n Implementation of the attack from Moosavi-Dezfooli et al. (2015).\n\n | Paper link: https://arxiv.org/abs/1511.04599\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"max_iter\",\n \"epsilon\",\n \"nb_grads\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n max_iter: int = 100,\n epsilon: float = 1e-6,\n nb_grads: int = 10,\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a DeepFool attack instance.\n\n :param classifier: A trained classifier.\n :param max_iter: The maximum number of iterations.\n :param epsilon: Overshoot parameter.\n :param nb_grads: The number of class gradients (top nb_grads w.r.t. prediction) to compute. This way only the\n most likely classes are considered, speeding up the computation.\n :param batch_size: Batch size\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.max_iter = max_iter\n self.epsilon = epsilon\n self.nb_grads = nb_grads\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n if self.estimator.clip_values is None:\n logger.warning(\n \"The `clip_values` attribute of the estimator is `None`, therefore this instance of DeepFool will by \"\n \"default generate adversarial perturbations scaled for input values in the range [0, 1] but not clip \"\n \"the adversarial example.\"\n )\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the adversarial examples.\n \"\"\"\n x_adv = x.astype(ART_NUMPY_DTYPE)\n preds = self.estimator.predict(x, batch_size=self.batch_size)\n\n if self.estimator.nb_classes == 2 and preds.shape[1] == 1:\n raise ValueError( # pragma: no cover\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if is_probability(preds[0]):\n logger.warning(\n \"It seems that the attacked model is predicting probabilities. DeepFool expects logits as model output \"\n \"to achieve its full attack strength.\"\n )\n\n # Determine the class labels for which to compute the gradients\n use_grads_subset = self.nb_grads < self.estimator.nb_classes\n if use_grads_subset:\n # TODO compute set of unique labels per batch\n grad_labels = np.argsort(-preds, axis=1)[:, : self.nb_grads]\n labels_set = np.unique(grad_labels)\n else:\n labels_set = np.arange(self.estimator.nb_classes)\n sorter = np.arange(len(labels_set))\n\n # Pick a small scalar to avoid division by 0\n tol = 10e-8\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_adv.shape[0] / float(self.batch_size))), desc=\"DeepFool\", disable=not self.verbose\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch = x_adv[batch_index_1:batch_index_2].copy()\n\n # Get predictions and gradients for batch\n f_batch = preds[batch_index_1:batch_index_2]\n fk_hat = np.argmax(f_batch, axis=1)\n if use_grads_subset:\n # Compute gradients only for top predicted classes\n grd = np.array([self.estimator.class_gradient(batch, label=int(label_i)) for label_i in labels_set])\n grd = np.squeeze(np.swapaxes(grd, 0, 2), axis=0)\n else:\n # Compute gradients for all classes\n grd = self.estimator.class_gradient(batch)\n\n # Get current predictions\n active_indices = np.arange(len(batch))\n current_step = 0\n while active_indices.size > 0 and current_step < self.max_iter:\n # Compute difference in predictions and gradients only for selected top predictions\n labels_indices = sorter[np.searchsorted(labels_set, fk_hat, sorter=sorter)]\n grad_diff = grd - grd[np.arange(len(grd)), labels_indices][:, None]\n f_diff = f_batch[:, labels_set] - f_batch[np.arange(len(f_batch)), labels_indices][:, None]\n\n # Choose coordinate and compute perturbation\n norm = np.linalg.norm(grad_diff.reshape(len(grad_diff), len(labels_set), -1), axis=2) + tol\n value = np.abs(f_diff) / norm\n value[np.arange(len(value)), labels_indices] = np.inf\n l_var = np.argmin(value, axis=1)\n absolute1 = abs(f_diff[np.arange(len(f_diff)), l_var])\n draddiff = grad_diff[np.arange(len(grad_diff)), l_var].reshape(len(grad_diff), -1)\n pow1 = (\n pow(\n np.linalg.norm(draddiff, axis=1),\n 2,\n )\n + tol\n )\n r_var = absolute1 / pow1\n r_var = r_var.reshape((-1,) + (1,) * (len(x.shape) - 1))\n r_var = r_var * grad_diff[np.arange(len(grad_diff)), l_var]\n\n # Add perturbation and clip result\n if self.estimator.clip_values is not None:\n batch[active_indices] = np.clip(\n batch[active_indices]\n + r_var[active_indices] * (self.estimator.clip_values[1] - self.estimator.clip_values[0]),\n self.estimator.clip_values[0],\n self.estimator.clip_values[1],\n )\n else:\n batch[active_indices] += r_var[active_indices]\n\n # Recompute prediction for new x\n f_batch = self.estimator.predict(batch)\n fk_i_hat = np.argmax(f_batch, axis=1)\n\n # Recompute gradients for new x\n if use_grads_subset:\n # Compute gradients only for (originally) top predicted classes\n grd = np.array([self.estimator.class_gradient(batch, label=int(label_i)) for label_i in labels_set])\n grd = np.squeeze(np.swapaxes(grd, 0, 2), axis=0)\n else:\n # Compute gradients for all classes\n grd = self.estimator.class_gradient(batch)\n\n # Stop if misclassification has been achieved\n active_indices = np.where(fk_i_hat == fk_hat)[0]\n\n current_step += 1\n\n # Apply overshoot parameter\n x_adv1 = x_adv[batch_index_1:batch_index_2]\n x_adv2 = (1 + self.epsilon) * (batch - x_adv[batch_index_1:batch_index_2])\n x_adv[batch_index_1:batch_index_2] = x_adv1 + x_adv2\n if self.estimator.clip_values is not None:\n np.clip(\n x_adv[batch_index_1:batch_index_2],\n self.estimator.clip_values[0],\n self.estimator.clip_values[1],\n out=x_adv[batch_index_1:batch_index_2],\n )\n\n return x_adv\n\n def _check_params(self) -> None:\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if not isinstance(self.nb_grads, int) or self.nb_grads <= 0:\n raise ValueError(\"The number of class gradients to compute must be a positive integer.\")\n\n if self.epsilon < 0:\n raise ValueError(\"The overshoot parameter must not be negative.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/dpatch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the adversarial patch attack `DPatch` for object detectors.\n\n| Paper link: https://arxiv.org/abs/1806.02299v4\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport math\nimport random\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\nfrom art import config\n\nif TYPE_CHECKING:\n from art.utils import OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass DPatch(EvasionAttack):\n \"\"\"\n Implementation of the DPatch attack.\n\n | Paper link: https://arxiv.org/abs/1806.02299v4\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"patch_shape\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ObjectDetectorMixin)\n\n def __init__(\n self,\n estimator: \"OBJECT_DETECTOR_TYPE\",\n patch_shape: tuple[int, int, int] = (40, 40, 3),\n learning_rate: float = 5.0,\n max_iter: int = 500,\n batch_size: int = 16,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.DPatch`.\n\n :param estimator: A trained object detector.\n :param patch_shape: The shape of the adversarial path as a tuple of shape (height, width, nb_channels).\n :param learning_rate: The learning rate of the optimization.\n :param max_iter: The number of optimization steps.\n :param batch_size: The size of the training batch.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.patch_shape = patch_shape\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n if self.estimator.clip_values is None:\n self._patch = np.zeros(shape=patch_shape, dtype=config.ART_NUMPY_DTYPE)\n else:\n self._patch = (\n np.random.randint(0, 255, size=patch_shape)\n / 255\n * (self.estimator.clip_values[1] - self.estimator.clip_values[0])\n + self.estimator.clip_values[0]\n ).astype(config.ART_NUMPY_DTYPE)\n\n self.target_label: int | np.ndarray | list[int] | None = []\n\n def generate(\n self,\n x: np.ndarray,\n y: np.ndarray | None = None,\n target_label: int | np.ndarray | list[int] | None = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Generate DPatch.\n\n :param x: Sample images.\n :param y: True labels of type `list[dict[np.ndarray]]` for untargeted attack, one dictionary per input image.\n The keys and values of the dictionary are:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image\n - scores [N]: the scores or each prediction.\n :param target_label: The target label of the DPatch attack.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :type mask: `np.ndarray`\n :return: Adversarial patch.\n \"\"\"\n mask = kwargs.get(\"mask\")\n if mask is not None:\n mask = mask.copy()\n if mask is not None and ( # pragma: no cover\n mask.dtype != bool\n or not (mask.shape[0] == 1 or mask.shape[0] == x.shape[0])\n or not (\n (mask.shape[1] == x.shape[1] and mask.shape[2] == x.shape[2])\n or (mask.shape[1] == x.shape[2] and mask.shape[2] == x.shape[3])\n )\n ):\n raise ValueError(\n \"The shape of `mask` has to be equal to the shape of a single samples (1, H, W) or the\"\n \"shape of `x` (N, H, W) without their channel dimensions.\"\n )\n\n channel_index = 1 if self.estimator.channels_first else x.ndim - 1\n if x.shape[channel_index] != self.patch_shape[channel_index - 1]:\n raise ValueError(\"The color channel index of the images and the patch have to be identical.\")\n if x.ndim != 4: # pragma: no cover\n raise ValueError(\"The adversarial patch can only be applied to images.\")\n if target_label is not None:\n if isinstance(target_label, int):\n self.target_label = [target_label] * x.shape[0]\n elif isinstance(target_label, np.ndarray):\n if target_label.shape not in ((x.shape[0], 1), (x.shape[0],)): # pragma: no cover\n raise ValueError(\"The target_label has to be a 1-dimensional array.\")\n self.target_label = target_label.tolist()\n else:\n if not len(target_label) == x.shape[0] or not isinstance(target_label, list): # pragma: no cover\n raise ValueError(\"The target_label as list of integers needs to of length number of images in `x`.\")\n self.target_label = target_label\n\n patched_images, transforms = self._augment_images_with_patch(\n x,\n self._patch,\n random_location=True,\n channels_first=self.estimator.channels_first,\n mask=mask,\n transforms=None,\n )\n patch_target: list[dict[str, np.ndarray]] = []\n\n if self.target_label and y is None:\n\n for i_image in range(patched_images.shape[0]):\n if isinstance(self.target_label, int):\n t_l = self.target_label\n else:\n t_l = self.target_label[i_image]\n\n i_x_1 = transforms[i_image][\"i_x_1\"]\n i_x_2 = transforms[i_image][\"i_x_2\"]\n i_y_1 = transforms[i_image][\"i_y_1\"]\n i_y_2 = transforms[i_image][\"i_y_2\"]\n\n target_dict = {}\n target_dict[\"boxes\"] = np.asarray([[i_x_1, i_y_1, i_x_2, i_y_2]])\n target_dict[\"labels\"] = np.asarray(\n [\n t_l,\n ]\n )\n target_dict[\"scores\"] = np.asarray(\n [\n 1.0,\n ]\n )\n\n patch_target.append(target_dict)\n\n else:\n\n predictions = y if y is not None else self.estimator.predict(x=patched_images, standardise_output=True)\n\n for i_image in range(patched_images.shape[0]):\n target_dict = {}\n target_dict[\"boxes\"] = predictions[i_image][\"boxes\"]\n target_dict[\"labels\"] = predictions[i_image][\"labels\"]\n target_dict[\"scores\"] = predictions[i_image][\"scores\"]\n\n patch_target.append(target_dict)\n\n for i_step in trange(self.max_iter, desc=\"DPatch iteration\", disable=not self.verbose):\n if i_step == 0 or (i_step + 1) % 100 == 0:\n logger.info(\"Training Step: %i\", i_step + 1)\n\n num_batches = math.ceil(x.shape[0] / self.batch_size)\n patch_gradients = np.zeros_like(self._patch)\n\n for i_batch in range(num_batches):\n i_batch_start = i_batch * self.batch_size\n i_batch_end = min((i_batch + 1) * self.batch_size, patched_images.shape[0])\n\n gradients = self.estimator.loss_gradient(\n x=patched_images[i_batch_start:i_batch_end],\n y=patch_target[i_batch_start:i_batch_end],\n standardise_output=True,\n )\n\n for i_image in range(gradients.shape[0]):\n\n i_x_1 = transforms[i_batch_start + i_image][\"i_x_1\"]\n i_x_2 = transforms[i_batch_start + i_image][\"i_x_2\"]\n i_y_1 = transforms[i_batch_start + i_image][\"i_y_1\"]\n i_y_2 = transforms[i_batch_start + i_image][\"i_y_2\"]\n\n if self.estimator.channels_first:\n patch_gradients_i = gradients[i_image, :, i_x_1:i_x_2, i_y_1:i_y_2]\n else:\n patch_gradients_i = gradients[i_image, i_x_1:i_x_2, i_y_1:i_y_2, :]\n\n patch_gradients = patch_gradients + patch_gradients_i\n\n if self.target_label:\n self._patch = self._patch - np.sign(patch_gradients) * self.learning_rate\n else:\n self._patch = self._patch + np.sign(patch_gradients) * self.learning_rate\n\n if self.estimator.clip_values is not None:\n self._patch = np.clip(\n self._patch,\n a_min=self.estimator.clip_values[0],\n a_max=self.estimator.clip_values[1],\n )\n\n patched_images, _ = self._augment_images_with_patch(\n x,\n self._patch,\n random_location=False,\n channels_first=self.estimator.channels_first,\n mask=None,\n transforms=transforms,\n )\n\n return self._patch\n\n @staticmethod\n def _augment_images_with_patch(\n x: np.ndarray,\n patch: np.ndarray,\n random_location: bool,\n channels_first: bool,\n mask: np.ndarray | None = None,\n transforms: list[dict[str, int]] | None = None,\n ) -> tuple[np.ndarray, list[dict[str, int]]]:\n \"\"\"\n Augment images with patch.\n\n :param x: Sample images.\n :param patch: The patch to be applied.\n :param random_location: If True apply patch at randomly shifted locations, otherwise place patch at origin\n (top-left corner).\n :param channels_first: Set channels first or last.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :param transforms: Patch transforms, requires `random_location=False`, and `mask=None`.\n :type mask: `np.ndarray`\n \"\"\"\n if transforms is not None:\n if random_location or mask is not None:\n raise ValueError(\n \"Definition of patch locations in `locations` requires `random_location=False`, and `mask=None`.\"\n )\n\n random_transformations = []\n x_copy = x.copy()\n patch_copy = patch.copy()\n\n if channels_first:\n x_copy = np.transpose(x_copy, (0, 2, 3, 1))\n patch_copy = np.transpose(patch_copy, (1, 2, 0))\n\n for i_image in range(x.shape[0]):\n\n if transforms is None:\n\n if random_location:\n if mask is None:\n i_x_1 = random.randint(0, x_copy.shape[1] - 1 - patch_copy.shape[0])\n i_y_1 = random.randint(0, x_copy.shape[2] - 1 - patch_copy.shape[1])\n else:\n\n if mask.shape[0] == 1:\n mask_2d = mask[0, :, :]\n else:\n mask_2d = mask[i_image, :, :]\n\n edge_x_0 = patch_copy.shape[0] // 2\n edge_x_1 = patch_copy.shape[0] - edge_x_0\n edge_y_0 = patch_copy.shape[1] // 2\n edge_y_1 = patch_copy.shape[1] - edge_y_0\n\n mask_2d[0:edge_x_0, :] = False\n mask_2d[-edge_x_1:, :] = False\n mask_2d[:, 0:edge_y_0] = False\n mask_2d[:, -edge_y_1:] = False\n\n num_pos = np.argwhere(mask_2d).shape[0]\n pos_id = np.random.choice(num_pos, size=1)\n pos = np.argwhere(mask_2d > 0)[pos_id[0]]\n i_x_1 = pos[0] - edge_x_0\n i_y_1 = pos[1] - edge_y_0\n\n else:\n i_x_1 = 0\n i_y_1 = 0\n\n i_x_2 = i_x_1 + patch_copy.shape[0]\n i_y_2 = i_y_1 + patch_copy.shape[1]\n\n random_transformations.append({\"i_x_1\": i_x_1, \"i_y_1\": i_y_1, \"i_x_2\": i_x_2, \"i_y_2\": i_y_2})\n\n else:\n i_x_1 = transforms[i_image][\"i_x_1\"]\n i_x_2 = transforms[i_image][\"i_x_2\"]\n i_y_1 = transforms[i_image][\"i_y_1\"]\n i_y_2 = transforms[i_image][\"i_y_2\"]\n\n x_copy[i_image, i_x_1:i_x_2, i_y_1:i_y_2, :] = patch_copy\n\n if channels_first:\n x_copy = np.transpose(x_copy, (0, 3, 1, 2))\n\n return x_copy, random_transformations\n\n def apply_patch(\n self,\n x: np.ndarray,\n patch_external: np.ndarray | None = None,\n random_location: bool = False,\n mask: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n Apply the adversarial patch to images.\n\n :param x: Images to be patched.\n :param patch_external: External patch to apply to images `x`. If None the attacks patch will be applied.\n :param random_location: True if patch location should be random.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :return: The patched images.\n \"\"\"\n if patch_external is not None:\n patch_local = patch_external\n else:\n patch_local = self._patch\n\n patched_images, _ = self._augment_images_with_patch(\n x=x,\n patch=patch_local,\n random_location=random_location,\n channels_first=self.estimator.channels_first,\n mask=mask,\n )\n\n return patched_images\n\n def _check_params(self) -> None:\n if not isinstance(self.patch_shape, (tuple, list)) or not all(isinstance(s, int) for s in self.patch_shape):\n raise ValueError(\"The patch shape must be either a tuple or list of integers.\")\n if len(self.patch_shape) != 3:\n raise ValueError(\"The length of patch shape must be 3.\")\n\n if not isinstance(self.learning_rate, float):\n raise ValueError(\"The learning rate must be of type float.\")\n if self.learning_rate <= 0.0:\n raise ValueError(\"The learning rate must be greater than 0.0.\")\n\n if not isinstance(self.max_iter, int):\n raise ValueError(\"The number of optimization steps must be of type int.\")\n if self.max_iter <= 0:\n raise ValueError(\"The number of optimization steps must be greater than 0.\")\n\n if not isinstance(self.batch_size, int):\n raise ValueError(\"The batch size must be of type int.\")\n if self.batch_size <= 0:\n raise ValueError(\"The batch size must be greater than 0.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/dpatch_robust.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a variation of the adversarial patch attack `DPatch` for object detectors.\nIt follows Lee & Kolter (2019) in using sign gradients with expectations over transformations.\nThe particular transformations supported in this implementation are cropping, rotations by multiples of 90 degrees,\nand changes in the brightness of the image.\n\n| Paper link (original DPatch): https://arxiv.org/abs/1806.02299v4\n| Paper link (physical-world patch from Lee & Kolter): https://arxiv.org/abs/1906.11897\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport math\nimport random\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\nfrom art import config\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n from art.utils import OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass RobustDPatch(EvasionAttack):\n \"\"\"\n Implementation of a particular variation of the DPatch attack.\n It follows Lee & Kolter (2019) in using sign gradients with expectations over transformations.\n The particular transformations supported in this implementation are cropping, rotations by multiples of 90 degrees,\n and changes in the brightness of the image.\n\n | Paper link (original DPatch): https://arxiv.org/abs/1806.02299v4\n | Paper link (physical-world patch from Lee & Kolter): https://arxiv.org/abs/1906.11897\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"patch_shape\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"patch_location\",\n \"crop_range\",\n \"brightness_range\",\n \"rotation_weights\",\n \"sample_size\",\n \"targeted\",\n \"summary_writer\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ObjectDetectorMixin)\n\n def __init__(\n self,\n estimator: \"OBJECT_DETECTOR_TYPE\",\n patch_shape: tuple[int, int, int] = (40, 40, 3),\n patch_location: tuple[int, int] = (0, 0),\n crop_range: tuple[int, int] = (0, 0),\n brightness_range: tuple[float, float] = (1.0, 1.0),\n rotation_weights: tuple[float, float, float, float] | tuple[int, int, int, int] = (1, 0, 0, 0),\n sample_size: int = 1,\n learning_rate: float = 5.0,\n max_iter: int = 500,\n batch_size: int = 16,\n targeted: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.RobustDPatch`.\n\n :param estimator: A trained object detector.\n :param patch_shape: The shape of the adversarial patch as a tuple of shape (height, width, nb_channels).\n :param patch_location: The location of the adversarial patch as a tuple of shape (upper left x, upper left y).\n :param crop_range: By how much the images may be cropped as a tuple of shape (height, width).\n :param brightness_range: Range for randomly adjusting the brightness of the image.\n :param rotation_weights: Sampling weights for random image rotations by (0, 90, 180, 270) degrees\n counter-clockwise.\n :param sample_size: Number of samples to be used in expectations over transformation.\n :param learning_rate: The learning rate of the optimization.\n :param max_iter: The number of optimization steps.\n :param batch_size: The size of the training batch.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n\n super().__init__(estimator=estimator, summary_writer=summary_writer)\n\n self.patch_shape = patch_shape\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.batch_size = batch_size\n if self.estimator.clip_values is None:\n self._patch = np.zeros(shape=patch_shape, dtype=config.ART_NUMPY_DTYPE)\n else:\n self._patch = (\n np.random.randint(0, 255, size=patch_shape)\n / 255\n * (self.estimator.clip_values[1] - self.estimator.clip_values[0])\n + self.estimator.clip_values[0]\n ).astype(config.ART_NUMPY_DTYPE)\n self.verbose = verbose\n self.patch_location = patch_location\n self.crop_range = crop_range\n self.brightness_range = brightness_range\n self.rotation_weights = rotation_weights\n self.sample_size = sample_size\n self._targeted = targeted\n self._check_params()\n\n def generate( # type: ignore\n self, x: np.ndarray, y: list[dict[str, np.ndarray]] | None = None, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Generate RobustDPatch.\n\n :param x: Sample images.\n :param y: Target labels for object detector.\n :return: Adversarial patch.\n \"\"\"\n channel_index = 1 if self.estimator.channels_first else x.ndim - 1\n if x.shape[channel_index] != self.patch_shape[channel_index - 1]:\n raise ValueError(\"The color channel index of the images and the patch have to be identical.\")\n if y is None and self.targeted:\n raise ValueError(\"The targeted version of RobustDPatch attack requires target labels provided to `y`.\")\n if y is not None and not self.targeted:\n raise ValueError(\"The untargeted version of RobustDPatch attack does not use True labels provided to 'y'.\")\n if x.ndim != 4: # pragma: no cover\n raise ValueError(\"The adversarial patch can only be applied to images.\")\n\n # Check whether patch fits into the cropped images:\n if self.estimator.channels_first:\n image_height, image_width = x.shape[2:4]\n else:\n image_height, image_width = x.shape[1:3]\n\n if not self.estimator.native_label_is_pytorch_format and y is not None:\n from art.estimators.object_detection.utils import convert_tf_to_pt\n\n y = convert_tf_to_pt(y=y, height=x.shape[1], width=x.shape[2])\n\n if y is not None:\n for i_image in range(x.shape[0]):\n y_i = y[i_image][\"boxes\"]\n for i_box in range(y_i.shape[0]):\n x_1, y_1, x_2, y_2 = y_i[i_box]\n if ( # pragma: no cover\n x_1 < self.crop_range[1]\n or y_1 < self.crop_range[0]\n or x_2 > image_width - self.crop_range[1] + 1\n or y_2 > image_height - self.crop_range[0] + 1\n ):\n raise ValueError(\"Cropping is intersecting with at least one box, reduce `crop_range`.\")\n\n if ( # pragma: no cover\n self.patch_location[0] + self.patch_shape[0] > image_height - self.crop_range[0]\n or self.patch_location[1] + self.patch_shape[1] > image_width - self.crop_range[1]\n ):\n raise ValueError(\"The patch (partially) lies outside the cropped image.\")\n\n for i_step in trange(self.max_iter, desc=\"RobustDPatch iteration\", disable=not self.verbose):\n if i_step == 0 or (i_step + 1) % 100 == 0:\n logger.info(\"Training Step: %i\", i_step + 1)\n\n num_batches = math.ceil(x.shape[0] / self.batch_size)\n patch_gradients_old = np.zeros_like(self._patch)\n\n for e_step in range(self.sample_size):\n if e_step == 0 or (e_step + 1) % 100 == 0:\n logger.info(\"EOT Step: %i\", e_step + 1)\n\n for i_batch in range(num_batches):\n i_batch_start = i_batch * self.batch_size\n i_batch_end = min((i_batch + 1) * self.batch_size, x.shape[0])\n\n if y is None:\n y_batch = y\n else:\n y_batch = y[i_batch_start:i_batch_end]\n\n # Sample and apply the random transformations:\n patched_images, patch_target, transforms = self._augment_images_with_patch(\n x[i_batch_start:i_batch_end], y_batch, self._patch, channels_first=self.estimator.channels_first\n )\n\n gradients = self.estimator.loss_gradient(\n x=patched_images,\n y=patch_target,\n standardise_output=True,\n )\n\n gradients = self._untransform_gradients(\n gradients, transforms, channels_first=self.estimator.channels_first\n )\n\n patch_gradients = patch_gradients_old + np.sum(gradients, axis=0)\n logger.debug(\n \"Gradient percentage diff: %f)\",\n np.mean(np.sign(patch_gradients) != np.sign(patch_gradients_old)),\n )\n\n patch_gradients_old = patch_gradients\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n x_patched, y_patched, _ = self._augment_images_with_patch(\n x, y, self._patch, channels_first=self.estimator.channels_first\n )\n\n self.summary_writer.update(\n batch_id=0,\n global_step=i_step,\n grad=np.expand_dims(patch_gradients, axis=0),\n patch=self._patch,\n estimator=self.estimator,\n x=x_patched,\n y=y_patched,\n targeted=self.targeted,\n )\n\n self._patch = self._patch + np.sign(patch_gradients) * (1 - 2 * int(self.targeted)) * self.learning_rate\n\n if self.estimator.clip_values is not None:\n self._patch = np.clip(\n self._patch,\n a_min=self.estimator.clip_values[0],\n a_max=self.estimator.clip_values[1],\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return self._patch\n\n def _augment_images_with_patch(\n self, x: np.ndarray, y: list[dict[str, np.ndarray]] | None, patch: np.ndarray, channels_first: bool\n ) -> tuple[np.ndarray, list[dict[str, np.ndarray]], dict[str, int | float]]:\n \"\"\"\n Augment images with patch.\n\n :param x: Sample images.\n :param y: Target labels.\n :param patch: The patch to be applied.\n :param channels_first: Set channels first or last.\n \"\"\"\n\n transformations: dict[str, float | int] = {}\n x_copy = x.copy()\n patch_copy = patch.copy()\n x_patch = x.copy()\n\n if channels_first:\n x_copy = np.transpose(x_copy, (0, 2, 3, 1))\n x_patch = np.transpose(x_patch, (0, 2, 3, 1))\n patch_copy = np.transpose(patch_copy, (1, 2, 0))\n\n # Apply patch:\n x_1, y_1 = self.patch_location\n x_2, y_2 = x_1 + patch_copy.shape[0], y_1 + patch_copy.shape[1]\n x_patch[:, x_1:x_2, y_1:y_2, :] = patch_copy\n\n # 1) crop images:\n crop_x = random.randint(0, self.crop_range[0])\n crop_y = random.randint(0, self.crop_range[1])\n x_1, y_1 = crop_x, crop_y\n x_2, y_2 = x_copy.shape[1] - crop_x + 1, x_copy.shape[2] - crop_y + 1\n x_copy = x_copy[:, x_1:x_2, y_1:y_2, :]\n x_patch = x_patch[:, x_1:x_2, y_1:y_2, :]\n\n transformations.update({\"crop_x\": crop_x, \"crop_y\": crop_y})\n\n # 2) rotate images:\n rot90 = random.choices([0, 1, 2, 3], weights=self.rotation_weights)[0]\n\n x_copy = np.rot90(x_copy, rot90, (1, 2))\n x_patch = np.rot90(x_patch, rot90, (1, 2))\n\n transformations.update({\"rot90\": rot90})\n\n if y is not None:\n\n y_copy: list[dict[str, np.ndarray]] = []\n\n for i_image in range(x_copy.shape[0]):\n y_b = y[i_image][\"boxes\"].copy()\n image_width = x.shape[2]\n image_height = x.shape[1]\n x_1_arr = y_b[:, 0]\n y_1_arr = y_b[:, 1]\n x_2_arr = y_b[:, 2]\n y_2_arr = y_b[:, 3]\n box_width = x_2_arr - x_1_arr\n box_height = y_2_arr - y_1_arr\n\n if rot90 == 0:\n x_1_new = x_1_arr\n y_1_new = y_1_arr\n x_2_new = x_2_arr\n y_2_new = y_2_arr\n\n if rot90 == 1:\n x_1_new = y_1_arr\n y_1_new = image_width - x_1_arr - box_width\n x_2_new = y_1_arr + box_height\n y_2_new = image_width - x_1_arr\n\n if rot90 == 2:\n x_1_new = image_width - x_2_arr\n y_1_new = image_height - y_2_arr\n x_2_new = x_1_new + box_width\n y_2_new = y_1_new + box_height\n\n if rot90 == 3:\n x_1_new = image_height - y_1_arr - box_height\n y_1_new = x_1_arr\n x_2_new = image_height - y_1_arr\n y_2_new = x_1_arr + box_width\n\n y_i = {}\n y_i[\"boxes\"] = np.zeros_like(y[i_image][\"boxes\"])\n y_i[\"boxes\"][:, 0] = x_1_new\n y_i[\"boxes\"][:, 1] = y_1_new\n y_i[\"boxes\"][:, 2] = x_2_new\n y_i[\"boxes\"][:, 3] = y_2_new\n\n y_i[\"labels\"] = y[i_image][\"labels\"]\n y_i[\"scores\"] = y[i_image][\"scores\"]\n\n y_copy.append(y_i)\n\n # 3) adjust brightness:\n brightness = random.uniform(*self.brightness_range)\n x_copy = np.round(brightness * x_copy / self.learning_rate) * self.learning_rate\n x_patch = np.round(brightness * x_patch / self.learning_rate) * self.learning_rate\n\n transformations.update({\"brightness\": brightness})\n\n logger.debug(\"Transformations: %s\", str(transformations))\n\n patch_target: list[dict[str, np.ndarray]] = []\n\n if self.targeted:\n predictions = y_copy\n else:\n if channels_first:\n x_copy = np.transpose(x_copy, (0, 3, 1, 2))\n predictions = self.estimator.predict(x=x_copy, standardise_output=True)\n\n for i_image in range(x_copy.shape[0]):\n target_dict = {}\n target_dict[\"boxes\"] = predictions[i_image][\"boxes\"]\n target_dict[\"labels\"] = predictions[i_image][\"labels\"]\n target_dict[\"scores\"] = predictions[i_image][\"scores\"]\n\n patch_target.append(target_dict)\n\n if channels_first:\n x_patch = np.transpose(x_patch, (0, 3, 1, 2))\n\n return x_patch, patch_target, transformations\n\n def _untransform_gradients(\n self,\n gradients: np.ndarray,\n transforms: dict[str, int | float],\n channels_first: bool,\n ) -> np.ndarray:\n \"\"\"\n Revert transformation on gradients.\n\n :param gradients: The gradients to be reverse transformed.\n :param transforms: The transformations in forward direction.\n :param channels_first: Set channels first or last.\n \"\"\"\n\n if channels_first:\n gradients = np.transpose(gradients, (0, 2, 3, 1))\n\n # Account for brightness adjustment:\n gradients = transforms[\"brightness\"] * gradients\n\n # Undo rotations:\n rot90 = int((4 - transforms[\"rot90\"]) % 4)\n gradients = np.rot90(gradients, k=rot90, axes=(1, 2))\n\n # Account for cropping when considering the upper left point of the patch:\n x_1 = self.patch_location[0] - int(transforms[\"crop_x\"])\n y_1 = self.patch_location[1] - int(transforms[\"crop_y\"])\n if channels_first:\n x_2 = x_1 + self.patch_shape[1]\n y_2 = y_1 + self.patch_shape[2]\n else:\n x_2 = x_1 + self.patch_shape[0]\n y_2 = y_1 + self.patch_shape[1]\n gradients = gradients[:, x_1:x_2, y_1:y_2, :]\n\n if channels_first:\n gradients = np.transpose(gradients, (0, 3, 1, 2))\n\n return gradients\n\n def apply_patch(self, x: np.ndarray, patch_external: np.ndarray | None = None) -> np.ndarray:\n \"\"\"\n Apply the adversarial patch to images.\n\n :param x: Images to be patched.\n :param patch_external: External patch to apply to images `x`. If None the attacks patch will be applied.\n :return: The patched images.\n \"\"\"\n\n x_patch = x.copy()\n\n if patch_external is not None:\n patch_local = patch_external.copy()\n else:\n patch_local = self._patch.copy()\n\n if self.estimator.channels_first:\n x_patch = np.transpose(x_patch, (0, 2, 3, 1))\n patch_local = np.transpose(patch_local, (1, 2, 0))\n\n # Apply patch:\n x_1, y_1 = self.patch_location\n x_2, y_2 = x_1 + patch_local.shape[0], y_1 + patch_local.shape[1]\n\n if x_2 > x_patch.shape[1] or y_2 > x_patch.shape[2]: # pragma: no cover\n raise ValueError(\"The patch (partially) lies outside the image.\")\n\n x_patch[:, x_1:x_2, y_1:y_2, :] = patch_local\n\n if self.estimator.channels_first:\n x_patch = np.transpose(x_patch, (0, 3, 1, 2))\n\n return x_patch\n\n def _check_params(self) -> None:\n if not isinstance(self.patch_shape, (tuple, list)) or not all(isinstance(s, int) for s in self.patch_shape):\n raise ValueError(\"The patch shape must be either a tuple or list of integers.\")\n if len(self.patch_shape) != 3:\n raise ValueError(\"The length of patch shape must be 3.\")\n\n if not isinstance(self.learning_rate, float):\n raise ValueError(\"The learning rate must be of type float.\")\n if self.learning_rate <= 0.0:\n raise ValueError(\"The learning rate must be greater than 0.0.\")\n\n if not isinstance(self.max_iter, int):\n raise ValueError(\"The number of optimization steps must be of type int.\")\n if self.max_iter <= 0:\n raise ValueError(\"The number of optimization steps must be greater than 0.\")\n\n if not isinstance(self.batch_size, int):\n raise ValueError(\"The batch size must be of type int.\")\n if self.batch_size <= 0:\n raise ValueError(\"The batch size must be greater than 0.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n if not isinstance(self.patch_location, (tuple, list)) or not all(\n isinstance(s, int) for s in self.patch_location\n ):\n raise ValueError(\"The patch location must be either a tuple or list of integers.\")\n if len(self.patch_location) != 2:\n raise ValueError(\"The length of patch location must be 2.\")\n\n if not isinstance(self.crop_range, (tuple, list)) or not all(isinstance(s, int) for s in self.crop_range):\n raise ValueError(\"The crop range must be either a tuple or list of integers.\")\n if len(self.crop_range) != 2:\n raise ValueError(\"The length of crop range must be 2.\")\n\n if self.crop_range[0] > self.crop_range[1]:\n raise ValueError(\"The first element of the crop range must be less or equal to the second one.\")\n\n if self.patch_location[0] < self.crop_range[0] or self.patch_location[1] < self.crop_range[1]:\n raise ValueError(\"The patch location must be outside the crop range.\")\n\n if not isinstance(self.brightness_range, (tuple, list)) or not all(\n isinstance(s, float) for s in self.brightness_range\n ):\n raise ValueError(\"The brightness range must be either a tuple or list of floats.\")\n if len(self.brightness_range) != 2:\n raise ValueError(\"The length of brightness range must be 2.\")\n\n if self.brightness_range[0] < 0.0:\n raise ValueError(\"The brightness range must be >= 0.0.\")\n\n if self.brightness_range[0] > self.brightness_range[1]:\n raise ValueError(\"The first element of the brightness range must be less or equal to the second one.\")\n\n if not isinstance(self.rotation_weights, (tuple, list)) or not all(\n isinstance(s, (float, int)) for s in self.rotation_weights\n ):\n raise ValueError(\"The rotation sampling weights must be provided as tuple or list of float or int values.\")\n if len(self.rotation_weights) != 4:\n raise ValueError(\"The number of rotation sampling weights must be 4.\")\n\n if not all(s >= 0.0 for s in self.rotation_weights):\n raise ValueError(\"The rotation sampling weights must be non-negative.\")\n\n if all(s == 0.0 for s in self.rotation_weights):\n raise ValueError(\"At least one of the rotation sampling weights must be strictly greater than zero.\")\n\n if not isinstance(self.sample_size, int):\n raise ValueError(\"The EOT sample size must be of type int.\")\n if self.sample_size <= 0:\n raise ValueError(\"The EOT sample size must be greater than 0.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The argument `targeted` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/elastic_net.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the elastic net attack `ElasticNet`. This is a white-box attack.\n\n| Paper link: https://arxiv.org/abs/1709.04114\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport six\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.utils import (\n compute_success,\n get_labels_np_array,\n check_and_transform_label_format,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ElasticNet(EvasionAttack):\n \"\"\"\n The elastic net attack of Pin-Yu Chen et al. (2018).\n\n | Paper link: https://arxiv.org/abs/1709.04114\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"confidence\",\n \"targeted\",\n \"learning_rate\",\n \"max_iter\",\n \"beta\",\n \"binary_search_steps\",\n \"initial_const\",\n \"batch_size\",\n \"decision_rule\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n confidence: float = 0.0,\n targeted: bool = False,\n learning_rate: float = 1e-2,\n binary_search_steps: int = 9,\n max_iter: int = 100,\n beta: float = 1e-3,\n initial_const: float = 1e-3,\n batch_size: int = 1,\n decision_rule: str = \"EN\",\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create an ElasticNet attack instance.\n\n :param classifier: A trained classifier.\n :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther\n away, from the original input, but classified with higher confidence as the target class.\n :param targeted: Should the attack target one specific class.\n :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better\n results but are slower to converge.\n :param binary_search_steps: Number of times to adjust constant with binary search (positive value).\n :param max_iter: The maximum number of iterations.\n :param beta: Hyperparameter trading off L2 minimization for L1 minimization.\n :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance\n and confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in\n Carlini and Wagner (2016).\n :param batch_size: Internal size of batches on which adversarial samples are generated.\n :param decision_rule: Decision rule. 'EN' means Elastic Net rule, 'L1' means L1 rule, 'L2' means L2 rule.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.confidence = confidence\n self._targeted = targeted\n self.learning_rate = learning_rate\n self.binary_search_steps = binary_search_steps\n self.max_iter = max_iter\n self.beta = beta\n self.initial_const = initial_const\n self.batch_size = batch_size\n self.decision_rule = decision_rule\n self.verbose = verbose\n self._check_params()\n\n def _loss(self, x: np.ndarray, x_adv: np.ndarray) -> tuple:\n \"\"\"\n Compute the loss function values.\n\n :param x: An array with the original input.\n :param x_adv: An array with the adversarial input.\n :return: A tuple of shape `(np.ndarray, float, float, float)` holding the current predictions, l1 distance,\n l2 distance and elastic net loss.\n \"\"\"\n l1dist = np.sum(np.abs(x - x_adv).reshape(x.shape[0], -1), axis=1)\n l2dist = np.sum(np.square(x - x_adv).reshape(x.shape[0], -1), axis=1)\n endist = self.beta * l1dist + l2dist\n predictions = self.estimator.predict(np.array(x_adv, dtype=ART_NUMPY_DTYPE), batch_size=self.batch_size)\n\n return np.argmax(predictions, axis=1), l1dist, l2dist, endist\n\n def _gradient_of_loss(\n self,\n target: np.ndarray,\n x: np.ndarray,\n x_adv: np.ndarray,\n c_weight: np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function.\n\n :param target: An array with the target class (one-hot encoded).\n :param x: An array with the original input.\n :param x_adv: An array with the adversarial input.\n :param c_weight: Weight of the loss term aiming for classification as target.\n :return: An array with the gradient of the loss function.\n \"\"\"\n # Compute the current predictions\n predictions = self.estimator.predict(np.array(x_adv, dtype=ART_NUMPY_DTYPE), batch_size=self.batch_size)\n\n if self.targeted:\n i_sub = np.argmax(target, axis=1)\n i_add = np.argmax(\n predictions * (1 - target) + (np.min(predictions, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n else:\n i_add = np.argmax(target, axis=1)\n i_sub = np.argmax(\n predictions * (1 - target) + (np.min(predictions, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n\n loss_gradient = self.estimator.class_gradient(x_adv, label=i_add)\n loss_gradient -= self.estimator.class_gradient(x_adv, label=i_sub)\n loss_gradient = loss_gradient.reshape(x.shape)\n\n c_mult = c_weight\n for _ in range(len(x.shape) - 1):\n c_mult = c_mult[:, np.newaxis]\n\n loss_gradient *= c_mult\n loss_gradient += 2 * (x_adv - x)\n\n # Set gradients where loss is constant to zero\n cond = (\n predictions[np.arange(x.shape[0]), i_add] - predictions[np.arange(x.shape[0]), i_sub] + self.confidence\n ) < 0\n loss_gradient[cond] = 0.0\n\n return loss_gradient\n\n def _decay_learning_rate(self, global_step: int, end_learning_rate: float, decay_steps: int) -> float:\n \"\"\"\n Applies a square-root decay to the learning rate.\n\n :param global_step: Global step to use for the decay computation.\n :param end_learning_rate: The minimal end learning rate.\n :param decay_steps: Number of decayed steps.\n :return: The decayed learning rate\n \"\"\"\n learn_rate = self.learning_rate - end_learning_rate\n decayed_learning_rate = learn_rate * (1 - global_step / decay_steps) ** 0.5 + end_learning_rate\n\n return decayed_learning_rate\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y` represents the target labels. Otherwise, the\n targets are the original class labels.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n # Assert that, if attack is targeted, y is provided:\n if self.targeted and y is None: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # No labels provided, use model prediction as correct class\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Compute adversarial examples with implicit batching\n nb_batches = int(np.ceil(x_adv.shape[0] / float(self.batch_size)))\n for batch_id in trange(nb_batches, desc=\"EAD\", disable=not self.verbose):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_batch = x_adv[batch_index_1:batch_index_2]\n y_batch = y[batch_index_1:batch_index_2]\n x_adv[batch_index_1:batch_index_2] = self._generate_batch(x_batch, y_batch)\n\n # Apply clip\n if self.estimator.clip_values is not None:\n x_adv = np.clip(x_adv, self.estimator.clip_values[0], self.estimator.clip_values[1])\n\n # Compute success rate of the EAD attack\n logger.info(\n \"Success rate of EAD attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n return x_adv\n\n def _generate_batch(self, x_batch: np.ndarray, y_batch: np.ndarray) -> np.ndarray:\n \"\"\"\n Run the attack on a batch of images and labels.\n\n :param x_batch: A batch of original examples.\n :param y_batch: A batch of targets (0-1 hot).\n :return: A batch of adversarial examples.\n \"\"\"\n # Initialize binary search:\n c_current = self.initial_const * np.ones(x_batch.shape[0])\n c_lower_bound = np.zeros(x_batch.shape[0])\n c_upper_bound = 10e10 * np.ones(x_batch.shape[0])\n\n # Initialize the best distortions and best attacks globally\n o_best_dist = np.inf * np.ones(x_batch.shape[0])\n o_best_attack = x_batch.copy()\n\n # Start with a binary search\n for bss in range(self.binary_search_steps):\n logger.debug(\n \"Binary search step %i out of %i (c_mean==%f)\",\n bss,\n self.binary_search_steps,\n np.mean(c_current),\n )\n\n # Run with 1 specific binary search step\n best_dist, best_label, best_attack = self._generate_bss(x_batch, y_batch, c_current)\n\n # Update best results so far\n o_best_attack[best_dist < o_best_dist] = best_attack[best_dist < o_best_dist]\n o_best_dist[best_dist < o_best_dist] = best_dist[best_dist < o_best_dist]\n\n # Adjust the constant as needed\n c_current, c_lower_bound, c_upper_bound = self._update_const(\n y_batch, best_label, c_current, c_lower_bound, c_upper_bound\n )\n\n return o_best_attack\n\n def _update_const(\n self,\n y_batch: np.ndarray,\n best_label: np.ndarray,\n c_batch: np.ndarray,\n c_lower_bound: np.ndarray,\n c_upper_bound: np.ndarray,\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Update constants.\n\n :param y_batch: A batch of targets (0-1 hot).\n :param best_label: A batch of best labels.\n :param c_batch: A batch of constants.\n :param c_lower_bound: A batch of lower bound constants.\n :param c_upper_bound: A batch of upper bound constants.\n :return: A tuple of three batches of updated constants and lower/upper bounds.\n \"\"\"\n\n def compare(o_1, o_2):\n if self.targeted:\n return o_1 == o_2\n return o_1 != o_2\n\n for i in range(c_batch.shape[0]):\n if compare(best_label[i], np.argmax(y_batch[i])) and best_label[i] != -np.inf:\n # Successful attack\n c_upper_bound[i] = min(c_upper_bound[i], c_batch[i])\n if c_upper_bound[i] < 1e9:\n c_batch[i] = (c_lower_bound[i] + c_upper_bound[i]) / 2.0\n\n else:\n # Failure attack\n c_lower_bound[i] = max(c_lower_bound[i], c_batch[i])\n if c_upper_bound[i] < 1e9:\n c_batch[i] = (c_lower_bound[i] + c_upper_bound[i]) / 2.0\n else:\n c_batch[i] *= 10\n\n return c_batch, c_lower_bound, c_upper_bound\n\n def _generate_bss(self, x_batch: np.ndarray, y_batch: np.ndarray, c_batch: np.ndarray) -> tuple:\n \"\"\"\n Generate adversarial examples for a batch of inputs with a specific batch of constants.\n\n :param x_batch: A batch of original examples.\n :param y_batch: A batch of targets (0-1 hot).\n :param c_batch: A batch of constants.\n :return: A tuple of the best elastic distances, best labels, best attacks\n \"\"\"\n\n def compare(o_1, o_2):\n if self.targeted:\n return o_1 == o_2\n return o_1 != o_2\n\n # Initialize the best distortions and best changed labels and best attacks\n best_dist = np.inf * np.ones(x_batch.shape[0])\n best_label = [-np.inf] * x_batch.shape[0]\n best_attack = x_batch.copy()\n\n # Implement the algorithm 1 in the EAD paper\n x_adv = x_batch.copy()\n y_adv = x_batch.copy()\n for i_iter in range(self.max_iter):\n logger.debug(\"Iteration step %i out of %i\", i_iter, self.max_iter)\n\n # Update learning rate\n learning_rate = self._decay_learning_rate(\n global_step=i_iter, end_learning_rate=0, decay_steps=self.max_iter\n )\n\n # Compute adversarial examples\n grad = self._gradient_of_loss(target=y_batch, x=x_batch, x_adv=y_adv, c_weight=c_batch)\n x_adv_next = self._shrinkage_threshold(y_adv - learning_rate * grad, x_batch, self.beta)\n y_adv = x_adv_next + (1.0 * i_iter / (i_iter + 3)) * (x_adv_next - x_adv)\n x_adv = x_adv_next\n\n # Adjust the best result\n (logits, l1dist, l2dist, endist) = self._loss(x=x_batch, x_adv=x_adv)\n\n if self.decision_rule == \"EN\":\n zip_set = zip(endist, logits)\n elif self.decision_rule == \"L1\":\n zip_set = zip(l1dist, logits)\n elif self.decision_rule == \"L2\":\n zip_set = zip(l2dist, logits)\n else: # pragma: no cover\n raise ValueError(\"The decision rule only supports `EN`, `L1`, `L2`.\")\n\n for j, (distance, label) in enumerate(zip_set):\n if distance < best_dist[j] and compare(label, np.argmax(y_batch[j])):\n best_dist[j] = distance\n best_attack[j] = x_adv[j]\n best_label[j] = label\n\n return best_dist, best_label, best_attack\n\n @staticmethod\n def _shrinkage_threshold(z_batch: np.ndarray, x_batch: np.ndarray, beta: float) -> np.ndarray:\n \"\"\"\n Implement the element-wise projected shrinkage-threshold function.\n\n :param z_batch: A batch of examples.\n :param x_batch: A batch of original examples.\n :param beta: The shrink parameter.\n :return: A shrinked version of z.\n \"\"\"\n cond1 = (z_batch - x_batch) > beta\n cond2 = np.abs(z_batch - x_batch) <= beta\n cond3 = (z_batch - x_batch) < -beta\n\n upper = np.minimum(z_batch - beta, 1.0)\n lower = np.maximum(z_batch + beta, 0.0)\n result = cond1 * upper + cond2 * x_batch + cond3 * lower\n\n return result\n\n def _check_params(self) -> None:\n if not isinstance(self.binary_search_steps, int) or self.binary_search_steps < 0:\n raise ValueError(\"The number of binary search steps must be a non-negative integer.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size < 1:\n raise ValueError(\"The batch size must be an integer greater than zero.\")\n\n if not isinstance(self.decision_rule, six.string_types) or self.decision_rule not in [\"EN\", \"L1\", \"L2\"]:\n raise ValueError(\"The decision rule only supports `EN`, `L1`, `L2`.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/fast_gradient.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Fast Gradient Method attack. This implementation includes the original Fast Gradient Sign\nMethod attack and extends it to other norms, therefore it is called the Fast Gradient Method.\n\n| Paper link: https://arxiv.org/abs/1412.6572\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import (\n compute_success,\n get_labels_np_array,\n random_sphere,\n projection,\n check_and_transform_label_format,\n)\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass FastGradientMethod(EvasionAttack):\n \"\"\"\n This attack was originally implemented by Goodfellow et al. (2015) with the infinity norm (and is known as the \"Fast\n Gradient Sign Method\"). This implementation extends the attack to other norms, and is therefore called the Fast\n Gradient Method.\n\n | Paper link: https://arxiv.org/abs/1412.6572\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"targeted\",\n \"num_random_init\",\n \"batch_size\",\n \"minimal\",\n \"summary_writer\",\n ]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 32,\n minimal: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n ) -> None:\n \"\"\"\n Create a :class:`.FastGradientMethod` instance.\n\n :param estimator: A trained classifier.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", `np.inf` or a real `p >= 1`.\n :param eps: Attack step size (input variation).\n :param eps_step: Step size of input variation for minimal perturbation computation.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False)\n :param num_random_init: Number of random initialisations within the epsilon ball. For random_init=0 starting at\n the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param minimal: Indicates if computing the minimal perturbation (True). If True, also define `eps_step` for\n the step size and eps for the maximum perturbation.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n \"\"\"\n super().__init__(estimator=estimator, summary_writer=summary_writer)\n self.norm = norm\n self.eps = eps\n self.eps_step = eps_step\n self._targeted = targeted\n self.num_random_init = num_random_init\n self.batch_size = batch_size\n self.minimal = minimal\n self._project = True\n FastGradientMethod._check_params(self)\n\n self._batch_id = 0\n self._i_max_iter = 0\n\n def _check_compatibility_input_and_eps(self, x: np.ndarray):\n \"\"\"\n Check the compatibility of the input with `eps` and `eps_step` which are of the same shape.\n\n :param x: An array with the original inputs.\n \"\"\"\n if isinstance(self.eps, np.ndarray):\n # Ensure the eps array is broadcastable\n if self.eps.ndim > x.ndim: # pragma: no cover\n raise ValueError(\"The `eps` shape must be broadcastable to input shape.\")\n\n def _minimal_perturbation(self, x: np.ndarray, y: np.ndarray, mask: np.ndarray | None) -> np.ndarray:\n \"\"\"\n Iteratively compute the minimal perturbation necessary to make the class prediction change. Stop when the\n first adversarial example was found.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :return: An array holding the adversarial examples.\n \"\"\"\n adv_x = x.copy()\n\n # Compute perturbation with implicit batching\n for batch_id in range(int(np.ceil(adv_x.shape[0] / float(self.batch_size)))):\n batch_index_1, batch_index_2 = (\n batch_id * self.batch_size,\n (batch_id + 1) * self.batch_size,\n )\n batch = adv_x[batch_index_1:batch_index_2]\n batch_labels = y[batch_index_1:batch_index_2]\n\n mask_batch = mask\n if mask is not None:\n # Here we need to make a distinction: if the masks are different for each input, we need to index\n # those for the current batch. Otherwise, (i.e. mask is meant to be broadcasted), keep it as it is.\n if len(mask.shape) == len(x.shape):\n mask_batch = mask[batch_index_1:batch_index_2]\n\n # Get perturbation\n perturbation = self._compute_perturbation(batch, batch_labels, mask_batch)\n\n # Get current predictions\n active_indices = np.arange(len(batch))\n\n current_eps: int | float | np.ndarray\n partial_stop_condition: bool | np.ndarray\n\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if len(self.eps.shape) == len(x.shape) and self.eps.shape[0] == x.shape[0]:\n current_eps = self.eps_step[batch_index_1:batch_index_2]\n partial_stop_condition = bool((current_eps <= self.eps[batch_index_1:batch_index_2]).all())\n\n else:\n current_eps = self.eps_step\n partial_stop_condition = bool((current_eps <= self.eps).all())\n\n else:\n current_eps = self.eps_step\n partial_stop_condition = current_eps <= self.eps\n\n while active_indices.size > 0 and partial_stop_condition:\n # Adversarial crafting\n current_x = self._apply_perturbation(x[batch_index_1:batch_index_2], perturbation, current_eps)\n\n # Update\n batch[active_indices] = current_x[active_indices]\n adv_preds = self.estimator.predict(batch)\n\n # If targeted active check to see whether we have hit the target, otherwise head to anything but\n if self.targeted:\n active_indices = np.where(np.argmax(batch_labels, axis=1) != np.argmax(adv_preds, axis=1))[0]\n else:\n active_indices = np.where(np.argmax(batch_labels, axis=1) == np.argmax(adv_preds, axis=1))[0]\n\n # Update current eps and check the stop condition\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if len(self.eps.shape) == len(x.shape) and self.eps.shape[0] == x.shape[0]:\n current_eps = current_eps + self.eps_step[batch_index_1:batch_index_2]\n partial_stop_condition = bool((current_eps <= self.eps[batch_index_1:batch_index_2]).all())\n\n else:\n current_eps = current_eps + self.eps_step\n partial_stop_condition = bool((current_eps <= self.eps).all())\n\n else:\n current_eps = current_eps + self.eps_step\n partial_stop_condition = current_eps <= self.eps\n\n adv_x[batch_index_1:batch_index_2] = batch\n\n return adv_x\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = self._get_mask(x, **kwargs)\n\n # Ensure eps is broadcastable\n self._check_compatibility_input_and_eps(x=x)\n\n if isinstance(self.estimator, ClassifierMixin):\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n logger.info(\"Using model predictions as correct labels for FGM.\")\n y_array = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)) # type: ignore\n else:\n y_array = y\n\n if self.estimator.nb_classes > 2:\n y_array = y_array / np.sum(y_array, axis=1, keepdims=True)\n\n # Return adversarial examples computed with minimal perturbation if option is active\n adv_x_best = x\n if self.minimal:\n logger.info(\"Performing minimal perturbation FGM.\")\n adv_x_best = self._minimal_perturbation(x, y_array, mask)\n rate_best = 100 * compute_success(\n self.estimator, # type: ignore\n x,\n y_array,\n adv_x_best,\n self.targeted,\n batch_size=self.batch_size, # type: ignore\n )\n else:\n rate_best = 0.0\n for _ in range(max(1, self.num_random_init)):\n adv_x = self._compute(\n x,\n x,\n y_array,\n mask,\n self.eps,\n self.eps,\n self._project,\n self.num_random_init > 0,\n )\n\n if self.num_random_init > 1:\n rate = 100 * compute_success(\n self.estimator, # type: ignore\n x,\n y_array,\n adv_x,\n self.targeted,\n batch_size=self.batch_size, # type: ignore\n )\n if rate > rate_best:\n rate_best = rate\n adv_x_best = adv_x\n else:\n adv_x_best = adv_x\n\n logger.info(\n \"Success rate of FGM attack: %.2f%%\",\n (\n rate_best\n if rate_best is not None\n else 100\n * compute_success(\n self.estimator, # type: ignore\n x,\n y_array,\n adv_x_best,\n self.targeted,\n batch_size=self.batch_size,\n )\n ),\n )\n\n else:\n if self.minimal: # pragma: no cover\n raise ValueError(\"Minimal perturbation is only supported for classification.\")\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n logger.info(\"Using model predictions as correct labels for FGM.\")\n y_array = self.estimator.predict(x, batch_size=self.batch_size)\n else:\n y_array = y\n\n adv_x_best = self._compute(\n x,\n x,\n y_array,\n None,\n self.eps,\n self.eps,\n self._project,\n self.num_random_init > 0,\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return adv_x_best\n\n def _check_params(self) -> None:\n\n norm: float = np.inf if self.norm == \"inf\" else float(self.norm)\n if norm < 1:\n raise ValueError('Norm order must be either \"inf\", `np.inf` or a real `p >= 1`.')\n\n if not (\n isinstance(self.eps, (int, float))\n and isinstance(self.eps_step, (int, float))\n or isinstance(self.eps, np.ndarray)\n and isinstance(self.eps_step, np.ndarray)\n ):\n raise TypeError(\n \"The perturbation size `eps` and the perturbation step-size `eps_step` must have the same type of `int`\"\n \", `float`, or `np.ndarray`.\"\n )\n\n if isinstance(self.eps, (int, float)):\n if self.eps < 0:\n raise ValueError(\"The perturbation size `eps` has to be nonnegative.\")\n else:\n if (self.eps < 0).any():\n raise ValueError(\"The perturbation size `eps` has to be nonnegative.\")\n\n if isinstance(self.eps_step, (int, float)):\n if self.eps_step <= 0:\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n else:\n if (self.eps_step <= 0).any():\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if self.eps.shape != self.eps_step.shape:\n raise ValueError(\n \"The perturbation size `eps` and the perturbation step-size `eps_step` must have the same shape.\"\n )\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The flag `targeted` has to be of type bool.\")\n\n if not isinstance(self.num_random_init, int):\n raise TypeError(\"The number of random initialisations has to be of type integer\")\n\n if self.num_random_init < 0:\n raise ValueError(\"The number of random initialisations `random_init` has to be greater than or equal to 0.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.minimal, bool):\n raise ValueError(\"The flag `minimal` has to be of type bool.\")\n\n def _compute_perturbation(\n self,\n x: np.ndarray,\n y: np.ndarray,\n mask: np.ndarray | None,\n decay: float | None = None,\n momentum: np.ndarray | None = None,\n ) -> np.ndarray:\n # Get gradient wrt loss; invert it if attack is targeted\n grad = self.estimator.loss_gradient(x, y) * (1 - 2 * int(self.targeted))\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n self.summary_writer.update(\n batch_id=self._batch_id,\n global_step=self._i_max_iter,\n grad=grad,\n patch=None,\n estimator=self.estimator,\n x=x,\n y=y,\n targeted=self.targeted,\n )\n\n # Check for NaN before normalisation and replace with 0\n if grad.dtype != object and np.isnan(grad).any(): # pragma: no cover\n logger.warning(\"Elements of the loss gradient are NaN and have been replaced with 0.0.\")\n grad = np.where(np.isnan(grad), 0.0, grad)\n else:\n for i, _ in enumerate(grad):\n grad_i_array = grad[i].astype(np.float32)\n if np.isnan(grad_i_array).any():\n grad[i] = np.where(np.isnan(grad_i_array), 0.0, grad_i_array).astype(object)\n\n # Apply mask\n if mask is not None:\n grad = np.where(mask == 0.0, 0.0, grad)\n\n # Apply norm bound\n def _apply_norm(norm, grad, object_type=False):\n \"\"\"Returns an x maximizing subject to ||x||_norm<=1.\"\"\"\n if (grad.dtype != object and np.isinf(grad).any()) or np.isnan( # pragma: no cover\n grad.astype(np.float32)\n ).any():\n logger.info(\"The loss gradient array contains at least one positive or negative infinity.\")\n\n grad_2d = grad.reshape(1 if object_type else len(grad), -1)\n if norm in [np.inf, \"inf\"]:\n grad_2d = np.ones_like(grad_2d)\n elif norm == 1:\n i_max = np.argmax(np.abs(grad_2d), axis=1)\n grad_2d = np.zeros_like(grad_2d)\n grad_2d[range(len(grad_2d)), i_max] = 1\n elif norm > 1:\n conjugate = norm / (norm - 1)\n q_norm = np.linalg.norm(grad_2d, ord=conjugate, axis=1, keepdims=True)\n grad_2d = (np.abs(grad_2d) / np.where(q_norm, q_norm, np.inf)) ** (conjugate - 1)\n grad = grad_2d.reshape(grad.shape) * np.sign(grad)\n return grad\n\n # Compute gradient momentum\n if decay is not None and momentum is not None:\n if x.dtype == object:\n raise NotImplementedError(\"Momentum Iterative Method not yet implemented for object type input.\")\n # Update momentum in-place (important).\n # The L1 normalization for accumulation is an arbitrary choice of the paper.\n grad_2d = grad.reshape(len(grad), -1)\n norm1 = np.linalg.norm(grad_2d, ord=1, axis=1, keepdims=True)\n normalized_grad = (grad_2d / np.where(norm1, norm1, np.inf)).reshape(grad.shape)\n momentum *= decay\n momentum += normalized_grad\n # Use the momentum to compute the perturbation, instead of the gradient\n grad = momentum\n\n if x.dtype == object:\n for i_sample in range(x.shape[0]):\n grad[i_sample] = _apply_norm(self.norm, grad[i_sample], object_type=True)\n assert x[i_sample].shape == grad[i_sample].shape\n else:\n grad = _apply_norm(self.norm, grad)\n\n assert x.shape == grad.shape\n\n return grad\n\n def _apply_perturbation(\n self, x: np.ndarray, perturbation: np.ndarray, eps_step: int | float | np.ndarray\n ) -> np.ndarray:\n\n perturbation_step = eps_step * perturbation\n if perturbation_step.dtype != object:\n perturbation_step[np.isnan(perturbation_step)] = 0\n else:\n for i, _ in enumerate(perturbation_step):\n perturbation_step_i_array = perturbation_step[i].astype(np.float32)\n if np.isnan(perturbation_step_i_array).any():\n perturbation_step[i] = np.where(\n np.isnan(perturbation_step_i_array), 0.0, perturbation_step_i_array\n ).astype(object)\n\n x = x + perturbation_step\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n if x.dtype == object:\n for i_obj in range(x.shape[0]):\n x[i_obj] = np.clip(x[i_obj], clip_min, clip_max)\n else:\n x = np.clip(x, clip_min, clip_max)\n\n return x\n\n def _compute(\n self,\n x: np.ndarray,\n x_init: np.ndarray,\n y: np.ndarray,\n mask: np.ndarray | None,\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n project: bool,\n random_init: bool,\n batch_id_ext: int | None = None,\n decay: float | None = None,\n momentum: np.ndarray | None = None,\n ) -> np.ndarray:\n if random_init:\n n = x.shape[0]\n m = np.prod(x.shape[1:]).item()\n random_perturbation = random_sphere(n, m, eps, self.norm).reshape(x.shape).astype(ART_NUMPY_DTYPE)\n if mask is not None:\n random_perturbation = random_perturbation * (mask.astype(ART_NUMPY_DTYPE))\n x_adv = x.astype(ART_NUMPY_DTYPE) + random_perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = np.clip(x_adv, clip_min, clip_max)\n else:\n if x.dtype == object:\n x_adv = x.copy()\n else:\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n # Compute perturbation with implicit batching\n for batch_id in range(int(np.ceil(x.shape[0] / float(self.batch_size)))):\n if batch_id_ext is None:\n self._batch_id = batch_id\n else:\n self._batch_id = batch_id_ext\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch_index_2 = min(batch_index_2, x.shape[0])\n batch = x_adv[batch_index_1:batch_index_2]\n batch_labels = y[batch_index_1:batch_index_2]\n\n mask_batch = mask\n if mask is not None:\n # Here we need to make a distinction: if the masks are different for each input, we need to index\n # those for the current batch. Otherwise, (i.e. mask is meant to be broadcasted), keep it as it is.\n if len(mask.shape) == len(x.shape):\n mask_batch = mask[batch_index_1:batch_index_2]\n\n # Get perturbation\n perturbation = self._compute_perturbation(batch, batch_labels, mask_batch, decay, momentum)\n\n batch_eps: int | float | np.ndarray\n batch_eps_step: int | float | np.ndarray\n\n # Compute batch_eps and batch_eps_step\n if isinstance(eps, np.ndarray) and isinstance(eps_step, np.ndarray):\n if len(eps.shape) == len(x.shape) and eps.shape[0] == x.shape[0]:\n batch_eps = eps[batch_index_1:batch_index_2]\n batch_eps_step = eps_step[batch_index_1:batch_index_2]\n\n else:\n batch_eps = eps\n batch_eps_step = eps_step\n\n else:\n batch_eps = eps\n batch_eps_step = eps_step\n\n # Apply perturbation and clip\n x_adv[batch_index_1:batch_index_2] = self._apply_perturbation(batch, perturbation, batch_eps_step)\n\n if project:\n if x_adv.dtype == object:\n for i_sample in range(batch_index_1, batch_index_2):\n if isinstance(batch_eps, np.ndarray) and batch_eps.shape[0] == x_adv.shape[0]:\n perturbation = projection(\n x_adv[i_sample] - x_init[i_sample], batch_eps[i_sample], self.norm\n )\n\n else:\n perturbation = projection(x_adv[i_sample] - x_init[i_sample], batch_eps, self.norm)\n\n x_adv[i_sample] = x_init[i_sample] + perturbation\n\n else:\n perturbation = projection(\n x_adv[batch_index_1:batch_index_2] - x_init[batch_index_1:batch_index_2], batch_eps, self.norm\n )\n x_adv[batch_index_1:batch_index_2] = x_init[batch_index_1:batch_index_2] + perturbation\n\n return x_adv\n\n @staticmethod\n def _get_mask(x: np.ndarray, **kwargs) -> np.ndarray | None:\n \"\"\"\n Get the mask from the kwargs.\n\n :param x: An array with the original inputs.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :type mask: `np.ndarray`\n :return: The mask.\n \"\"\"\n mask: np.ndarray | None = kwargs.get(\"mask\")\n\n if mask is not None:\n if mask.ndim > x.ndim: # pragma: no cover\n raise ValueError(\"Mask shape must be broadcastable to input shape.\")\n\n if not (np.issubdtype(mask.dtype, np.floating) or mask.dtype == bool): # pragma: no cover\n raise ValueError(\n f\"The `mask` has to be either of type np.float32, np.float64 or bool. The provided\"\n f\"`mask` is of type {mask.dtype}.\"\n )\n\n if np.issubdtype(mask.dtype, np.floating) and np.amin(mask) < 0.0: # pragma: no cover\n raise ValueError(\n \"The `mask` of type np.float32 or np.float64 requires all elements to be either zero\"\n \"or positive values.\"\n )\n\n return mask\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/frame_saliency.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the frame saliency attack framework. Originally designed for video data, this framework will\nprioritize which parts of a sequential input should be perturbed based on saliency scores.\n\n| Paper link: https://arxiv.org/abs/1811.11875\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import (\n compute_success_array,\n get_labels_np_array,\n check_and_transform_label_format,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass FrameSaliencyAttack(EvasionAttack):\n \"\"\"\n Implementation of the attack framework proposed by Inkawhich et al. (2018). Prioritizes the frame of a sequential\n input to be adversarially perturbed based on the saliency score of each frame.\n\n | Paper link: https://arxiv.org/abs/1811.11875\n \"\"\"\n\n method_list = [\"iterative_saliency\", \"iterative_saliency_refresh\", \"one_shot\"]\n attack_params = EvasionAttack.attack_params + [\n \"attacker\",\n \"method\",\n \"frame_index\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n attacker: EvasionAttack,\n method: str = \"iterative_saliency\",\n frame_index: int = 1,\n batch_size: int = 1,\n verbose: bool = True,\n ):\n \"\"\"\n :param classifier: A trained classifier.\n :param attacker: An adversarial evasion attacker which supports masking. Currently supported:\n ProjectedGradientDescent, BasicIterativeMethod, FastGradientMethod.\n :param method: Specifies which method to use: \"iterative_saliency\" (adds perturbation iteratively to frame\n with the highest saliency score until attack is successful), \"iterative_saliency_refresh\"\n (updates perturbation after each iteration), \"one_shot\" (adds all perturbations at once, i.e.\n defaults to original attack).\n :param frame_index: Index of the axis in input (feature) array `x` representing the frame dimension.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.attacker = attacker\n self.method = method\n self.frame_index = frame_index\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the adversarial examples.\n \"\"\"\n if len(x.shape) < 3: # pragma: no cover\n raise ValueError(\"Frame saliency attack works only on inputs of dimension greater than 2.\")\n\n if self.frame_index >= len(x.shape): # pragma: no cover\n raise ValueError(\"Frame index is out of bounds for the given input shape.\")\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if self.method == \"one_shot\":\n if y is None:\n return self.attacker.generate(x)\n\n return self.attacker.generate(x, y)\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if hasattr(self.attacker, \"targeted\") and self.attacker.targeted: # type: ignore # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n targets = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n else:\n targets = y\n\n if self.estimator.nb_classes == 2 and targets.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n nb_samples = x.shape[0]\n nb_frames = x.shape[self.frame_index]\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n # Determine for which adversarial examples the attack fails:\n attack_failure = self._compute_attack_failure_array(x, targets, x_adv)\n\n # Determine the order in which to perturb frames, based on saliency scores:\n frames_to_perturb = self._compute_frames_to_perturb(x_adv, targets)\n\n # Generate adversarial perturbations. If the method is \"iterative_saliency_refresh\", we will use a mask so that\n # only the next frame to be perturbed is considered in the attack; moreover we keep track of the next frames to\n # be perturbed, so they will not be perturbed again later on.\n mask = np.ones(x.shape)\n if self.method == \"iterative_saliency_refresh\":\n mask = np.zeros(x.shape)\n mask = np.swapaxes(mask, 1, self.frame_index)\n mask[:, frames_to_perturb[:, 0], ::] = 1\n mask = np.swapaxes(mask, 1, self.frame_index)\n disregard = np.zeros((nb_samples, nb_frames))\n disregard[:, frames_to_perturb[:, 0]] = np.inf\n\n x_adv_new = self.attacker.generate(x, targets, mask=mask)\n\n # Here starts the main iteration:\n for i in trange(nb_frames, desc=\"Frame saliency\", disable=not self.verbose):\n # Check if attack has already succeeded for all inputs:\n if sum(attack_failure) == 0:\n break\n\n # Update designated frames with adversarial perturbations:\n x_adv = np.swapaxes(x_adv, 1, self.frame_index)\n x_adv_new = np.swapaxes(x_adv_new, 1, self.frame_index)\n x_adv[attack_failure, frames_to_perturb[:, i][attack_failure], ::] = x_adv_new[\n attack_failure, frames_to_perturb[:, i][attack_failure], ::\n ]\n x_adv = np.swapaxes(x_adv, 1, self.frame_index)\n x_adv_new = np.swapaxes(x_adv_new, 1, self.frame_index)\n\n # Update for which adversarial examples the attack still fails:\n attack_failure = self._compute_attack_failure_array(x, targets, x_adv)\n\n # For the \"refresh\" method, update the next frames to be perturbed (disregarding the frames that were\n # perturbed already) and also refresh the adversarial perturbations:\n if self.method == \"iterative_saliency_refresh\" and i < nb_frames - 1:\n frames_to_perturb = self._compute_frames_to_perturb(x_adv, targets, disregard)\n mask = np.zeros(x.shape)\n mask = np.swapaxes(mask, 1, self.frame_index)\n mask[:, frames_to_perturb[:, i + 1], ::] = 1\n mask = np.swapaxes(mask, 1, self.frame_index)\n disregard[:, frames_to_perturb[:, i + 1]] = np.inf\n x_adv_new = self.attacker.generate(x_adv, targets, mask=mask)\n\n return x_adv\n\n def _compute_attack_failure_array(self, x: np.ndarray, targets: np.ndarray, x_adv: np.ndarray) -> np.ndarray:\n attack_success = compute_success_array(\n self.attacker.estimator, x, targets, x_adv, self.attacker.targeted # type: ignore\n )\n return np.invert(attack_success)\n\n def _compute_frames_to_perturb(\n self, x_adv: np.ndarray, targets: np.ndarray, disregard: np.ndarray | None = None\n ) -> np.ndarray:\n saliency_score = self.estimator.loss_gradient(x_adv, targets)\n saliency_score = np.swapaxes(saliency_score, 1, self.frame_index)\n saliency_score = saliency_score.reshape((saliency_score.shape[:2] + (np.prod(saliency_score.shape[2:]),)))\n saliency_score = np.mean(np.abs(saliency_score), axis=2)\n\n if disregard is not None:\n saliency_score += disregard\n\n return np.argsort(-saliency_score, axis=1)\n\n def _check_params(self) -> None:\n from art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n from art.attacks.evasion.iterative_method import BasicIterativeMethod\n from art.attacks.evasion.fast_gradient import FastGradientMethod\n\n if not isinstance(self.attacker, (ProjectedGradientDescent, BasicIterativeMethod, FastGradientMethod)):\n raise ValueError(\n \"The attacker must be either of class 'ProjectedGradientDescent', 'BasicIterativeMethod' or \"\n \"'FastGradientMethod'\"\n )\n\n if self.method not in self.method_list:\n raise ValueError(\"Method must be either 'iterative_saliency', 'iterative_saliency_refresh' or 'one_shot'.\")\n\n if self.frame_index < 1:\n raise ValueError(\"The index `frame_index` of the frame dimension has to be >=1.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not self.estimator == self.attacker.estimator:\n raise Warning(\"Different classifiers given for computation of saliency scores and adversarial noise.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/geometric_decision_based_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Geometric Decision-based Attack (GeoDA), a black-box attack requiring class predictions.\n\n| Paper link: https://arxiv.org/abs/2003.06468\n\"\"\"\nfrom __future__ import annotations\n\nimport os\nimport math\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass GeoDA(EvasionAttack):\n \"\"\"\n Implementation of the Geometric Decision-based Attack (GeoDA), a black-box attack requiring class predictions.\n Based on reference implementation: https://github.com/thisisalirah/GeoDA\n\n | Paper link: https://arxiv.org/abs/2003.06468\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"batch_size\",\n \"norm\",\n \"sub_dim\",\n \"max_iter\",\n \"bin_search_tol\",\n \"lambda_param\",\n \"sigma\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\",\n batch_size: int = 64,\n norm: int | float | str = 2,\n sub_dim: int = 10,\n max_iter: int = 4000,\n bin_search_tol: float = 0.1,\n lambda_param: float = 0.6,\n sigma: float = 0.0002,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a Geometric Decision-based Attack instance.\n\n :param estimator: A trained classifier.\n :param batch_size: The size of the batch used by the estimator during inference.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param sub_dim: Dimensionality of 2D frequency space (DCT).\n :param max_iter: Maximum number of iterations.\n :param bin_search_tol: Maximum remaining L2 perturbation defining binary search convergence. Input images are\n normalised by maximal estimator.clip_value[1] if available or maximal value in the input\n image.\n :param lambda_param: The lambda of equation 19 with `lambda_param=0` corresponding to a single iteration and\n `lambda_param=1` to a uniform distribution of iterations per step.\n :param sigma: Variance of the Gaussian perturbation.\n :param targeted: Should the attack target one specific class.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.batch_size = batch_size\n self.norm = norm\n self.sub_dim = sub_dim\n self.max_iter = max_iter\n self.bin_search_tol = bin_search_tol\n self.lambda_param = lambda_param\n self.sigma = sigma\n self._targeted = False\n\n self.verbose = verbose\n self._check_params()\n\n self.sub_basis: np.ndarray\n self.nb_calls = 0\n self.clip_min = 0.0\n self.clip_max = 0.0\n if self.estimator.input_shape is None: # pragma: no cover\n raise ValueError(\"The `input_shape` of the is required but None.\")\n self.nb_channels = (\n self.estimator.input_shape[0] if self.estimator.channels_first else self.estimator.input_shape[2]\n )\n\n # Optimal number of iterations\n iteration = round(self.max_iter / 500)\n q_opt_it = int(self.max_iter - iteration * 25)\n _, iterate = self._opt_query_iteration(q_opt_it, iteration, self.lambda_param)\n q_opt_it = int(self.max_iter - iterate * 25)\n self.q_opt_iter, self.iterate = self._opt_query_iteration(q_opt_it, iteration, self.lambda_param)\n\n @staticmethod\n def _generate_2d_dct_basis(sub_dim: int, res: int) -> np.ndarray:\n def alpha(var_a: int, num: int):\n \"\"\"\n Get alpha.\n \"\"\"\n if var_a == 0:\n return math.sqrt(1.0 / num)\n\n return math.sqrt(2.0 / num)\n\n def dct(i_x: int, i_y: int, i_v: int, i_u: int, num: int) -> float:\n \"\"\"\n Get 2D DCT.\n \"\"\"\n return (\n alpha(i_u, num)\n * alpha(i_v, num)\n * math.cos(((2 * i_x + 1) * (i_u * math.pi)) / (2 * num))\n * math.cos(((2 * i_y + 1) * (i_v * math.pi)) / (2 * num))\n )\n\n # We can get different frequencies by setting u and v\n u_max = sub_dim\n v_max = sub_dim\n\n dct_basis = []\n for i_u in range(u_max):\n for i_v in range(v_max):\n basis = np.zeros((res, res))\n for i_y in range(res):\n for i_x in range(res):\n basis[i_y, i_x] = dct(i_x, i_y, i_v, i_u, max(res, v_max))\n dct_basis.append(basis)\n dct_basis_array = np.mat(np.reshape(dct_basis, (v_max * u_max, res * res))).transpose()\n\n return dct_basis_array\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y` represents the target labels.\n :return: The adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=True)\n\n if y is not None and self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n x_adv = x.copy()\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)) # type: ignore\n\n # Get clip_min and clip_max from the classifier or infer them from data\n if self.estimator.clip_values is not None:\n self.clip_min, self.clip_max = self.estimator.clip_values\n else:\n self.clip_min, self.clip_max = np.min(x), np.max(x)\n\n # Check for square input images\n if (self.estimator.channels_first and x.shape[2] != x.shape[3]) or ( # pragma: no cover\n not self.estimator.channels_first and x.shape[1] != x.shape[2]\n ):\n raise ValueError(\"Input images `x` have to be square.\")\n\n # Create or load DCT basis\n image_size = x.shape[2]\n logger.info(\"Create or load DCT basis.\")\n path = f\"2d_dct_basis_{self.sub_dim}_{image_size}.npy\"\n if os.path.exists(path):\n self.sub_basis = np.load(path).astype(ART_NUMPY_DTYPE)\n else:\n self.sub_basis = self._generate_2d_dct_basis(sub_dim=self.sub_dim, res=image_size).astype(ART_NUMPY_DTYPE)\n np.save(path, self.sub_basis)\n\n for i in trange(x.shape[0], desc=\"GeoDA - samples\", disable=not self.verbose, position=0):\n x_i = x[[i]]\n y_i = y[[i]]\n\n # Reset number of calls\n self.nb_calls = 0\n\n # Random search\n x_random = self._find_random_adversarial(x=x_i, y=y_i)\n logger.info(\"Random search adversarial example is adversarial: %r\", self._is_adversarial(x_random, y_i))\n\n # Binary search\n x_boundary = self._binary_search(x_i, y_i, x_random, tol=self.bin_search_tol)\n logger.info(\"Binary search example at boundary is adversarial: %r\", self._is_adversarial(x_boundary, y_i))\n\n grad = np.zeros_like(x_i)\n x_adv_i = x_i\n\n for k in trange(self.iterate, desc=\"GeoDA - steps\", disable=not self.verbose, position=1):\n grad_oi, _ = self._black_grad_batch(x_boundary, self.q_opt_iter[k], self.batch_size, y_i)\n grad = grad_oi + grad\n x_adv_i = self._go_to_boundary(x_i, y_i, grad)\n x_adv_i = self._binary_search(x_i, y_i, x_adv_i, tol=self.bin_search_tol)\n x_boundary = x_adv_i\n\n x_adv_i = np.clip(x_adv_i, a_min=self.clip_min, a_max=self.clip_max)\n\n x_adv[i] = x_adv_i\n\n return x_adv\n\n def _is_adversarial(self, x_adv: np.ndarray, y_true: np.ndarray) -> bool:\n \"\"\"\n Check if example is adversarial.\n\n :param x_adv: Current example.\n :param y_true: True label of `x`.\n :return: Boolean if `x` is mis-classified.\n \"\"\"\n y_prediction = self.estimator.predict(x=x_adv)\n\n if self.targeted:\n return np.argmax(y_prediction, axis=1)[0] == np.argmax(y_true, axis=1)[0]\n\n return np.argmax(y_prediction, axis=1)[0] != np.argmax(y_true, axis=1)[0]\n\n def _find_random_adversarial(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Find an adversarial example by random search.\n\n :param x: Current example.\n :param y: True label of `x`.\n :return: A random adversarial example for `x`.\n \"\"\"\n nb_calls = 0\n step_size = 0.02\n x_perturbed = x\n\n while not self._is_adversarial(x_perturbed, y):\n nb_calls += 1\n perturbation = np.random.normal(size=x.shape).astype(ART_NUMPY_DTYPE)\n x_perturbed = x + nb_calls * step_size * perturbation\n x_perturbed = np.clip(x_perturbed, a_min=self.clip_min, a_max=self.clip_max)\n\n self.nb_calls += nb_calls\n\n return x_perturbed\n\n def _binary_search(self, x: np.ndarray, y: np.ndarray, x_random: np.ndarray, tol: float) -> np.ndarray:\n \"\"\"\n Find example on decision boundary between input and random sample by binary search.\n\n :param x: Current example.\n :param y: True label of `x`.\n :param x_random: Random adversarial example of `x`.\n :return: The adversarial example at the decision boundary.\n \"\"\"\n x_adv = x_random\n x_cln = x\n\n if self.estimator.clip_values is not None:\n max_value = self.estimator.clip_values[1]\n else:\n max_value = np.max(x)\n\n while np.linalg.norm((x_adv.flatten() - x_cln.flatten()) / max_value, ord=2) >= tol:\n self.nb_calls += 1\n x_mid = (x_cln + x_adv) / 2.0\n if self._is_adversarial(x_mid, y):\n x_adv = x_mid\n else:\n x_cln = x_mid\n\n return x_adv\n\n def _opt_query_iteration(self, var_nq: int, var_t: int, lambda_param: float) -> tuple[list[int], int]:\n \"\"\"\n Determine optimal distribution of number of queries.\n \"\"\"\n coefficients = [lambda_param ** (-2 * i / 3) for i in range(0, var_t)]\n sum_coefficients = sum(coefficients)\n opt_q = [round(var_nq * coefficients[i] / sum_coefficients) for i in range(0, var_t)]\n\n if opt_q[0] > 80:\n var_t = var_t + 1\n opt_q, var_t = self._opt_query_iteration(var_nq, var_t, lambda_param)\n elif opt_q[0] < 50:\n var_t = var_t - 1\n opt_q, var_t = self._opt_query_iteration(var_nq, var_t, lambda_param)\n\n return opt_q, var_t\n\n def _black_grad_batch(\n self, x_boundary: np.ndarray, q_max: int, batch_size: int, original_label: np.ndarray\n ) -> tuple[np.ndarray, int]:\n \"\"\"\n Calculate gradient towards decision boundary.\n \"\"\"\n self.nb_calls += q_max\n grad_tmp: list[np.ndarray] = [] # estimated gradients in each estimate_batch\n z_list: list[int] = [] # sign of grad_tmp\n outs = []\n num_batches = math.ceil(q_max / batch_size)\n last_batch = q_max - (num_batches - 1) * batch_size\n all_noises = []\n\n for j in range(num_batches):\n if j == num_batches - 1:\n current_batch = self._sub_noise(last_batch, self.sub_basis)\n noisy_boundary = [x_boundary[0, :, :, :]] * last_batch + self.sigma * current_batch\n else:\n current_batch = self._sub_noise(batch_size, self.sub_basis)\n noisy_boundary = [x_boundary[0, :, :, :]] * batch_size + self.sigma * current_batch\n\n all_noises.append(current_batch)\n predict_labels = np.argmax(self.estimator.predict(noisy_boundary), axis=1).astype(int)\n outs.append(predict_labels)\n\n all_noise = np.concatenate(all_noises, axis=0)\n outs = np.concatenate(outs, axis=0)\n\n for i, predict_label in enumerate(outs):\n if predict_label == np.argmax(original_label, axis=1)[0]:\n z_list.append(1)\n grad_tmp.append(all_noise[i])\n else:\n z_list.append(-1)\n grad_tmp.append(-all_noise[i])\n\n grad: np.ndarray = -(1 / q_max) * sum(grad_tmp) # type: ignore\n grad_f = grad[None, :, :, :]\n\n return grad_f, sum(z_list)\n\n def _go_to_boundary(self, x: np.ndarray, y: np.ndarray, grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Move towards decision boundary.\n\n :param x: Current example to be moved towards the decision boundary.\n :param y: The true label.\n :param grad: Gradient towards decision boundary.\n :return: Example moved towards decision boundary.\n \"\"\"\n epsilon = 5\n nb_calls = 0\n x_perturbed = x\n\n if self.norm in [np.inf, \"inf\"]:\n grads = np.sign(grad) / np.linalg.norm(grad.flatten(), ord=2)\n else:\n grads = grad # self.norm in [1, 2]\n\n while not self._is_adversarial(x_perturbed, y):\n nb_calls += 1\n if nb_calls > 100:\n logger.info(\"Moving towards decision boundary failed because of too many iterations.\")\n break\n\n x_perturbed = x + (nb_calls * epsilon * grads[0])\n x_perturbed = np.clip(x_perturbed, a_min=self.clip_min, a_max=self.clip_max)\n\n self.nb_calls += nb_calls\n\n return x_perturbed\n\n def _sub_noise(self, num_noises: int, basis: np.ndarray):\n \"\"\"\n Create subspace random perturbation.\n\n :param num_noises: Number of random subspace noises.\n :param basis: Subspace bases.\n :return: Random subspace perturbations.\n \"\"\"\n noise = np.random.normal(size=(basis.shape[1], self.nb_channels * num_noises)) * (self.clip_max - self.clip_min)\n sub_noise = np.array(np.matmul(basis, noise).transpose((1, 0)).astype(ART_NUMPY_DTYPE))\n\n if self.estimator.channels_first:\n subspace_shape = (num_noises,) + self.estimator.input_shape\n else:\n subspace_shape = (\n num_noises,\n self.estimator.input_shape[2],\n self.estimator.input_shape[0],\n self.estimator.input_shape[1],\n )\n\n r_list = sub_noise.reshape(subspace_shape)\n\n if not self.estimator.channels_first:\n r_list = r_list.transpose((0, 2, 3, 1))\n\n return r_list\n\n def _check_params(self) -> None:\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The batch size has to be a positive integer.\")\n\n if self.norm not in [1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, or \"inf\".')\n\n if not isinstance(self.sub_dim, int) or self.sub_dim <= 0:\n raise ValueError(\"The subspace dimension has to be a positive integer.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The maximum number of iterations has to be a positive integer.\")\n\n if not isinstance(self.bin_search_tol, float) or self.bin_search_tol <= 0:\n raise ValueError(\"The binary search tolerance has to be a positive float.\")\n\n if not isinstance(self.lambda_param, float) or self.lambda_param <= 0:\n raise ValueError(\"The lambda parameter has to be a positive float.\")\n\n if not isinstance(self.sigma, float) or self.sigma <= 0:\n raise ValueError(\"The sigma has to be a positive float.\")\n\n # if not isinstance(self.targeted, bool):\n # raise ValueError(\"The argument `targeted` has to be of type bool.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/hclu.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nImplementation of the High-Confidence-Low-Uncertainty (HCLU) adversarial example formulation by Grosse et al. (2018)\n\n| Paper link: https://arxiv.org/abs/1812.02606\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport copy\nimport logging\n\n\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.classification.GPy import GPyGaussianProcessClassifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass HighConfidenceLowUncertainty(EvasionAttack):\n \"\"\"\n Implementation of the High-Confidence-Low-Uncertainty (HCLU) adversarial example formulation by Grosse et al. (2018)\n\n | Paper link: https://arxiv.org/abs/1812.02606\n \"\"\"\n\n attack_params = [\"conf\", \"unc_increase\", \"min_val\", \"max_val\", \"verbose\"]\n _estimator_requirements = (GPyGaussianProcessClassifier,)\n\n def __init__(\n self,\n classifier: GPyGaussianProcessClassifier,\n conf: float = 0.95,\n unc_increase: float = 100.0,\n min_val: float = 0.0,\n max_val: float = 1.0,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n :param classifier: A trained model of type GPYGaussianProcessClassifier.\n :param conf: Confidence that examples should have, if there were to be classified as 1.0 maximally.\n :param unc_increase: Value uncertainty is allowed to deviate, where 1.0 is original value.\n :param min_val: minimal value any feature can take.\n :param max_val: maximal value any feature can take.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.conf = conf\n self.unc_increase = unc_increase\n self.min_val = min_val\n self.max_val = max_val\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial examples and return them as an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :return: An array holding the adversarial examples.\n \"\"\"\n x_adv = copy.copy(x)\n\n def minfun(x, args): # minimize L2 norm\n return np.sum(np.sqrt((x - args[\"orig\"]) ** 2))\n\n def constraint_conf(x, args): # constraint for confidence\n pred = args[\"classifier\"].predict(x.reshape(1, -1))[0, 0]\n if args[\"class_zero\"]:\n pred = 1.0 - pred\n return (pred - args[\"conf\"]).reshape(-1)\n\n def constraint_unc(x, args): # constraint for uncertainty\n cur_unc = (args[\"classifier\"].predict_uncertainty(x.reshape(1, -1))).reshape(-1)\n return (args[\"max_uncertainty\"] - cur_unc)[0]\n\n bounds = []\n # adding bounds, to not go away from original data\n for i in range(np.shape(x)[1]):\n bounds.append((self.min_val, self.max_val))\n for i in trange(x.shape[0], desc=\"HCLU\", disable=not self.verbose): # go through data and craft\n # get properties for attack\n max_uncertainty = self.unc_increase * self.estimator.predict_uncertainty(x_adv[i].reshape(1, -1))\n class_zero = not self.estimator.predict(x_adv[i].reshape(1, -1))[0, 0] < 0.5\n init_args = {\n \"classifier\": self.estimator,\n \"class_zero\": class_zero,\n \"max_uncertainty\": max_uncertainty,\n \"conf\": self.conf,\n }\n constr_conf = {\"type\": \"ineq\", \"fun\": constraint_conf, \"args\": (init_args,)}\n constr_unc = {\"type\": \"ineq\", \"fun\": constraint_unc, \"args\": (init_args,)}\n args = {\"args\": init_args, \"orig\": x[i].reshape(-1)}\n # finally, run optimization\n x_adv[i] = minimize(\n minfun,\n x_adv[i],\n args=args,\n bounds=bounds,\n constraints=[constr_conf, constr_unc],\n )[\"x\"]\n\n return x_adv\n\n def _check_params(self) -> None:\n\n if self.conf <= 0.5 or self.conf > 1.0:\n raise ValueError(\"Confidence value has to be a value between 0.5 and 1.0.\")\n\n if self.unc_increase <= 0.0:\n raise ValueError(\"Value to increase uncertainty must be positive.\")\n\n if self.min_val > self.max_val:\n raise ValueError(\"Maximum has to be larger than minimum.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/hop_skip_jump.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the HopSkipJump attack `HopSkipJump`. This is a black-box attack that only requires class\npredictions. It is an advanced version of the Boundary attack.\n\n| Paper link: https://arxiv.org/abs/1904.02144\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\nfrom art.utils import compute_success, to_categorical, check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass HopSkipJump(EvasionAttack):\n \"\"\"\n Implementation of the HopSkipJump attack from Jianbo et al. (2019). This is a powerful black-box attack that\n only requires final class prediction, and is an advanced version of the boundary attack.\n\n | Paper link: https://arxiv.org/abs/1904.02144\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"targeted\",\n \"norm\",\n \"max_iter\",\n \"max_eval\",\n \"init_eval\",\n \"init_size\",\n \"curr_iter\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n batch_size: int = 64,\n targeted: bool = False,\n norm: int | float | str = 2,\n max_iter: int = 50,\n max_eval: int = 10000,\n init_eval: int = 100,\n init_size: int = 100,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a HopSkipJump attack instance.\n\n :param classifier: A trained classifier.\n :param batch_size: The size of the batch used by the estimator during inference.\n :param targeted: Should the attack target one specific class.\n :param norm: Order of the norm. Possible values: \"inf\", np.inf or 2.\n :param max_iter: Maximum number of iterations.\n :param max_eval: Maximum number of evaluations for estimating gradient.\n :param init_eval: Initial number of evaluations for estimating gradient.\n :param init_size: Maximum number of trials for initial generation of adversarial examples.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self._targeted = targeted\n self.norm = norm\n self.max_iter = max_iter\n self.max_eval = max_eval\n self.init_eval = init_eval\n self.init_size = init_size\n self.curr_iter = 0\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n self.curr_iter = 0\n\n # Set binary search threshold\n if norm == 2:\n self.theta = 0.01 / np.sqrt(np.prod(self.estimator.input_shape))\n else:\n self.theta = 0.01 / np.prod(self.estimator.input_shape)\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,).\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :param x_adv_init: Initial array to act as initial adversarial examples. Same shape as `x`.\n :type x_adv_init: `np.ndarray`\n :param resume: Allow users to continue their previous attack.\n :type resume: `bool`\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = kwargs.get(\"mask\")\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)) # type: ignore\n\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Check whether users need a stateful attack\n resume = kwargs.get(\"resume\")\n\n if resume is not None and resume:\n start = self.curr_iter\n else:\n start = 0\n\n # Check the mask\n if mask is not None:\n if len(mask.shape) == len(x.shape):\n mask = mask.astype(ART_NUMPY_DTYPE)\n else:\n mask = np.array([mask.astype(ART_NUMPY_DTYPE)] * x.shape[0])\n else:\n mask = np.array([None] * x.shape[0])\n\n # Get clip_min and clip_max from the classifier or infer them from data\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.min(x), np.max(x)\n\n # Prediction from the original images\n preds = np.argmax(self.estimator.predict(x, batch_size=self.batch_size), axis=1)\n\n # Prediction from the initial adversarial examples if not None\n x_adv_init = kwargs.get(\"x_adv_init\")\n\n if x_adv_init is not None:\n # Add mask param to the x_adv_init\n for i in range(x.shape[0]):\n if mask[i] is not None:\n x_adv_init[i] = x_adv_init[i] * mask[i] + x[i] * (1 - mask[i])\n\n # Do prediction on the init\n init_preds = np.argmax(self.estimator.predict(x_adv_init, batch_size=self.batch_size), axis=1)\n\n else:\n init_preds = [None] * len(x)\n x_adv_init = [None] * len(x)\n\n # Assert that, if attack is targeted, y is provided\n if self.targeted and y is None: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Some initial setups\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n y = np.argmax(y, axis=1)\n\n # Generate the adversarial samples\n for ind, val in enumerate(tqdm(x_adv, desc=\"HopSkipJump\", disable=not self.verbose)):\n self.curr_iter = start\n\n if self.targeted:\n x_adv[ind] = self._perturb(\n x=val,\n y=y[ind], # type: ignore\n y_p=preds[ind],\n init_pred=init_preds[ind],\n adv_init=x_adv_init[ind],\n mask=mask[ind],\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n else:\n x_adv[ind] = self._perturb(\n x=val,\n y=-1,\n y_p=preds[ind],\n init_pred=init_preds[ind],\n adv_init=x_adv_init[ind],\n mask=mask[ind],\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n y = to_categorical(y, self.estimator.nb_classes) # type: ignore\n\n logger.info(\n \"Success rate of HopSkipJump attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n return x_adv\n\n def _perturb(\n self,\n x: np.ndarray,\n y: int,\n y_p: int,\n init_pred: int,\n adv_init: np.ndarray,\n mask: np.ndarray | None,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray:\n \"\"\"\n Internal attack function for one example.\n\n :param x: An array with one original input to be attacked.\n :param y: If `self.targeted` is true, then `y` represents the target label.\n :param y_p: The predicted label of x.\n :param init_pred: The predicted label of the initial image.\n :param adv_init: Initial array to act as an initial adversarial example.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: An adversarial example.\n \"\"\"\n # First, create an initial adversarial sample\n initial_sample = self._init_sample(x, y, y_p, init_pred, adv_init, mask, clip_min, clip_max)\n\n # If an initial adversarial example is not found, then return the original image\n if initial_sample is None:\n return x\n\n # If an initial adversarial example found, then go with HopSkipJump attack\n x_adv = self._attack(initial_sample[0], x, initial_sample[1], mask, clip_min, clip_max)\n\n return x_adv\n\n def _init_sample(\n self,\n x: np.ndarray,\n y: int,\n y_p: int,\n init_pred: int,\n adv_init: np.ndarray,\n mask: np.ndarray | None,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray | tuple[np.ndarray, int] | None:\n \"\"\"\n Find initial adversarial example for the attack.\n\n :param x: An array with 1 original input to be attacked.\n :param y: If `self.targeted` is true, then `y` represents the target label.\n :param y_p: The predicted label of x.\n :param init_pred: The predicted label of the initial image.\n :param adv_init: Initial array to act as an initial adversarial example.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: An adversarial example.\n \"\"\"\n nprd = np.random.RandomState()\n initial_sample = None\n\n if self.targeted:\n # Attack satisfied\n if y == y_p:\n return None\n\n # Attack unsatisfied yet and the initial image satisfied\n if adv_init is not None and init_pred == y:\n return adv_init.astype(ART_NUMPY_DTYPE), init_pred\n\n # Attack unsatisfied yet and the initial image unsatisfied\n for _ in range(self.init_size):\n random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)\n\n if mask is not None:\n random_img = random_img * mask + x * (1 - mask)\n\n random_class = np.argmax(\n self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),\n axis=1,\n )[0]\n\n if random_class == y:\n # Binary search to reduce the l2 distance to the original image\n random_img = self._binary_search(\n current_sample=random_img,\n original_sample=x,\n target=y,\n norm=2,\n clip_min=clip_min,\n clip_max=clip_max,\n threshold=0.001,\n )\n initial_sample = random_img, random_class\n\n logger.info(\"Found initial adversarial image for targeted attack.\")\n break\n else:\n logger.warning(\"Failed to draw a random image that is adversarial, attack failed.\")\n\n else:\n # The initial image satisfied\n if adv_init is not None and init_pred != y_p:\n return adv_init.astype(ART_NUMPY_DTYPE), y_p\n\n # The initial image unsatisfied\n for _ in range(self.init_size):\n random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)\n\n if mask is not None:\n random_img = random_img * mask + x * (1 - mask)\n\n random_class = np.argmax(\n self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),\n axis=1,\n )[0]\n\n if random_class != y_p:\n # Binary search to reduce the l2 distance to the original image\n random_img = self._binary_search(\n current_sample=random_img,\n original_sample=x,\n target=y_p,\n norm=2,\n clip_min=clip_min,\n clip_max=clip_max,\n threshold=0.001,\n )\n initial_sample = random_img, y_p\n\n logger.info(\"Found initial adversarial image for untargeted attack.\")\n break\n else:\n logger.warning(\"Failed to draw a random image that is adversarial, attack failed.\")\n\n return initial_sample\n\n def _attack(\n self,\n initial_sample: np.ndarray,\n original_sample: np.ndarray,\n target: int,\n mask: np.ndarray | None,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray:\n \"\"\"\n Main function for the boundary attack.\n\n :param initial_sample: An initial adversarial example.\n :param original_sample: The original input.\n :param target: The target label.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: an adversarial example.\n \"\"\"\n # Set current perturbed image to the initial image\n current_sample = initial_sample\n\n # Main loop to wander around the boundary\n for _ in range(self.max_iter):\n # First compute delta\n delta = self._compute_delta(\n current_sample=current_sample,\n original_sample=original_sample,\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n # Then run binary search\n current_sample = self._binary_search(\n current_sample=current_sample,\n original_sample=original_sample,\n norm=self.norm,\n target=target,\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n # Next compute the number of evaluations and compute the update\n num_eval = min(int(self.init_eval * np.sqrt(self.curr_iter + 1)), self.max_eval)\n\n update = self._compute_update(\n current_sample=current_sample,\n num_eval=num_eval,\n delta=delta,\n target=target,\n mask=mask,\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n # Finally run step size search by first computing epsilon\n if self.norm == 2:\n dist = np.linalg.norm(original_sample - current_sample)\n else:\n dist = np.max(abs(original_sample - current_sample))\n\n epsilon = 2.0 * dist / np.sqrt(self.curr_iter + 1)\n success = False\n\n while not success:\n epsilon /= 2.0\n potential_sample = current_sample + epsilon * update\n success = self._adversarial_satisfactory( # type: ignore\n samples=potential_sample[None],\n target=target,\n clip_min=clip_min,\n clip_max=clip_max,\n )\n\n # Update current sample\n current_sample = np.clip(potential_sample, clip_min, clip_max)\n\n # Update current iteration\n self.curr_iter += 1\n\n # If attack failed. return original sample\n if np.isnan(current_sample).any(): # pragma: no cover\n logger.debug(\"NaN detected in sample, returning original sample.\")\n return original_sample\n\n return current_sample\n\n def _binary_search(\n self,\n current_sample: np.ndarray,\n original_sample: np.ndarray,\n target: int,\n norm: int | float | str,\n clip_min: float,\n clip_max: float,\n threshold: float | None = None,\n ) -> np.ndarray:\n \"\"\"\n Binary search to approach the boundary.\n\n :param current_sample: Current adversarial example.\n :param original_sample: The original input.\n :param target: The target label.\n :param norm: Order of the norm. Possible values: \"inf\", np.inf or 2.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param threshold: The upper threshold in binary search.\n :return: an adversarial example.\n \"\"\"\n # First set upper and lower bounds as well as the threshold for the binary search\n if norm == 2:\n (upper_bound, lower_bound) = (np.array(1.0), np.array(0.0))\n\n if threshold is None:\n threshold = self.theta\n\n else:\n (upper_bound, lower_bound) = (\n np.max(abs(original_sample - current_sample)),\n np.array(0.0),\n )\n\n if threshold is None:\n threshold = np.minimum(upper_bound * self.theta, self.theta)\n\n # Then start the binary search\n while (upper_bound - lower_bound) > threshold:\n # Interpolation point\n alpha = (upper_bound + lower_bound) / 2.0\n interpolated_sample = self._interpolate(\n current_sample=current_sample,\n original_sample=original_sample,\n alpha=alpha,\n norm=norm,\n )\n\n # Update upper_bound and lower_bound\n satisfied = self._adversarial_satisfactory(\n samples=interpolated_sample[None],\n target=target,\n clip_min=clip_min,\n clip_max=clip_max,\n )[0]\n lower_bound = np.where(satisfied == 0, alpha, lower_bound)\n upper_bound = np.where(satisfied == 1, alpha, upper_bound)\n\n result = self._interpolate(\n current_sample=current_sample,\n original_sample=original_sample,\n alpha=float(upper_bound),\n norm=norm,\n )\n\n return result\n\n def _compute_delta(\n self,\n current_sample: np.ndarray,\n original_sample: np.ndarray,\n clip_min: float,\n clip_max: float,\n ) -> float:\n \"\"\"\n Compute the delta parameter.\n\n :param current_sample: Current adversarial example.\n :param original_sample: The original input.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: Delta value.\n \"\"\"\n # Note: This is a bit different from the original paper, instead we keep those that are\n # implemented in the original source code of the authors\n if self.curr_iter == 0:\n return 0.1 * (clip_max - clip_min)\n\n if self.norm == 2:\n dist = np.linalg.norm(original_sample - current_sample)\n delta = np.sqrt(np.prod(self.estimator.input_shape)) * self.theta * dist\n else:\n dist = np.max(abs(original_sample - current_sample))\n delta = np.prod(self.estimator.input_shape) * self.theta * dist\n\n return delta\n\n def _compute_update(\n self,\n current_sample: np.ndarray,\n num_eval: int,\n delta: float,\n target: int,\n mask: np.ndarray | None,\n clip_min: float,\n clip_max: float,\n ) -> np.ndarray:\n \"\"\"\n Compute the update in Eq.(14).\n\n :param current_sample: Current adversarial example.\n :param num_eval: The number of evaluations for estimating gradient.\n :param delta: The size of random perturbation.\n :param target: The target label.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: an updated perturbation.\n \"\"\"\n # Generate random noise\n rnd_noise_shape = [num_eval] + list(self.estimator.input_shape)\n if self.norm == 2:\n rnd_noise = np.random.randn(*rnd_noise_shape).astype(ART_NUMPY_DTYPE)\n else:\n rnd_noise = np.random.uniform(low=-1, high=1, size=rnd_noise_shape).astype(ART_NUMPY_DTYPE)\n\n # With mask\n if mask is not None:\n rnd_noise = rnd_noise * mask\n\n # Normalize random noise to fit into the range of input data\n rnd_noise = rnd_noise / np.sqrt(\n np.sum(\n rnd_noise**2,\n axis=tuple(range(len(rnd_noise_shape)))[1:],\n keepdims=True,\n )\n )\n eval_samples = np.clip(current_sample + delta * rnd_noise, clip_min, clip_max)\n rnd_noise = (eval_samples - current_sample) / delta\n\n # Compute gradient: This is a bit different from the original paper, instead we keep those that are\n # implemented in the original source code of the authors\n satisfied = self._adversarial_satisfactory(\n samples=eval_samples, target=target, clip_min=clip_min, clip_max=clip_max\n )\n f_val = 2 * satisfied.reshape([num_eval] + [1] * len(self.estimator.input_shape)) - 1.0\n f_val = f_val.astype(ART_NUMPY_DTYPE)\n\n if np.mean(f_val) == 1.0:\n grad = np.mean(rnd_noise, axis=0)\n elif np.mean(f_val) == -1.0:\n grad = -np.mean(rnd_noise, axis=0)\n else:\n f_val -= np.mean(f_val)\n grad = np.mean(f_val * rnd_noise, axis=0)\n\n # Compute update\n if self.norm == 2:\n result = grad / np.linalg.norm(grad)\n else:\n result = np.sign(grad)\n\n return result\n\n def _adversarial_satisfactory(\n self, samples: np.ndarray, target: int, clip_min: float, clip_max: float\n ) -> np.ndarray:\n \"\"\"\n Check whether an image is adversarial.\n\n :param samples: A batch of examples.\n :param target: The target label.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: An array of 0/1.\n \"\"\"\n samples = np.clip(samples, clip_min, clip_max)\n preds = np.argmax(self.estimator.predict(samples, batch_size=self.batch_size), axis=1)\n\n if self.targeted:\n result = preds == target\n else:\n result = preds != target\n\n return result\n\n @staticmethod\n def _interpolate(\n current_sample: np.ndarray, original_sample: np.ndarray, alpha: float, norm: int | float | str\n ) -> np.ndarray:\n \"\"\"\n Interpolate a new sample based on the original and the current samples.\n\n :param current_sample: Current adversarial example.\n :param original_sample: The original input.\n :param alpha: The coefficient of interpolation.\n :param norm: Order of the norm. Possible values: \"inf\", np.inf or 2.\n :return: An adversarial example.\n \"\"\"\n if norm == 2:\n result = (1 - alpha) * original_sample + alpha * current_sample\n else:\n result = np.clip(current_sample, original_sample - alpha, original_sample + alpha)\n\n return result\n\n def _check_params(self) -> None:\n # Check if order of the norm is acceptable given current implementation\n if self.norm not in [2, np.inf, \"inf\"]:\n raise ValueError('Norm order must be either 2, `np.inf` or \"inf\".')\n\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.max_eval, int) or self.max_eval <= 0:\n raise ValueError(\"The maximum number of evaluations must be a positive integer.\")\n\n if not isinstance(self.init_eval, int) or self.init_eval <= 0:\n raise ValueError(\"The initial number of evaluations must be a positive integer.\")\n\n if self.init_eval > self.max_eval:\n raise ValueError(\"The maximum number of evaluations must be larger than the initial number of evaluations.\")\n\n if not isinstance(self.init_size, int) or self.init_size <= 0:\n raise ValueError(\"The number of initial trials must be a positive integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/iterative_method.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Basic Iterative Method attack `BasicIterativeMethod` as the iterative version of FGM and\nFGSM. This is a white-box attack.\n\n| Paper link: https://arxiv.org/abs/1607.02533\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass BasicIterativeMethod(ProjectedGradientDescent):\n \"\"\"\n The Basic Iterative Method is the iterative version of FGM and FGSM.\n\n | Paper link: https://arxiv.org/abs/1607.02533\n \"\"\"\n\n attack_params = ProjectedGradientDescent.attack_params\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n max_iter: int = 100,\n targeted: bool = False,\n batch_size: int = 32,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a :class:`.ProjectedGradientDescent` instance.\n\n :param estimator: A trained classifier.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n estimator=estimator,\n norm=np.inf,\n eps=eps,\n eps_step=eps_step,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=0,\n batch_size=batch_size,\n verbose=verbose,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/lowprofool.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the `LowProFool` attack. This is a white-box attack.\n\nIts main objective is to take a valid tabular sample and transform it, so that a given classifier predicts it to be some\ntarget class.\n\n`LowProFool` attack transforms the provided real-valued tabular data into adversaries of the specified target classes.\nThe generated adversaries have to be as close as possible to the original samples in terms of the weighted Lp-norm,\nwhere the weights determine each feature's importance.\n\n| Paper link: https://arxiv.org/abs/1911.03274\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.stats import pearsonr\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import LossGradientsMixin\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass LowProFool(EvasionAttack):\n \"\"\"\n `LowProFool` attack.\n\n | Paper link: https://arxiv.org/abs/1911.03274\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"n_steps\",\n \"threshold\",\n \"lambd\",\n \"eta\",\n \"eta_decay\",\n \"eta_min\",\n \"norm\",\n \"importance\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n n_steps: int = 100,\n threshold: float | None = 0.5,\n lambd: float = 1.5,\n eta: float = 0.2,\n eta_decay: float = 0.98,\n eta_min: float = 1e-7,\n norm: int | float | str = 2,\n importance: Callable | str | np.ndarray = \"pearson\",\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create a LowProFool instance.\n\n :param classifier: Appropriate classifier's instance\n :param n_steps: Number of iterations to follow\n :param threshold: Lowest prediction probability of a valid adversary\n :param lambd: Amount of lp-norm impact on objective function\n :param eta: Rate of updating the perturbation vectors\n :param eta_decay: Step-by-step decrease of eta\n :param eta_min: Minimal eta value\n :param norm: Parameter `p` for Lp-space norm (norm=2 - euclidean norm)\n :param importance: Function to calculate feature importance with\n or vector of those precomputed; possibilities:\n > 'pearson' - Pearson correlation (string)\n > function - Custom function (callable object)\n > vector - Vector of feature importance (np.ndarray)\n :param verbose: Verbose mode / Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.n_steps = n_steps\n self.threshold = threshold\n self.lambd = lambd\n self.eta = eta\n self.eta_decay = eta_decay\n self.eta_min = eta_min\n self.norm = norm\n self.importance = importance\n self.verbose = verbose\n\n self._targeted = True\n self.n_classes = self.estimator.nb_classes\n self.n_features = self.estimator.input_shape[0]\n self.importance_vec = None\n if self.estimator.clip_values is None:\n logger.warning( # pragma: no cover\n \"The `clip_values` attribute of the estimator is `None`, therefore this instance of LowProFool will by \"\n \"default generate adversarial perturbations without clipping them.\"\n )\n\n self._check_params()\n\n if isinstance(self.importance, np.ndarray):\n self.importance_vec = self.importance\n\n if eta_decay < 1 and eta_min > 0:\n steps_before_min_eta_reached = np.ceil(np.log(eta_min / eta) / np.log(eta_decay))\n\n if steps_before_min_eta_reached / self.n_steps < 0.8:\n logger.warning( # pragma: no cover\n \"The given combination of 'n_steps', 'eta', 'eta_decay' and 'eta_min' effectively sets learning \"\n \"rate to its minimal value after about %d steps out of all %d.\",\n steps_before_min_eta_reached,\n self.n_steps,\n )\n\n def __weighted_lp_norm(self, perturbations: np.ndarray) -> np.ndarray:\n \"\"\"\n Lp-norm of perturbation vectors weighted by feature importance.\n\n :param perturbations: Perturbations of samples towards being adversarial.\n :return: Array with weighted Lp-norm of perturbations.\n \"\"\"\n order: int | float = np.inf if self.norm == \"inf\" else float(self.norm)\n return self.lambd * np.linalg.norm(self.importance_vec * perturbations, axis=1, ord=order).reshape(-1, 1)\n\n def __weighted_lp_norm_gradient(self, perturbations: np.ndarray) -> np.ndarray:\n \"\"\"\n Gradient of the weighted Lp-space norm in regard to the data vector.\n\n :param perturbations: Perturbations of samples towards being adversarial.\n :return: Weighted Lp-norm gradients array.\n \"\"\"\n norm = self.norm\n\n if isinstance(norm, (int, float)) and norm < np.inf and self.importance_vec is not None:\n numerator = (\n self.importance_vec * self.importance_vec * perturbations * np.power(np.abs(perturbations), norm - 2)\n )\n denominator = np.power(np.sum(np.power(self.importance_vec * perturbations, norm)), (norm - 1) / norm)\n\n numerator = np.where(denominator > 1e-10, numerator, np.zeros(numerator.shape[1]))\n denominator = np.where(denominator <= 1e-10, 1.0, denominator)\n\n return numerator / denominator\n\n # L-infinity norm (norm in [\"inf\", np.inf]).\n numerator = np.array(self.importance_vec * perturbations)\n optimum = np.max(np.abs(numerator))\n return np.where(abs(numerator) == optimum, np.sign(numerator), 0)\n\n def __get_gradients(self, samples: np.ndarray, perturbations: np.ndarray, targets: np.ndarray) -> np.ndarray:\n \"\"\"\n Gradient of the objective function in regard to the data vector, i.e. sum of the classifier's loss gradient\n and weighted lp-space norm gradient, both in regard to data vector.\n\n :param samples: Base design matrix.\n :param perturbations: Perturbations of samples towards being adversarial.\n :param targets: The target labels for the attack.\n :return: Aggregate gradient of objective function.\n \"\"\"\n clf_loss_grad = self.estimator.loss_gradient(\n (samples + perturbations).astype(np.float32), targets.astype(np.float32)\n )\n norm_grad = self.lambd * self.__weighted_lp_norm_gradient(perturbations)\n\n return clf_loss_grad + norm_grad\n\n def __apply_clipping(self, samples: np.ndarray, perturbations: np.ndarray) -> np.ndarray:\n \"\"\"\n Function for clipping perturbation vectors to forbid the adversary vectors to go beyond the allowed ranges of\n values.\n\n :param samples: Base design matrix.\n :param perturbations: Perturbations of samples towards being adversarial.\n :return: Clipped perturbation array.\n \"\"\"\n if self.estimator.clip_values is None:\n return perturbations\n\n mins = self.estimator.clip_values[0]\n maxs = self.estimator.clip_values[1]\n\n np.clip(perturbations, mins - samples, maxs - samples, perturbations)\n return perturbations\n\n def __calculate_feature_importances(self, x: np.ndarray, y: np.ndarray) -> None:\n \"\"\"\n This function calculates feature importances using a specified built-in function or applies a provided custom\n function (callable object). It calculates those values on the passed training data.\n\n :param x: Design matrix of the dataset used to train the classifier.\n :param y: Labels of the dataset used to train the classifier.\n :return: None.\n \"\"\"\n if self.importance == \"pearson\":\n # Apply a simple Pearson correlation calculation.\n pearson_correlations = [pearsonr(x[:, col], y)[0] for col in range(x.shape[1])]\n absolutes = np.abs(np.array(pearson_correlations))\n self.importance_vec = absolutes / np.power(np.sum(absolutes**2), 0.5)\n\n elif callable(self.importance): # pragma: no cover\n # Apply a custom function to call on the provided data.\n try:\n self.importance_vec = np.array(self.importance(x, y))\n except Exception as exception:\n logger.exception(\"Provided importance function has failed.\")\n raise exception\n\n if not isinstance(self.importance_vec, np.ndarray):\n self.importance_vec = None\n raise TypeError(\"Feature importance vector should be of type np.ndarray or any convertible to that.\")\n if self.importance_vec.shape != (self.n_features,):\n self.importance_vec = None\n raise ValueError(\"Feature has to be one-dimensional array of size (n_features, ).\")\n\n else: # pragma: no cover\n raise TypeError(f\"Unrecognized feature importance function: {self.importance}\")\n\n def fit_importances(\n self,\n x: np.ndarray | None = None,\n y: np.ndarray | None = None,\n importance_array: np.ndarray | None = None,\n normalize: bool | None = True,\n ):\n \"\"\"\n This function allows one to easily calculate the feature importance vector using the pre-specified function,\n in case it wasn't passed at initialization.\n\n :param x: Design matrix of the dataset used to train the classifier.\n :param y: Labels of the dataset used to train the classifier.\n :param importance_array: Array providing features' importance score.\n :param normalize: Assure that feature importance values sum to 1.\n :return: LowProFool instance itself.\n \"\"\"\n if importance_array is not None:\n # Use a pre-calculated vector of feature importance.\n if np.array(importance_array).shape == (self.n_features,):\n self.importance_vec = np.array(importance_array)\n else: # pragma: no cover\n raise ValueError(\"Feature has to be one-dimensional array of size (n_features, ).\")\n\n elif self.importance_vec is None:\n # Apply a function specified at the LowProFool instance initialization.\n self.__calculate_feature_importances(np.array(x), np.array(y))\n\n if normalize:\n # Make sure that importance vector sums to 1.\n if self.importance_vec is not None:\n self.importance_vec = np.array(self.importance_vec) / np.sum(self.importance_vec)\n else:\n raise ValueError(\"Unexpected `None` detected.\")\n\n return self\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversaries for the samples passed in the `x` data matrix, whose targets are specified in `y`,\n one-hot-encoded target matrix. This procedure makes use of the LowProFool algorithm. In the case of failure,\n the resulting array will contain the initial samples on the problematic positions - which otherwise should\n contain the best adversary found in the process.\n\n :param x: An array with the original inputs to be attacked.\n :param y: One-hot-encoded target classes of shape (nb_samples, nb_classes).\n :param kwargs:\n :return: An array holding the adversarial examples.\n \"\"\"\n if self.importance_vec is None:\n raise ValueError(\"No feature importance vector has been provided yet.\")\n if y is None:\n raise ValueError(\"It is required to pass target classes as `y` parameter.\")\n\n # Make sure samples and targets are of type np.ndarray.\n samples = np.array(x, dtype=np.float64)\n targets = np.array(y, dtype=np.float64)\n\n # Extract the target classes as integers implying their classes' indices.\n targets_integer = np.argmax(y, axis=1)\n\n if targets.shape[1] != self.n_classes:\n raise ValueError(\"Targets shape is not compatible with number of classes.\")\n if samples.shape[1] != self.n_features:\n raise ValueError(\"Samples shape is not compatible with number of features.\")\n\n # Initialize perturbation vectors and learning rate.\n perturbations = np.zeros(samples.shape, dtype=np.float64)\n eta = self.eta\n\n # Initialize 'keep-the-best' variables.\n best_norm_losses = np.inf * np.ones(samples.shape[0], dtype=np.float64)\n best_perturbations = perturbations.copy()\n\n # Success indicators per sample.\n success_indicators = np.zeros(samples.shape[0], dtype=np.float64)\n\n # Predicate used to determine whether the target was met based on the given probabilities.\n def met_target(probas, target_class):\n if self.threshold is None:\n return np.argmax(probas) == target_class\n return probas[target_class] > self.threshold\n\n # Main loop.\n for _ in trange(self.n_steps, desc=\"LowProFool\", disable=not self.verbose):\n # Calculate gradients, apply them to perturbations and clip if needed.\n grad = self.__get_gradients(samples, perturbations, targets)\n perturbations -= eta * grad\n perturbations = self.__apply_clipping(samples, perturbations)\n\n # Decrease learning rate for the next iteration.\n eta = max(eta * self.eta_decay, self.eta_min)\n\n # Calculate class-wise probabilities.\n y_probas = self.estimator.predict((samples + perturbations).astype(np.float32))\n\n # Examine the quality of adversaries in the current step.\n for j, target_int in enumerate(targets_integer):\n # Check for every sample whether the threshold probability is reached.\n if met_target(y_probas[j], target_int):\n success_indicators[j] = 1.0\n # Calculate weighted Lp-norm loss.\n norm_loss = self.__weighted_lp_norm(perturbations[j : j + 1])[0, 0]\n\n # Note it, if the adversary improves.\n if norm_loss < best_norm_losses[j]:\n best_norm_losses[j] = norm_loss\n best_perturbations[j] = perturbations[j].copy()\n\n logger.info(\n \"Success rate of LowProFool attack: %.2f}%%\", 100 * np.sum(success_indicators) / success_indicators.size\n )\n\n # The generated adversaries are a sum of initial samples and best perturbation vectors found by the algorithm.\n return samples + best_perturbations\n\n def _check_params(self) -> None:\n \"\"\"\n Check correctness of parameters.\n\n :return: None.\n \"\"\"\n if not (isinstance(self.n_classes, int) and self.n_classes > 0):\n raise ValueError(\"The argument `n_classes` has to be positive integer.\")\n\n if not (isinstance(self.n_features, int) and self.n_features > 0):\n raise ValueError(\"The argument `n_features` has to be positive integer.\")\n\n if not (isinstance(self.n_steps, int) and self.n_steps > 0):\n raise ValueError(\"The argument `n_steps` (number of iterations) has to be positive integer.\")\n\n if not ((isinstance(self.threshold, float) and 0 < self.threshold < 1) or self.threshold is None):\n raise ValueError(\"The argument `threshold` has to be either float in range (0, 1) or None.\")\n\n if not (isinstance(self.lambd, (float, int)) and self.lambd >= 0):\n raise ValueError(\"The argument `lambd` has to be non-negative float or integer.\")\n\n if not (isinstance(self.eta, (float, int)) and self.eta > 0):\n raise ValueError(\"The argument `eta` has to be positive float or integer.\")\n\n if not (isinstance(self.eta_decay, (float, int)) and 0 < self.eta_decay <= 1):\n raise ValueError(\"The argument `eta_decay` has to be float or integer in range (0, 1].\")\n\n if not (isinstance(self.eta_min, (float, int)) and self.eta_min >= 0):\n raise ValueError(\"The argument `eta_min` has to be non-negative float or integer.\")\n\n if not (\n (isinstance(self.norm, (float, int)) and self.norm > 0)\n or (isinstance(self.norm, str) and self.norm == \"inf\")\n or self.norm == np.inf\n ):\n raise ValueError('The argument `norm` has to be either positive-valued float or integer, np.inf, or \"inf\".')\n\n if not (\n isinstance(self.importance, str)\n or callable(self.importance)\n or (isinstance(self.importance, np.ndarray) and self.importance.shape == (self.n_features,))\n ):\n raise ValueError(\n \"The argument `importance` has to be either string, \"\n + \"callable or np.ndarray of the shape (n_features, ).\"\n )\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/momentum_iterative_method.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Momentum Iterative Fast Gradient Method attack `MomentumIterativeMethod` as the iterative\nversion of FGM and FGSM with integrated momentum. This is a white-box attack.\n\n| Paper link: https://arxiv.org/abs/1710.06081\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass MomentumIterativeMethod(ProjectedGradientDescent):\n \"\"\"\n Momentum Iterative Fast Gradient Method attack integrates momentum into the iterative\n version of FGM and FGSM.\n\n | Paper link: https://arxiv.org/abs/1710.06081\n \"\"\"\n\n attack_params = ProjectedGradientDescent.attack_params\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n decay: float = 1.0,\n max_iter: int = 100,\n targeted: bool = False,\n batch_size: int = 32,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a :class:`.MomentumIterativeMethod` instance.\n\n :param estimator: A trained classifier.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param decay: Decay factor for accumulating the velocity vector.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n estimator=estimator,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=0,\n batch_size=batch_size,\n verbose=verbose,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/newtonfool.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the white-box attack `NewtonFool`.\n\n| Paper link: http://doi.acm.org/10.1145/3134600.3134635\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.utils import to_categorical\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass NewtonFool(EvasionAttack):\n \"\"\"\n Implementation of the attack from Uyeong Jang et al. (2017).\n\n | Paper link: http://doi.acm.org/10.1145/3134600.3134635\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\"max_iter\", \"eta\", \"batch_size\", \"verbose\"]\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n max_iter: int = 100,\n eta: float = 0.01,\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a NewtonFool attack instance.\n\n :param classifier: A trained classifier.\n :param max_iter: The maximum number of iterations.\n :param eta: The eta coefficient.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.max_iter = max_iter\n self.eta = eta\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in a Numpy array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the adversarial examples.\n \"\"\"\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n # Initialize variables\n y_pred = self.estimator.predict(x, batch_size=self.batch_size)\n pred_class = np.argmax(y_pred, axis=1)\n\n if self.estimator.nb_classes == 2 and y_pred.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_adv.shape[0] / float(self.batch_size))), desc=\"NewtonFool\", disable=not self.verbose\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch = x_adv[batch_index_1:batch_index_2]\n\n # Main algorithm for each batch\n norm_batch = np.linalg.norm(np.reshape(batch, (batch.shape[0], -1)), axis=1)\n l_batch = pred_class[batch_index_1:batch_index_2]\n l_b = to_categorical(l_batch, self.estimator.nb_classes).astype(bool)\n\n # Main loop of the algorithm\n for _ in range(self.max_iter):\n # Compute score\n score = self.estimator.predict(batch)[l_b]\n\n # Compute the gradients and norm\n grads = self.estimator.class_gradient(batch, label=l_batch)\n if grads.shape[1] == 1:\n grads = np.squeeze(grads, axis=1)\n norm_grad = np.linalg.norm(np.reshape(grads, (batch.shape[0], -1)), axis=1)\n\n # Theta\n theta = self._compute_theta(norm_batch, score, norm_grad)\n\n # Perturbation\n di_batch = self._compute_pert(theta, grads, norm_grad)\n\n # Update xi and perturbation\n batch += di_batch\n\n # Apply clip\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv[batch_index_1:batch_index_2] = np.clip(batch, clip_min, clip_max)\n else:\n x_adv[batch_index_1:batch_index_2] = batch\n\n return x_adv\n\n def _compute_theta(self, norm_batch: np.ndarray, score: np.ndarray, norm_grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Function to compute the theta at each step.\n\n :param norm_batch: Norm of a batch.\n :param score: Softmax value at the attacked class.\n :param norm_grad: Norm of gradient values at the attacked class.\n :return: Theta value.\n \"\"\"\n equ1 = self.eta * norm_batch * norm_grad\n equ2 = score - 1.0 / self.estimator.nb_classes\n result = np.minimum.reduce([equ1, equ2])\n\n return result\n\n @staticmethod\n def _compute_pert(theta: np.ndarray, grads: np.ndarray, norm_grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Function to compute the perturbation at each step.\n\n :param theta: Theta value at the current step.\n :param grads: Gradient values at the attacked class.\n :param norm_grad: Norm of gradient values at the attacked class.\n :return: Computed perturbation.\n \"\"\"\n # Pick a small scalar to avoid division by 0\n tol = 10e-8\n\n nom = -theta.reshape((-1,) + (1,) * (len(grads.shape) - 1)) * grads\n denom = norm_grad**2\n denom[denom < tol] = tol\n result = nom / denom.reshape((-1,) + (1,) * (len(grads.shape) - 1))\n\n return result\n\n def _check_params(self) -> None:\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if not isinstance(self.eta, (float, int)) or self.eta <= 0:\n raise ValueError(\"The eta coefficient must be a positive float.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/pe_malware_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the following white-box attacks related to PE malware crafting:\n 1) Append based attacks (example paper link: https://arxiv.org/abs/1810.08280)\n 2) Section insertion attacks (example paper link: https://arxiv.org/abs/2008.07125)\n 3) Slack manipulation attacks (example paper link: https://arxiv.org/abs/1810.08280)\n 4) DOS Header Attacks (example paper link: https://arxiv.org/abs/1901.03583)\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nimport random\nimport logging\nfrom typing import TYPE_CHECKING\nfrom tqdm.auto import trange\n\nimport numpy as np\n\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.attack import EvasionAttack\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass MalwareGDTensorFlow(EvasionAttack):\n \"\"\"\n Implementation of the following white-box attacks related to PE malware crafting:\n 1) Append based attacks (example paper link: https://arxiv.org/abs/1810.08280)\n 2) Section insertion attacks (example paper link: https://arxiv.org/abs/2008.07125)\n 3) Slack manipulation attacks (example paper link: https://arxiv.org/abs/1810.08280)\n 4) DOS Header Attacks (example paper link: https://arxiv.org/abs/1901.03583)\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"embedding_weights\",\n \"param_dic\",\n \"num_of_iterations\",\n \"l_0\",\n \"l_r\",\n \"use_sign\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n embedding_weights: np.ndarray,\n param_dic: dict[str, int],\n num_of_iterations: int = 10,\n l_0: float | int = 0.1,\n l_r: float = 1.0,\n use_sign: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n :param classifier: A trained classifier that takes in the PE embeddings to make a prediction.\n :param embedding_weights: Weights for the embedding layer\n :param param_dic: A dictionary specifying some MalConv parameters.\n 'maxlen': the input size to the MalConv model\n 'input_dim': the number of discrete values, normally 257.\n 'embedding_size': size of the embedding layer. Default 8.\n :param num_of_iterations: The number of iterations to apply.\n :param l_0: l_0 bound for the attack. If less than 1 it is interpreted as a fraction of the file size.\n If larger than 1 it is interpreted as the total number of permissible features to change.\n :param l_r: Learning rate for the optimisation\n :param use_sign: If we want to use the sign of the gradient, rather than the gradient itself.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.param_dic = param_dic\n self.embedding_weights = embedding_weights\n self.l_0 = l_0\n self.l_r = l_r\n self.use_sign = use_sign\n self.total_perturbation: np.ndarray = np.zeros(shape=(1, 1))\n self.num_of_iterations = num_of_iterations\n self.verbose = verbose\n self._check_params()\n\n self.embedding_weights = self.embedding_weights.astype(\"float32\")\n\n def _check_params(self) -> None:\n if not isinstance(self.param_dic, dict):\n raise ValueError(\n \"A param_dic should be provided with the following keys/value pairs: \"\n \"'maxlen': the input size to the MalConv model\"\n \"'input_dim': the number of discrete values. Normally 257.\"\n \"'embedding_size': size of the embedding layer. Normally 8.\"\n )\n\n if not isinstance(self.embedding_weights, np.ndarray):\n raise ValueError(\"The weights for the embedding layer should be given as a numpy array.\")\n\n if not isinstance(self.l_0, (int, float)) or self.l_0 < 0:\n raise ValueError(\n \"The l0 bound should be greater or equal to 0. Further, it should be provided as an \"\n \"integer specifying the total number of features to perturb, or a a float representing \"\n \"the fraction of the total number of features of the original file we can perturb.\"\n )\n\n if not isinstance(self.l_r, (int, float)) or self.l_r < 0:\n raise ValueError(\"The learning rate should be a float or integer greater than zero.\")\n\n if not isinstance(self.use_sign, bool):\n raise ValueError(\"Whether to use the sign of the gradient should be a True/False bool.\")\n\n if not isinstance(self.num_of_iterations, int) or self.num_of_iterations < 0:\n raise ValueError(\"The number of iterations must be an integer greater than zero.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The verbosity level should be a True/False bool.\")\n\n @staticmethod\n def initialise_sample(\n x: np.ndarray,\n y: np.ndarray,\n sample_sizes: np.ndarray,\n perturbation_size: np.ndarray,\n perturb_sizes: list[list[int]] | None,\n perturb_starts: list[list[int]] | None,\n ) -> np.ndarray:\n \"\"\"\n Randomly append bytes at the end of the malware to initialise it, or if perturbation regions are provided,\n perturb those.\n\n :param x: Array with input data.\n :param y: Labels, after having been adjusted to account for malware which cannot support the full l0 budget.\n :param sample_sizes: The size of the original file, before it was padded to the input size required by MalConv\n :param perturbation_size: Size of the perturbations in L0 terms to put at end of file\n :param perturb_sizes: List of length batch size, each element is in itself a list containing the size\n of the allowable perturbation region\n :param perturb_starts: List of length batch size, each element is in itself a list containing the start\n of perturbation region.\n :return x: Array with features to be perturbed set to a random value.\n \"\"\"\n for j in range(len(x)):\n if y[j] == 1:\n if perturb_sizes is not None and perturb_starts is not None:\n for size, start in zip(perturb_sizes[j], perturb_starts[j]):\n x[j, start : start + size] = np.random.randint(low=0, high=256, size=(1, size))\n x[j, sample_sizes[j] : sample_sizes[j] + perturbation_size[j]] = np.random.randint(\n low=0, high=256, size=(1, perturbation_size[j])\n )\n\n return x\n\n def check_valid_size(\n self,\n y: np.ndarray,\n sample_sizes: np.ndarray,\n append_perturbation_size: np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n Checks that we can append the l0 perturbation to the malware sample and not exceed the\n maximum file size. A new label vector with just the valid files indicated is created.\n\n :param y: Labels.\n :param sample_sizes: The size of the original file, before it was padded to the input size required by MalConv.\n :param append_perturbation_size: Size of the perturbations in L0 terms to put at end of file.\n :return adv_label_vector: Labels which indicate which malware samples have enough free features to\n accommodate all the adversarial perturbation.\n \"\"\"\n\n adv_label_vector = np.zeros_like(y)\n for i, label in enumerate(y):\n if label == 1:\n if sample_sizes[i] + append_perturbation_size[i] <= self.param_dic[\"maxlen\"]:\n adv_label_vector[i] = 1\n logger.info(\"size to append on sample %d is %d\", i, append_perturbation_size[i])\n\n return adv_label_vector\n\n def generate_mask(\n self,\n x: np.ndarray,\n y: np.ndarray,\n sample_sizes: np.ndarray,\n perturbation_size: np.ndarray,\n perturb_sizes: list[list[int]] | None,\n perturb_starts: list[list[int]] | None,\n ) -> \"tf.Tensor\":\n \"\"\"\n Makes a mask to apply to the gradients to control which samples in the batch are perturbed.\n\n :param x: Array with input data.\n :param y: Labels to make sure the benign files are zero masked.\n :param sample_sizes: The size of the original file, before it was padded to the input size required by MalConv\n :param perturbation_size: Size of the perturbations in L0 terms to put at end of file\n :param perturb_sizes: List of length batch size, each element is in itself a list containing the size\n of the allowable perturbation region\n :param perturb_starts: List of length batch size, each element is in itself a list containing the start\n of perturbation region.\n :return mask: Array with 1s on the features we will modify on this batch and 0s elsewhere.\n \"\"\"\n import tensorflow as tf\n\n mask = np.zeros_like(x)\n for i in range(len(x)):\n if y[i] == 1:\n # if no section information was provided, append perturbation at the end of the file.\n if perturb_sizes is None and perturb_starts is None:\n mask[i, sample_sizes[i] : sample_sizes[i] + perturbation_size[i]] = 1\n elif perturb_sizes is not None and perturb_starts is not None:\n sample_perturb_sizes = perturb_sizes[i]\n sample_perturb_starts = perturb_starts[i]\n\n for size, start in zip(sample_perturb_sizes, sample_perturb_starts):\n mask[i, start : start + size] = 1\n mask[i, sample_sizes[i] : sample_sizes[i] + perturbation_size[i]] = 1\n else: # pragma: no cover\n raise ValueError(\n \"either both start and size of perturbation regions are supplied or neither is supplied\"\n )\n\n # sanity check that the total number of features marked on the mask\n # does not exceed the total perturbation budget\n assert np.sum(mask[i]) == self.total_perturbation[i]\n mask = np.expand_dims(mask, axis=-1)\n expanded_masks = []\n for _ in range(self.param_dic[\"embedding_size\"]):\n expanded_masks.append(mask)\n # repeat it so that it matches the 8 dimensional embedding layer\n expanded_masks = np.concatenate(expanded_masks, axis=-1)\n expanded_masks = tf.convert_to_tensor(expanded_masks)\n expanded_masks = tf.cast(expanded_masks, dtype=\"float32\")\n return expanded_masks\n\n def update_embeddings(self, embeddings: \"tf.Tensor\", gradients: \"tf.Tensor\", mask: \"tf.Tensor\") -> \"tf.Tensor\":\n \"\"\"\n Update embeddings.\n\n :param embeddings: Embeddings produced by the data from passing it through the first embedding layer of MalConv\n :param gradients: Gradients to update the embeddings\n :param mask: Tensor with 1s on the embeddings we modify, 0s elsewhere.\n :return embeddings: Updated embeddings wrt the adversarial objective.\n \"\"\"\n import tensorflow as tf\n\n if self.use_sign:\n gradients = tf.sign(gradients)\n embeddings = embeddings + self.l_r * gradients * mask\n return embeddings\n\n def get_adv_malware(\n self,\n embeddings: \"tf.Tensor\",\n data: np.ndarray,\n labels: np.ndarray,\n fsize: np.ndarray,\n perturbation_size: np.ndarray,\n perturb_sizes: list[list[int]] | None = None,\n perturb_starts: list[list[int]] | None = None,\n ) -> np.ndarray:\n \"\"\"\n Project the adversarial example back though the closest l2 vector.\n\n :param embeddings: Adversarially optimised embeddings\n :param labels: Labels for the data\n :param fsize: Size of the original malware\n :param data: Original data in the feature space\n :param perturbation_size: Size of the l0 attack to append (if any).\n :param perturb_sizes: List, with each element itself being a list of the start positions of a\n perturbation regions in a sample\n :param perturb_starts: List, with each element itself being a list of the start positions of a\n start of the perturbation regions in a sample\n\n :return data: Numpy array with valid data samples.\n \"\"\"\n import tensorflow as tf\n\n for i, label in enumerate(labels):\n if label == 1:\n total_diff = 0\n m = tf.constant([1, self.param_dic[\"input_dim\"], 1], tf.int32)\n\n if perturb_sizes is not None and perturb_starts is not None:\n for size, start in zip(perturb_sizes[i], perturb_starts[i]):\n expanded = tf.tile(tf.expand_dims(embeddings[i, start : start + size, :], axis=1), m)\n diff = tf.norm((expanded - self.embedding_weights), axis=-1)\n diff = tf.math.argmin(diff, axis=-1)\n data[i, start : start + size] = diff\n total_diff += len(diff)\n expanded = tf.tile(\n tf.expand_dims(embeddings[i, fsize[i] : fsize[i] + perturbation_size[i], :], axis=1), m\n )\n diff = tf.norm((expanded - self.embedding_weights), axis=-1)\n diff = tf.math.argmin(diff, axis=-1)\n data[i, fsize[i] : fsize[i] + perturbation_size[i]] = diff\n total_diff += len(diff)\n\n # sanity check that the total number of perturbed features does\n # not exceed the total perturbation budget\n assert total_diff == self.total_perturbation[i]\n return data\n\n @staticmethod\n def pull_out_adversarial_malware(\n x: np.ndarray,\n y: np.ndarray,\n sample_sizes: np.ndarray,\n initial_dtype: np.dtype,\n input_perturb_sizes: list[list[int]] | None = None,\n input_perturb_starts: list[list[int]] | None = None,\n ) -> (\n tuple[np.ndarray, np.ndarray, np.ndarray]\n | tuple[np.ndarray, np.ndarray, np.ndarray, list[list[int]], list[list[int]]]\n ):\n \"\"\"\n Fetches the malware from the data\n\n :param x: Batch of data which will contain a mix of adversarial examples and unperturbed data.\n :param y: Labels indicating which are valid adversarial examples or not.\n :param initial_dtype: Data can be given in a few formats (uin16, float, etc.) so use initial_dtype\n to make the returned sample match the original.\n :param sample_sizes: Size of the original data files\n :param input_perturb_sizes: List of length batch size, each element is in itself a list containing\n the size of the allowable perturbation region\n :param input_perturb_starts: List of length batch size, each element is in itself a list containing\n the start of perturbation region.\n\n :return adv_x: array composed of only the data that we can make valid adversarial examples from.\n :return adv_y: labels, all ones.\n \"\"\"\n num_of_malware_samples = int(np.sum(y))\n\n # make array and allocate, much faster than appending to list and converting\n adv_x = np.zeros((num_of_malware_samples, x.shape[1]), dtype=initial_dtype)\n adv_y = np.ones((num_of_malware_samples, 1))\n\n adv_sample_sizes = np.zeros((num_of_malware_samples,), dtype=int)\n perturb_sizes = []\n perturb_starts = []\n\n j = 0\n for i, label in enumerate(y):\n if label == 1:\n adv_x[j] = x[i]\n adv_sample_sizes[j] = int(sample_sizes[i])\n j += 1\n if input_perturb_sizes is not None and input_perturb_starts is not None:\n perturb_sizes.append(input_perturb_sizes[i])\n perturb_starts.append(input_perturb_starts[i])\n\n if input_perturb_sizes is not None and input_perturb_starts is not None:\n return adv_x, adv_y, adv_sample_sizes, perturb_starts, perturb_sizes\n\n return adv_x, adv_y, adv_sample_sizes\n\n def compute_perturbation_regions(\n self,\n input_perturbation_size: np.ndarray,\n input_perturb_sizes: list[list[int]],\n automatically_append: bool,\n ) -> tuple[np.ndarray, list[list[int]]]:\n \"\"\"\n Based on the l0 budget and the provided allowable perturbation regions we iteratively mark regions of the PE\n file for modification until we exhaust our budget.\n\n :param input_perturb_sizes: The size of the regions we can perturb.\n :param input_perturbation_size: The total amount of perturbation allowed on a specific sample.\n :param automatically_append: If we want to automatically append unused perturbation on the end of the malware.\n :return perturbation_size: Remaining perturbation (if any)\n :return perturb_sizes: Potentially adjusted sizes of the locations in the PE file we can perturb.\n \"\"\"\n perturb_sizes = input_perturb_sizes.copy()\n perturbation_size = input_perturbation_size.copy()\n\n # reduce the perturbation we add at the end if we have perturbation to add in the malware itself and reduce the\n # sizes given in input_perturb_sizes if it exceeds the total input_perturbation_size\n for i, section_sizes in enumerate(perturb_sizes):\n for j, size in enumerate(section_sizes):\n if perturbation_size[i] - size >= 0:\n logger.info(\"on sample %d allocate %d in perturb region\", i, size)\n perturbation_size[i] = perturbation_size[i] - size\n else: # run out of l0 budget.\n excess = np.abs(perturbation_size[i] - size) # amount of overspill\n perturbation_size[i] = perturbation_size[i] - size\n section_sizes[j] = size - excess\n # update the perturb sizes\n\n logger.info(\"on sample %d ran out of l0, update to %d from %d\", i, section_sizes[j], size)\n\n perturb_sizes[i] = section_sizes\n perturbation_size[i] = 0\n perturbation_size = np.where(perturbation_size < 0, 0, perturbation_size)\n\n if not automatically_append:\n # if we do not want to automatically append then set the remaining perturbation to 0\n perturbation_size = np.zeros_like(perturbation_size)\n # total_perturbation is now sample dependant so reassign.\n total_perturbation = np.zeros_like(perturbation_size)\n for i in range(len(perturbation_size)):\n total_perturbation[i] = np.sum(perturb_sizes[i])\n self.total_perturbation = total_perturbation\n return perturbation_size, perturb_sizes\n\n def pull_out_valid_samples(\n self,\n x: np.ndarray,\n y: np.ndarray,\n sample_sizes: np.ndarray,\n automatically_append: bool = True,\n perturb_sizes: list[list[int]] | None = None,\n perturb_starts: list[list[int]] | None = None,\n ) -> (\n tuple[np.ndarray, np.ndarray, np.ndarray]\n | tuple[np.ndarray, np.ndarray, np.ndarray, list[list[int]], list[list[int]]]\n ):\n \"\"\"\n Filters the input data for samples that can be made adversarial.\n\n :param x: Array with input data.\n :param y: Labels to make sure the benign files are zero masked.\n :param sample_sizes: The size of the original file, before it was padded to the input size required by MalConv\n :param automatically_append: Whether to automatically append extra spare perturbation at the end of the file.\n :param perturb_sizes: List of length batch size, each element is in itself a list containing\n the size of the allowable perturbation region\n :param perturb_starts: List of length batch size, each element is in itself a list containing\n the start of perturbation region.\n\n \"\"\"\n initial_dtype = x.dtype\n\n perturbation_size = np.zeros(len(sample_sizes), dtype=int)\n for i, sample_size in enumerate(sample_sizes):\n if self.l_0 < 1: # l0 is a fraction of the filesize\n perturbation_size[i] = int(sample_size * self.l_0)\n else: # or l0 is interpreted as total perturbation size\n perturbation_size[i] = int(self.l_0)\n\n if perturb_sizes is not None and perturb_starts is not None:\n perturbation_size, perturb_sizes = self.compute_perturbation_regions(\n perturbation_size, perturb_sizes, automatically_append\n )\n\n y = self.check_valid_size(y, sample_sizes, perturbation_size)\n if perturb_sizes is not None and perturb_starts is not None:\n return self.pull_out_adversarial_malware(x, y, sample_sizes, initial_dtype, perturb_sizes, perturb_starts)\n\n return self.pull_out_adversarial_malware(x, y, sample_sizes, initial_dtype)\n\n def generate(\n self,\n x: np.ndarray,\n y: np.ndarray | None = None,\n sample_sizes: np.ndarray | None = None,\n automatically_append: bool = True,\n verify_input_data: bool = True,\n perturb_sizes: list[list[int]] | None = None,\n perturb_starts: list[list[int]] | None = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Generates the adversarial examples. x needs to be composed of valid files by default which can support the\n adversarial perturbation and so are malicious and can support the assigned L0 budget. They can be obtained by\n using `pull_out_valid_samples` on the data.\n\n This check on the input data can be over-ridden by toggling the flag verify_input_data\n This will result in only the data which can be made adversarial being perturbed and so the resulting batch will\n be a mixture of adversarial and unperturbed data.\n\n To assign the L0 budget we go through each list in perturb_sizes and perturb_starts in order, and\n assign the budget based on the sizes given until the l0 budget is exhausted.\n\n After all the regions marked in perturb_sizes and perturb_starts have been assigned and automatically_append is\n set to true and remaining l0 perturbation the extra perturbation is added at the end in an append style attack.\n\n :param x: An array with input data.\n :param y: (N, 1) binary labels to make sure the benign files are zero masked.\n :param sample_sizes: The size of the original file, before it was padded to the input size required by MalConv\n :param automatically_append: Whether to automatically append extra spare perturbation at the end of the file.\n :param verify_input_data: If to check that all the data supplied is valid for adversarial perturbations.\n :param perturb_sizes: A list of length batch size, each element is in itself a list containing\n the size of the allowable perturbation region\n :param perturb_starts: A list of length batch size, each element is in itself a list containing\n the start of perturbation region.\n :return x: our adversarial examples.\n \"\"\"\n import tensorflow as tf\n\n # make copy so original data is not modified.\n adv_x = x.copy()\n if sample_sizes is None: # pragma: no cover\n raise ValueError(\"The size of the original files needs to be supplied\")\n if y is None: # pragma: no cover\n raise ValueError(\"Labels need to be provided so we only modify the malware\")\n\n # check that the dimensions all match\n assert len(adv_x) == len(y)\n assert len(y) == len(sample_sizes)\n if perturb_sizes is not None:\n assert len(y) == len(perturb_sizes)\n if perturb_starts is not None:\n assert len(y) == len(perturb_starts)\n\n # check that if perturb_starts is provided perturb_sizes is also provided and vise versa\n if perturb_starts is not None:\n assert perturb_sizes is not None\n if perturb_sizes is not None:\n assert perturb_starts is not None\n\n # if we do not automatically append then make sure that we have supplied\n # start and end positions for the perturbation.\n if not automatically_append:\n assert perturb_sizes is not None\n assert perturb_starts is not None\n\n perturbation_size = np.zeros(len(sample_sizes), dtype=int)\n for i, sample_size in enumerate(sample_sizes):\n if self.l_0 < 1: # l0 is a fraction of the filesize\n perturbation_size[i] = int(sample_size * self.l_0)\n else: # or l0 is interpreted as total perturbation size\n perturbation_size[i] = int(self.l_0)\n self.total_perturbation = np.copy(perturbation_size)\n\n if perturb_sizes is not None and perturb_starts is not None:\n perturbation_size, perturb_sizes = self.compute_perturbation_regions(\n perturbation_size, perturb_sizes, automatically_append\n )\n\n y = self.check_valid_size(y, sample_sizes, perturbation_size)\n\n if verify_input_data:\n if np.sum(y) != len(y):\n raise ValueError( # pragma: no cover\n f\"{len(y) - np.sum(y)} invalid samples found in batch which cannot support the assigned \"\n f\"perturbation or are benign To filter for samples that can be processed use \"\n f\"pull_out_valid_samples on the samples. Checking can be disabled by using verify_input_data\"\n )\n\n adv_x = self.initialise_sample(\n adv_x, y, sample_sizes, perturbation_size, perturb_sizes=perturb_sizes, perturb_starts=perturb_starts\n )\n\n mask = self.generate_mask(\n adv_x, y, sample_sizes, perturbation_size, perturb_sizes=perturb_sizes, perturb_starts=perturb_starts\n )\n\n embeddings = tf.nn.embedding_lookup(params=self.embedding_weights, ids=adv_x.astype(\"int32\"))\n\n for _ in trange(self.num_of_iterations, desc=\"PE Adv. Malware\", disable=not self.verbose):\n gradients = self.estimator.class_gradient(embeddings, label=0)\n # go from (bsize x 1 x features x embedding size) -> (bsize x features x embedding size) in a\n # framework-agnostic manner.\n gradients = gradients[:, 0, :, :]\n gradients = -1 * gradients\n embeddings = self.update_embeddings(embeddings, gradients, mask)\n\n adv_x = self.get_adv_malware(\n embeddings=embeddings,\n data=adv_x,\n labels=y,\n fsize=sample_sizes,\n perturbation_size=perturbation_size,\n perturb_sizes=perturb_sizes,\n perturb_starts=perturb_starts,\n )\n\n return adv_x\n\n @staticmethod\n def process_file(\n filepath: str, padding_char: int = 256, maxlen: int = 2**20\n ) -> tuple[np.ndarray, int]: # pragma: no cover\n \"\"\"\n Go from raw file to numpy array.\n\n :param filepath: Path to the file we convert to a numpy array\n :param padding_char: The char to use to pad the input if it is shorter than maxlen\n :param maxlen: Maximum size of the file processed by the model. Currently set to 1MB\n :return data: A numpy array of the PE file\n :return size_of_original_file: Size of the PE file\n \"\"\"\n with open(filepath, \"rb\") as file:\n open_file = file.read()\n size_of_original_file = len(open_file)\n\n data = np.ones((maxlen,), dtype=np.uint16) * padding_char\n selected_bytes = np.frombuffer(open_file[:maxlen], dtype=np.uint8)\n data[: len(selected_bytes)] = selected_bytes\n\n return data, size_of_original_file\n\n @staticmethod\n def get_peinfo(\n filepath: str, save_to_json_path: str | None = None\n ) -> tuple[list[int], list[int]]: # pragma: no cover\n \"\"\"\n Given a PE file we extract out the section information to determine the slack regions in the file.\n We return two lists 1) with the start location of the slack regions and 2) with the size of the slack region.\n We are using the lief library (https://github.com/lief-project/LIEF) to manipulate the PE file.\n\n :param filepath: Path to file we want to analyse with pedump and get the section information.\n :param save_to_json_path: (Optional) if we want to save the results of pedump to a json file, provide the path.\n :return start_of_slack: A list with the slack starts\n :return size_of_slack: A list with the slack start positions\n \"\"\"\n import lief # pylint: disable=import-outside-toplevel\n\n start_of_slack = []\n size_of_slack = []\n\n cleaned_dump = {}\n\n binary_load = lief.parse(filepath)\n if binary_load is not None:\n binary = binary_load\n else:\n raise ValueError(\"Failed to load binary.\")\n\n for section in binary.sections:\n section_info = {}\n slack = section.sizeof_raw_data - section.virtual_size # type: ignore\n section_info[\"PointerToRawData\"] = section.pointerto_raw_data # type: ignore\n section_info[\"VirtualAddress\"] = section.virtual_size # type: ignore\n section_info[\"SizeOfRawData\"] = section.sizeof_raw_data # type: ignore\n cleaned_dump[section.name] = section_info\n if slack > 0:\n size_of_slack.append(slack)\n start_of_slack.append(section.pointerto_raw_data + section.virtual_size) # type: ignore\n\n if save_to_json_path is not None:\n with open(save_to_json_path, \"w\", encoding=\"utf8\") as outfile:\n json.dump(cleaned_dump, outfile, indent=4, sort_keys=True)\n\n return start_of_slack, size_of_slack\n\n def insert_section(\n self,\n datapoint: list[int] | str,\n sample_size: int | None = None,\n padding_char: int = 256,\n maxlen: int = 2**20,\n bytes_to_assign: int | None = None,\n verbose: bool = False,\n ) -> (\n tuple[np.ndarray, int, int, int, list[int], list[int]] | tuple[None, None, None, None, None, None]\n ): # pragma: no cover\n \"\"\"\n Create a new section in a PE file that the attacker can perturb to create an adversarial example.\n we are using the lief library (https://github.com/lief-project/LIEF) to manipulate the PE file.\n\n :param datapoint: either 1) path to file we want to analyse with lief and get the section information.\n or 2) list of ints that can be processed by lief.\n\n If we have already pre-processed the file into a numpy array, we convert it to a form\n that can be read by lief.\n eg, if we have it as a numpy array this could be done by:\n\n datapoint = datapoint[0:size] # size is the original size of the malware file\n datapoint = datapoint.astype('uint8')\n datapoint = datapoint.tolist()\n :param sample_size: Size of the original datapoint. Only if it is an array and the l0 budget is fractional\n :param padding_char: The char to use to pad the file to be of length maxlen\n :param maxlen: Maximum length of the data that the MalConv model can process\n :param bytes_to_assign: (Optional) how many bytes we wish to specify when inserting a new section.\n If unspecified the whole l0 budget will be used on a single section.\n :param verbose: lief outputs a lot to the console, particularly if we are processing many files.\n By default, suppress printing of messages. Can be toggled on/off by True/False\n :return manipulated_data: Executable with section inserted and turned into a numpy array of\n the appropriate size.\n :return len(manipulated_file): Size of original file\n :return information_on_section.pointerto_raw_data: The start of the inserted section\n :return information_on_section.virtual_size: Size of the inserted section\n :return size_of_slack: Size of slack regions in this executable (including from the section we just inserted)\n :return start_of_slack: Start of slack regions in this executable (including from the section we just inserted)\n \"\"\"\n\n import lief # pylint: disable=import-outside-toplevel\n\n if not verbose:\n lief.logging.disable()\n\n binary_parse = lief.PE.parse(datapoint)\n if binary_parse is not None:\n binary = binary_parse\n else:\n raise ValueError(\"Failed to load binary.\")\n\n name_in_use = True\n while name_in_use:\n new_section_name = \".\" + \"\".join(chr(random.randrange(ord(\"a\"), ord(\"z\"))) for _ in range(5))\n name_in_use = False\n\n # check if the random name is already by chance in use\n for section in binary.sections:\n if new_section_name == section.name:\n name_in_use = True\n\n new_section = lief.PE.Section(new_section_name)\n\n if bytes_to_assign is None:\n if self.l_0 < 1: # l0 is a fraction of the file size\n # if it's a filepath we need to get the file size\n if isinstance(datapoint, str):\n with open(datapoint, \"rb\") as file:\n open_file = file.read()\n sample_size = len(open_file)\n else:\n if sample_size is None:\n raise ValueError(\n \"if the data is an array and the l0 budget is fractional \"\n \"the sample size must be provided\"\n )\n\n perturbation_size = int(sample_size * self.l_0)\n else: # or l0 is interpreted as total perturbation size\n perturbation_size = int(self.l_0)\n new_section.content = [random.randint(0, 255) for _ in range(perturbation_size)] # type: ignore\n else:\n new_section.content = [random.randint(0, 255) for _ in range(bytes_to_assign)] # type: ignore\n\n # we add the new section at the end of the existing sections\n section_end_points = []\n for section in binary.sections:\n section_end_points.append(section.virtual_address + section.size)\n\n new_section.virtual_address = max(section_end_points)\n\n binary.add_section(\n new_section,\n random.choice(\n [\n lief.PE.SECTION_TYPES.BSS,\n lief.PE.SECTION_TYPES.DATA,\n lief.PE.SECTION_TYPES.EXPORT,\n lief.PE.SECTION_TYPES.IDATA,\n lief.PE.SECTION_TYPES.RELOCATION,\n lief.PE.SECTION_TYPES.RESOURCE,\n lief.PE.SECTION_TYPES.TEXT,\n lief.PE.SECTION_TYPES.UNKNOWN,\n ]\n ),\n )\n\n information_on_section = binary.get_section(new_section_name)\n\n size_of_slack = []\n start_of_slack = []\n for section in binary.sections:\n slack = section.sizeof_raw_data - section.virtual_size\n if slack > 0:\n size_of_slack.append(slack)\n start_of_slack.append(section.pointerto_raw_data + section.virtual_size)\n\n builder = lief.PE.Builder(binary)\n builder.build()\n\n manipulated_file = np.array(builder.get_build(), dtype=np.uint8)\n\n manipulated_data = np.ones((maxlen,), dtype=np.uint16) * padding_char\n\n # Only process files which are less than the max file size supported\n if len(manipulated_file) < maxlen:\n manipulated_data[: len(manipulated_file)] = manipulated_file[:maxlen]\n\n return (\n manipulated_data,\n len(manipulated_file),\n information_on_section.pointerto_raw_data,\n information_on_section.virtual_size,\n size_of_slack,\n start_of_slack,\n )\n return None, None, None, None, None, None\n\n @staticmethod\n def get_dos_locations(x: np.ndarray) -> tuple[list[list[int]], list[list[int]]]:\n \"\"\"\n We identify the regions in the DOS header which we can perturb adversarially.\n\n There are a series of \"magic numbers\" in this method which relate to the structure of the PE file.\n 1) mz_offset = 2: the first two bytes of a PE are fixed as MZ.\n 2) 0x3C: offset to the pointer to the PE header. The pointer is 4 bytes long.\n 3) 0x40: end of the pointer to the PE header.\n\n :return batch_of_starts: A list of start locations we can perturb.\n This will always have the same value of 2 and 64.\n :return batch_of_sizes: Size of the perturbations we can carry out.\n :return batch_of_starts: Start locations which we can perturb.\n \"\"\"\n batch_of_starts = []\n batch_of_sizes = []\n mz_offset = 2\n\n for i in range(len(x)):\n size = []\n start = []\n\n pointer_to_pe_header = x[i, int(0x3C) : int(0x40)].astype(np.uint8)\n\n # combine 4 unint8 bytes into unit32\n pointer_to_pe_header = (\n pointer_to_pe_header[3] << 24\n | pointer_to_pe_header[2] << 16\n | pointer_to_pe_header[1] << 8\n | pointer_to_pe_header[0]\n )\n\n size.append(int(0x3C) - mz_offset)\n start.append(mz_offset)\n\n size.append(int(pointer_to_pe_header) - int(0x40) - 1)\n start.append(int(0x40))\n\n batch_of_starts.append(start)\n batch_of_sizes.append(size)\n\n return batch_of_starts, batch_of_sizes\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/pixel_threshold.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Threshold Attack and Pixel Attack.\nThe Pixel Attack is a generalisation of One Pixel Attack.\n\n| One Pixel Attack Paper link: https://arxiv.org/ans/1710.08864\n| Pixel and Threshold Attack Paper link: https://arxiv.org/abs/1906.06026\n\"\"\"\n# pylint: disable=wrong-import-position\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom itertools import product\nfrom packaging.version import parse\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\n# Currently, a modified version of SciPy's differential evolution is used in\n# code. An ideal version would be using the import as follows,\n# from scipy.optimize import differential_evolution\n# In the meantime, the modified implementation is used which is defined in the\n# lines `453-1457`.\n# Otherwise, may use Tensorflow's implementation of DE.\n\nfrom six import string_types\nimport scipy\nfrom scipy._lib._util import check_random_state\n\nscipy_version = list(parse(scipy.__version__.lower()).release)\nif scipy_version[1] >= 8:\n from scipy.optimize._optimize import _status_message\nelse:\n from scipy.optimize.optimize import _status_message\nfrom scipy.optimize import OptimizeResult, minimize # noqa\nfrom tqdm.auto import tqdm # noqa\n\nfrom art.config import ART_NUMPY_DTYPE # noqa\nfrom art.attacks.attack import EvasionAttack # noqa\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin # noqa\nfrom art.estimators.classification.classifier import ClassifierMixin # noqa\nfrom art.utils import check_and_transform_label_format # noqa\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass PixelThreshold(EvasionAttack):\n \"\"\"\n These attacks were originally implemented by Vargas et al. (2019) & Su et al.(2019).\n\n | One Pixel Attack Paper link: https://arxiv.org/abs/1710.08864\n | Pixel and Threshold Attack Paper link: https://arxiv.org/abs/1906.06026\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\"th\", \"es\", \"max_iter\", \"targeted\", \"verbose\", \"verbose_es\"]\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n th: int | None = None,\n es: int = 0,\n max_iter: int = 100,\n targeted: bool = False,\n verbose: bool = True,\n verbose_es: bool = False,\n ) -> None:\n \"\"\"\n Create a :class:`.PixelThreshold` instance.\n\n :param classifier: A trained classifier.\n :param th: threshold value of the Pixel/ Threshold attack. th=None indicates finding a minimum threshold.\n :param es: Indicates whether the attack uses CMAES (0) or DE (1) as Evolutionary Strategy.\n :param max_iter: Sets the Maximum iterations to run the Evolutionary Strategies for optimisation.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param verbose: Print verbose messages of ES and show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self._project = True\n self.type_attack = -1\n self.th = th # pylint: disable=invalid-name\n self.es = es # pylint: disable=invalid-name\n self.max_iter = max_iter\n self._targeted = targeted\n self.verbose = verbose\n self.verbose_es = verbose_es\n self.rescale = False\n PixelThreshold._check_params(self)\n\n if self.estimator.channels_first:\n self.img_rows = self.estimator.input_shape[-2]\n self.img_cols = self.estimator.input_shape[-1]\n self.img_channels = self.estimator.input_shape[-3]\n else:\n self.img_rows = self.estimator.input_shape[-3]\n self.img_cols = self.estimator.input_shape[-2]\n self.img_channels = self.estimator.input_shape[-1]\n\n def _check_params(self) -> None:\n if self.th is not None:\n if self.th <= 0:\n raise ValueError(\"The perturbation size `eps` has to be positive.\")\n\n if not isinstance(self.es, int):\n raise ValueError(\"The flag `es` has to be of type int.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The flag `targeted` has to be of type bool.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The flag `verbose` has to be of type bool.\")\n\n if not isinstance(self.verbose_es, bool): # pragma: no cover\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n if self.estimator.clip_values is None:\n raise ValueError(\"This attack requires estimator clip values to be defined.\")\n\n def rescale_input(self, x):\n \"\"\"Rescale inputs\"\"\"\n x = x.astype(ART_NUMPY_DTYPE) / 255.0\n x = (x * (self.estimator.clip_values[1] - self.estimator.clip_values[0])) + self.estimator.clip_values[0]\n return x\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param max_iter: Maximum number of optimisation iterations.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=False)\n\n if y is None:\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n y = np.argmax(self.estimator.predict(x), axis=1)\n else:\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n if y.ndim > 1 and y.shape[1] > 1:\n y = np.argmax(y, axis=1)\n\n y = y.flatten() # type: ignore\n\n if self.th is None:\n logger.info(\n \"Performing minimal perturbation Attack. \\\n This could take long time to process. \\\n For sanity check, pass th=10 to the Attack instance.\"\n )\n\n # NOTE: Pixel and Threshold Attacks are well-defined for unprocessed images where the pixel values are,\n # 8-Bit color i.e., the pixel values are np.uint8 in range [0, 255].\n\n # TO-DO: Better checking of input image.\n # All other cases not tested needs the images to be rescaled to [0, 255].\n if self.estimator.clip_values[1] != 255.0:\n self.rescale = True\n x = (x - self.estimator.clip_values[0]) / (self.estimator.clip_values[1] - self.estimator.clip_values[0])\n x = x * 255.0\n\n x = x.astype(ART_NUMPY_DTYPE)\n\n adv_x_best = []\n self.adv_th = []\n for image, target_class in tqdm(zip(x, y), desc=\"Pixel threshold\", disable=not self.verbose): # type: ignore\n\n if self.th is None:\n\n min_th = -1\n start, end = 1, 127\n\n image_result = image\n\n while True: # pragma: no cover\n\n threshold = (start + end) // 2\n success, trial_image_result = self._attack(image, target_class, threshold)\n\n if success:\n image_result = trial_image_result\n end = threshold - 1\n min_th = threshold\n else:\n start = threshold + 1\n\n if end < start:\n break\n\n self.adv_th = [min_th]\n\n else:\n\n success, image_result = self._attack(image, target_class, self.th)\n\n if not success:\n image_result = image\n\n adv_x_best += [image_result]\n\n adv_x_best_array = np.array(adv_x_best)\n\n if self.rescale:\n adv_x_best_array = self.rescale_input(adv_x_best_array)\n\n return adv_x_best_array\n\n def _get_bounds(self, img: np.ndarray, limit) -> tuple[list[list], list]:\n \"\"\"\n Define the bounds for the image `img` within the limits `limit`.\n \"\"\"\n\n def bound_limit(value):\n return np.clip(value - limit, 0, 255), np.clip(value + limit, 0, 255)\n\n minbounds, maxbounds, bounds, initial = [], [], [], []\n\n for i, j, k in product(range(img.shape[-3]), range(img.shape[-2]), range(img.shape[-1])):\n temp = img[i, j, k]\n initial += [temp]\n bound = bound_limit(temp)\n if self.es == 0: # pragma: no cover\n minbounds += [bound[0]]\n maxbounds += [bound[1]]\n else:\n bounds += [bound]\n if self.es == 0:\n bounds = [minbounds, maxbounds]\n\n return bounds, initial\n\n def _perturb_image(self, x: np.ndarray, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Perturbs the given image `img` with the given perturbation `x`.\n \"\"\"\n return img\n\n def _attack_success(self, adv_x, x, target_class):\n \"\"\"\n Checks whether the given perturbation `adv_x` for the image `img` is successful.\n \"\"\"\n adv = self._perturb_image(adv_x, x)\n\n if self.rescale:\n adv = self.rescale_input(adv)\n\n predicted_class = np.argmax(self.estimator.predict(adv)[0])\n return bool(\n (self.targeted and predicted_class == target_class)\n or (not self.targeted and predicted_class != target_class)\n )\n\n def _attack(self, image: np.ndarray, target_class: np.ndarray, limit: int) -> tuple[bool, np.ndarray]:\n \"\"\"\n Attack the given image `image` with the threshold `limit` for the `target_class` which is true label for\n untargeted attack and targeted label for targeted attack.\n \"\"\"\n bounds, initial = self._get_bounds(image, limit)\n\n def predict_fn(x):\n adv = self._perturb_image(x, image)\n\n if self.rescale:\n adv = self.rescale_input(adv)\n\n predictions = self.estimator.predict(adv)[:, target_class]\n return predictions if not self.targeted else 1 - predictions\n\n def callback_fn(x, convergence=None): # pylint: disable=inconsistent-return-statements,unused-argument\n if self.es == 0:\n if self._attack_success(x.result[0], image, target_class):\n raise CMAEarlyStoppingException(\"Attack Completed :) Earlier than expected\")\n else:\n return self._attack_success(x, image, target_class)\n\n if self.es == 0:\n from cma import CMAOptions\n\n opts = CMAOptions()\n if not self.verbose_es:\n opts.set(\"verbose\", -9)\n opts.set(\"verb_disp\", 40000)\n opts.set(\"verb_log\", 40000)\n opts.set(\"verb_time\", False)\n\n opts.set(\"bounds\", bounds)\n\n if self.type_attack == 0:\n std = 63\n else: # pragma: no cover\n std = limit\n\n from cma import CMAEvolutionStrategy\n\n strategy = CMAEvolutionStrategy(initial, std / 4, opts)\n\n try:\n strategy.optimize(\n predict_fn,\n maxfun=max(1, 400 // len(bounds)) * len(bounds) * 100,\n callback=callback_fn,\n iterations=self.max_iter,\n )\n except CMAEarlyStoppingException as err:\n if self.verbose_es: # pragma: no cover\n logger.info(err)\n\n adv_x = strategy.result[0]\n else:\n strategy = differential_evolution(\n predict_fn,\n bounds,\n disp=self.verbose_es,\n maxiter=self.max_iter,\n popsize=max(1, 400 // len(bounds)),\n recombination=1,\n atol=-1,\n callback=callback_fn,\n polish=False,\n )\n adv_x = strategy.x\n\n if self._attack_success(adv_x, image, target_class):\n return True, self._perturb_image(adv_x, image)[0]\n\n return False, image\n\n\nclass PixelAttack(PixelThreshold):\n \"\"\"\n This attack was originally implemented by Vargas et al. (2019). It is generalisation of One Pixel Attack originally\n implemented by Su et al. (2019).\n\n | One Pixel Attack Paper link: https://arxiv.org/abs/1710.08864\n | Pixel Attack Paper link: https://arxiv.org/abs/1906.06026\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n th: int | None = None,\n es: int = 1,\n max_iter: int = 100,\n targeted: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create a :class:`.PixelAttack` instance.\n\n :param classifier: A trained classifier.\n :param th: threshold value of the Pixel/ Threshold attack. th=None indicates finding a minimum threshold.\n :param es: Indicates whether the attack uses CMAES (0) or DE (1) as Evolutionary Strategy.\n :param max_iter: Sets the Maximum iterations to run the Evolutionary Strategies for optimisation.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param verbose: Indicates whether to print verbose messages of ES used.\n \"\"\"\n super().__init__(classifier, th, es, max_iter, targeted, verbose)\n self.type_attack = 0\n\n def _perturb_image(self, x: np.ndarray, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Perturbs the given image `img` with the given perturbation `x`.\n \"\"\"\n if x.ndim < 2:\n x = np.array([x])\n imgs = np.tile(img, [len(x)] + [1] * (x.ndim + 1))\n x = x.astype(int)\n for adv, image in zip(x, imgs):\n for pixel in np.split(adv, len(adv) // (2 + self.img_channels)):\n x_pos, y_pos, *rgb = pixel\n if not self.estimator.channels_first:\n image[x_pos % self.img_rows, y_pos % self.img_cols] = rgb\n else:\n image[:, x_pos % self.img_rows, y_pos % self.img_cols] = rgb\n return imgs\n\n def _get_bounds(self, img: np.ndarray, limit) -> tuple[list[list], list]:\n \"\"\"\n Define the bounds for the image `img` within the limits `limit`.\n \"\"\"\n initial: list[int] = []\n bounds: list[list[int]]\n if self.es == 0:\n for count, (i, j) in enumerate(product(range(self.img_rows), range(self.img_cols))):\n initial += [i, j]\n for k in range(self.img_channels):\n if not self.estimator.channels_first:\n initial += [img[i, j, k]]\n else:\n initial += [img[k, i, j]]\n\n if count == limit - 1:\n break\n\n min_bounds = [0, 0]\n for _ in range(self.img_channels):\n min_bounds += [0]\n min_bounds = min_bounds * limit\n max_bounds = [self.img_rows, self.img_cols]\n for _ in range(self.img_channels):\n max_bounds += [255]\n max_bounds = max_bounds * limit\n bounds = [min_bounds, max_bounds]\n else:\n bounds = [[0, self.img_rows], [0, self.img_cols]]\n for _ in range(self.img_channels):\n bounds += [[0, 255]]\n bounds = bounds * limit\n return bounds, initial\n\n\nclass ThresholdAttack(PixelThreshold):\n \"\"\"\n This attack was originally implemented by Vargas et al. (2019).\n\n | Paper link: https://arxiv.org/abs/1906.06026\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n th: int | None = None,\n es: int = 0,\n max_iter: int = 100,\n targeted: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create a :class:`.PixelThreshold` instance.\n\n :param classifier: A trained classifier.\n :param th: threshold value of the Pixel/ Threshold attack. th=None indicates finding a minimum threshold.\n :param es: Indicates whether the attack uses CMAES (0) or DE (1) as Evolutionary Strategy.\n :param max_iter: Sets the Maximum iterations to run the Evolutionary Strategies for optimisation.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param verbose: Indicates whether to print verbose messages of ES used.\n \"\"\"\n super().__init__(classifier, th, es, max_iter, targeted, verbose)\n self.type_attack = 1\n\n def _perturb_image(self, x: np.ndarray, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Perturbs the given image `img` with the given perturbation `x`.\n \"\"\"\n if x.ndim < 2:\n x = x[None, ...]\n imgs = np.tile(img, [len(x)] + [1] * (x.ndim + 1))\n x = x.astype(int)\n for adv, image in zip(x, imgs):\n for count, (i, j, k) in enumerate(\n product(\n range(image.shape[-3]),\n range(image.shape[-2]),\n range(image.shape[-1]),\n )\n ):\n image[i, j, k] = adv[count]\n return imgs\n\n\nclass CMAEarlyStoppingException(Exception):\n \"\"\"Raised when CMA is stopping early after successful optimisation.\"\"\"\n\n pass\n\n\n# TODO: Make the attack compatible with current version of SciPy Optimize\n# Differential Evolution\n# pylint: disable=pointless-string-statemen\n\"\"\"\nA slight modification to Scipy's implementation of differential evolution.\nTo speed up predictions, the entire parameters array is passed to `self.func`,\nwhere a neural network model can batch its computations and execute in parallel\nSearch for `CHANGES` to find all code changes.\n\nDan Kondratyuk 2018\n\nOriginal code adapted from\nhttps://github.com/scipy/scipy/blob/70e61dee181de23fdd8d893eaa9491100e2218d7/scipy/optimize/_differentialevolution.py\n----------\ndifferential_evolution:The differential evolution global optimization algorithm\nAdded by Andrew Nelson 2014\n\"\"\"\n\n# Copyright (c) 2001, 2002 Enthought, Inc.\n# All rights reserved.\n# Copyright (c) 2003-2017 SciPy Developers.\n# All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# a. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# b. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# c. Neither the name of Enthought nor the names of the SciPy Developers\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n# THE POSSIBILITY OF SUCH DAMAGE.\n# SciPy bundles a number of libraries that are compatibly licensed. We list\n# these here.\n# Name: Numpydoc\n# Files: doc/sphinxext/numpydoc/*\n# License: 2-clause BSD\n# For details, see doc/sphinxext/LICENSE.txt\n# Name: scipy-sphinx-theme\n# Files: doc/scipy-sphinx-theme/*\n# License: 3-clause BSD, PSF and Apache 2.0\n# For details, see doc/sphinxext/LICENSE.txt\n# Name: Six\n# Files: scipy/_lib/six.py\n# License: MIT\n# For details, see the header inside scipy/_lib/six.py\n# Name: Decorator\n# Files: scipy/_lib/decorator.py\n# License: 2-clause BSD\n# For details, see the header inside scipy/_lib/decorator.py\n# Name: ID\n# Files: scipy/linalg/src/id_dist/*\n# License: 3-clause BSD\n# For details, see scipy/linalg/src/id_dist/doc/doc.tex\n# Name: L-BFGS-B\n# Files: scipy/optimize/lbfgsb/*\n# License: BSD license\n# For details, see scipy/optimize/lbfgsb/README\n# Name: SuperLU\n# Files: scipy/sparse/linalg/dsolve/SuperLU/*\n# License: 3-clause BSD\n# For details, see scipy/sparse/linalg/dsolve/SuperLU/License.txt\n# Name: ARPACK\n# Files: scipy/sparse/linalg/eigen/arpack/ARPACK/*\n# License: 3-clause BSD\n# For details, see scipy/sparse/linalg/eigen/arpack/ARPACK/COPYING\n# Name: Qhull\n# Files: scipy/spatial/qhull/*\n# License: Qhull license (BSD-like)\n# For details, see scipy/spatial/qhull/COPYING.txt\n# Name: Cephes\n# Files: scipy/special/cephes/*\n# License: 3-clause BSD\n# Distributed under 3-clause BSD license with permission from the author,\n# see https://lists.debian.org/debian-legal/2004/12/msg00295.html\n# Cephes Math Library Release 2.8: June, 2000\n# Copyright 1984, 1995, 2000 by Stephen L. Moshier\n# This software is derived from the Cephes Math Library and is\n# incorporated herein by permission of the author.\n# All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# Name: Faddeeva\n# Files: scipy/special/Faddeeva.*\n# License: MIT\n# Copyright (c) 2012 Massachusetts Institute of Technology\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n__all__ = [\"differential_evolution\"] # pragma: no cover\n\n_MACHEPS = np.finfo(np.float64).eps # pragma: no cover\n\n\ndef differential_evolution( # pragma: no cover\n func,\n bounds,\n args=(),\n strategy=\"best1bin\",\n maxiter=1000,\n popsize=15,\n tol=0.01,\n mutation=(0.5, 1),\n recombination=0.7,\n seed=None,\n callback=None,\n disp=False,\n polish=True,\n init=\"latinhypercube\",\n atol=0,\n):\n \"\"\"Finds the global minimum of a multivariate function.\n Differential Evolution is stochastic in nature (does not use gradient\n methods) to find the minimium, and can search large areas of candidate\n space, but often requires larger numbers of function evaluations than\n conventional gradient based techniques.\n The algorithm is due to Storn and Price [1]_.\n Parameters\n ----------\n func : callable\n The objective function to be minimized. Must be in the form\n ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array\n and ``args`` is a tuple of any additional fixed parameters needed to\n completely specify the function.\n bounds : sequence\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``,\n defining the lower and upper bounds for the optimizing argument of\n `func`. It is required to have ``len(bounds) == len(x)``.\n ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : tuple, optional\n Any additional fixed parameters needed to\n completely specify the objective function.\n strategy : str, optional\n The differential evolution strategy to use. Should be one of:\n - 'best1bin'\n - 'best1exp'\n - 'rand1exp'\n - 'randtobest1exp'\n - 'currenttobest1exp'\n - 'best2exp'\n - 'rand2exp'\n - 'randtobest1bin'\n - 'currenttobest1bin'\n - 'best2bin'\n - 'rand2bin'\n - 'rand1bin'\n The default is 'best1bin'.\n maxiter : int, optional\n The maximum number of generations over which the entire population is\n evolved. The maximum number of function evaluations (with no polishing)\n is: ``(maxiter + 1) * popsize * len(x)``\n popsize : int, optional\n A multiplier for setting the total population size. The population has\n ``popsize * len(x)`` individuals (unless the initial population is\n supplied via the `init` keyword).\n tol : float, optional\n Relative tolerance for convergence, the solving stops when\n ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,\n where and `atol` and `tol` are the absolute and relative tolerance\n respectively.\n mutation : float or tuple(float, float), optional\n The mutation constant. In the literature this is also known as\n differential weight, being denoted by F.\n If specified as a float it should be in the range [0, 2].\n If specified as a tuple ``(min, max)`` dithering is employed. Dithering\n randomly changes the mutation constant on a generation by generation\n basis. The mutation constant for that generation is taken from\n ``U[min, max)``. Dithering can help speed convergence significantly.\n Increasing the mutation constant increases the search radius, but will\n slow down convergence.\n recombination : float, optional\n The recombination constant, should be in the range [0, 1]. In the\n literature this is also known as the crossover probability, being\n denoted by CR. Increasing this value allows a larger number of mutants\n to progress into the next generation, but at the risk of population\n stability.\n seed : int or `np.random.RandomState`, optional\n If `seed` is not specified the `np.RandomState` singleton is used.\n If `seed` is an int, a new `np.random.RandomState` instance is used,\n seeded with seed.\n If `seed` is already a `np.random.RandomState instance`, then that\n `np.random.RandomState` instance is used.\n Specify `seed` for repeatable minimizations.\n disp : bool, optional\n Display status messages\n callback : callable, `callback(xk, convergence=val)`, optional\n A function to follow the progress of the minimization. ``xk`` is\n the current value of ``x0``. ``val`` represents the fractional\n value of the population convergence. When ``val`` is greater than one\n the function halts. If callback returns `True`, then the minimization\n is halted (any polishing is still carried out).\n polish : bool, optional\n If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`\n method is used to polish the best population member at the end, which\n can improve the minimization slightly.\n init : str or array-like, optional\n Specify which type of population initialization is performed. Should be\n one of:\n - 'latinhypercube'\n - 'random'\n - array specifying the initial population. The array should have\n shape ``(M, len(x))``, where len(x) is the number of parameters.\n `init` is clipped to `bounds` before use.\n The default is 'latinhypercube'. Latin Hypercube sampling tries to\n maximize coverage of the available parameter space. 'random'\n initializes the population randomly - this has the drawback that\n clustering can occur, preventing the whole of parameter space being\n covered. Use of an array to specify a population subset could be used,\n for example, to create a tight bunch of initial guesses in a location\n where the solution is known to exist, thereby reducing time for\n convergence.\n atol : float, optional\n Absolute tolerance for convergence, the solving stops when\n ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,\n where and `atol` and `tol` are the absolute and relative tolerance\n respectively.\n Returns\n -------\n res : OptimizeResult\n The optimization result represented as a `OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``success`` a\n Boolean flag indicating if the optimizer exited successfully and\n ``message`` which describes the cause of the termination. See\n `OptimizeResult` for a description of other attributes. If `polish`\n was employed, and a lower minimum was obtained by the polishing, then\n OptimizeResult also contains the ``jac`` attribute.\n Notes\n -----\n Differential evolution is a stochastic population based method that is\n useful for global optimization problems. At each pass through the\n population the algorithm mutates each candidate solution by mixing with\n other candidate solutions to create a trial candidate. There are several\n strategies [2]_ for creating trial candidates, which suit some problems\n more than others. The 'best1bin' strategy is a good starting point for many\n systems. In this strategy two members of the population are randomly\n chosen. Their difference is used to mutate the best member (the `best` in\n `best1bin`), :math:`b_0`,\n so far:\n .. math::\n b' = b_0 + mutation * (population[rand0] - population[rand1])\n A trial vector is then constructed. Starting with a randomly chosen 'i'th\n parameter the trial is sequentially filled (in modulo) with parameters from\n `b'` or the original candidate. The choice of whether to use `b'` or the\n original candidate is made with a binomial distribution (the 'bin' in\n 'best1bin') - a random number in [0, 1) is generated. If this number is\n less than the `recombination` constant then the parameter is loaded from\n `b'`, otherwise it is loaded from the original candidate. The final\n parameter is always loaded from `b'`. Once the trial candidate is built\n its fitness is assessed. If the trial is better than the original candidate\n then it takes its place. If it is also better than the best overall\n candidate it also replaces that.\n To improve your chances of finding a global minimum use higher `popsize`\n values, with higher `mutation` and (dithering), but lower `recombination`\n values. This has the effect of widening the search radius, but slowing\n convergence.\n .. versionadded:: 0.15.0\n Examples\n --------\n Let us consider the problem of minimizing the Rosenbrock function. This\n function is implemented in `rosen` in `scipy.optimize`.\n >>> from scipy.optimize import rosen, differential_evolution\n >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]\n >>> result = differential_evolution(rosen, bounds)\n >>> result.x, result.fun\n (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)\n Next find the minimum of the Ackley function\n (http://en.wikipedia.org/wiki/Test_functions_for_optimization).\n >>> from scipy.optimize import differential_evolution\n >>> import numpy as np\n >>> def ackley(x):\n ... arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))\n ... arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi *x[1]))\n ... return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e\n >>> bounds = [(-5, 5), (-5, 5)]\n >>> result = differential_evolution(ackley, bounds)\n >>> result.x, result.fun\n (array([ 0., 0.]), 4.4408920985006262e-16)\n References\n ----------\n .. [1] Storn, R and Price, K, Differential Evolution - a Simple and\n Efficient Heuristic for Global Optimization over Continuous Spaces,\n Journal of Global Optimization, 1997, 11, 341 - 359.\n .. [2] http://www1.icsi.berkeley.edu/~storn/code.html\n .. [3] http://en.wikipedia.org/wiki/Differential_evolution\n \"\"\"\n\n solver = DifferentialEvolutionSolver(\n func,\n bounds,\n args=args,\n strategy=strategy,\n maxiter=maxiter,\n popsize=popsize,\n tol=tol,\n mutation=mutation,\n recombination=recombination,\n seed=seed,\n polish=polish,\n callback=callback,\n disp=disp,\n init=init,\n atol=atol,\n )\n return solver.solve()\n\n\nclass DifferentialEvolutionSolver: # pragma: no cover\n \"\"\"This class implements the differential evolution solver\n Parameters\n ----------\n func : callable\n The objective function to be minimized. Must be in the form\n ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array\n and ``args`` is a tuple of any additional fixed parameters needed to\n completely specify the function.\n bounds : sequence\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``,\n defining the lower and upper bounds for the optimizing argument of\n `func`. It is required to have ``len(bounds) == len(x)``.\n ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : tuple, optional\n Any additional fixed parameters needed to\n completely specify the objective function.\n strategy : str, optional\n The differential evolution strategy to use. Should be one of:\n - 'best1bin'\n - 'best1exp'\n - 'rand1exp'\n - 'randtobest1exp'\n - 'currenttobest1exp'\n - 'best2exp'\n - 'rand2exp'\n - 'randtobest1bin'\n - 'currenttobest1bin'\n - 'best2bin'\n - 'rand2bin'\n - 'rand1bin'\n The default is 'best1bin'\n maxiter : int, optional\n The maximum number of generations over which the entire population is\n evolved. The maximum number of function evaluations (with no polishing)\n is: ``(maxiter + 1) * popsize * len(x)``\n popsize : int, optional\n A multiplier for setting the total population size. The population has\n ``popsize * len(x)`` individuals (unless the initial population is\n supplied via the `init` keyword).\n tol : float, optional\n Relative tolerance for convergence, the solving stops when\n ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,\n where and `atol` and `tol` are the absolute and relative tolerance\n respectively.\n mutation : float or tuple(float, float), optional\n The mutation constant. In the literature this is also known as\n differential weight, being denoted by F.\n If specified as a float it should be in the range [0, 2].\n If specified as a tuple ``(min, max)`` dithering is employed. Dithering\n randomly changes the mutation constant on a generation by generation\n basis. The mutation constant for that generation is taken from\n U[min, max). Dithering can help speed convergence significantly.\n Increasing the mutation constant increases the search radius, but will\n slow down convergence.\n recombination : float, optional\n The recombination constant, should be in the range [0, 1]. In the\n literature this is also known as the crossover probability, being\n denoted by CR. Increasing this value allows a larger number of mutants\n to progress into the next generation, but at the risk of population\n stability.\n seed : int or `np.random.RandomState`, optional\n If `seed` is not specified the `np.random.RandomState` singleton is\n used.\n If `seed` is an int, a new `np.random.RandomState` instance is used,\n seeded with `seed`.\n If `seed` is already a `np.random.RandomState` instance, then that\n `np.random.RandomState` instance is used.\n Specify `seed` for repeatable minimizations.\n disp : bool, optional\n Display status messages\n callback : callable, `callback(xk, convergence=val)`, optional\n A function to follow the progress of the minimization. ``xk`` is\n the current value of ``x0``. ``val`` represents the fractional\n value of the population convergence. When ``val`` is greater than one\n the function halts. If callback returns `True`, then the minimization\n is halted (any polishing is still carried out).\n polish : bool, optional\n If True, then `scipy.optimize.minimize` with the `L-BFGS-B` method\n is used to polish the best population member at the end. This requires\n a few more function evaluations.\n maxfun : int, optional\n Set the maximum number of function evaluations. However, it probably\n makes more sense to set `maxiter` instead.\n init : str or array-like, optional\n Specify which type of population initialization is performed. Should be\n one of:\n - 'latinhypercube'\n - 'random'\n - array specifying the initial population. The array should have\n shape ``(M, len(x))``, where len(x) is the number of parameters.\n `init` is clipped to `bounds` before use.\n The default is 'latinhypercube'. Latin Hypercube sampling tries to\n maximize coverage of the available parameter space. 'random'\n initializes the population randomly - this has the drawback that\n clustering can occur, preventing the whole of parameter space being\n covered. Use of an array to specify a population could be used, for\n example, to create a tight bunch of initial guesses in a location\n where the solution is known to exist, thereby reducing time for\n convergence.\n atol : float, optional\n Absolute tolerance for convergence, the solving stops when\n ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,\n where and `atol` and `tol` are the absolute and relative tolerance\n respectively.\n \"\"\"\n\n # Dispatch of mutation strategy method (binomial or exponential).\n _binomial = {\n \"best1bin\": \"_best1\",\n \"randtobest1bin\": \"_randtobest1\",\n \"currenttobest1bin\": \"_currenttobest1\",\n \"best2bin\": \"_best2\",\n \"rand2bin\": \"_rand2\",\n \"rand1bin\": \"_rand1\",\n }\n _exponential = {\n \"best1exp\": \"_best1\",\n \"rand1exp\": \"_rand1\",\n \"randtobest1exp\": \"_randtobest1\",\n \"currenttobest1exp\": \"_currenttobest1\",\n \"best2exp\": \"_best2\",\n \"rand2exp\": \"_rand2\",\n }\n\n __init_error_msg = (\n \"The population initialization method must be one of \"\n \"'latinhypercube' or 'random', or an array of shape \"\n \"(M, N) where N is the number of parameters and M>5\"\n )\n\n def __init__(\n self,\n func,\n bounds,\n args=(),\n strategy=\"best1bin\",\n maxiter=1000,\n popsize=15,\n tol=0.01,\n mutation=(0.5, 1),\n recombination=0.7,\n seed=None,\n maxfun=np.inf,\n callback=None,\n disp=False,\n polish=True,\n init=\"latinhypercube\",\n atol=0,\n ):\n\n if strategy in self._binomial:\n self.mutation_func = getattr(self, self._binomial[strategy])\n elif strategy in self._exponential:\n self.mutation_func = getattr(self, self._exponential[strategy])\n else:\n raise ValueError(\"Please select a valid mutation strategy\")\n self.strategy = strategy\n\n self.callback = callback\n self.polish = polish\n\n # relative and absolute tolerances for convergence\n self.tol, self.atol = tol, atol\n\n # Mutation constant should be in [0, 2). If specified as a sequence\n # then dithering is performed.\n self.scale = mutation\n if not np.all(np.isfinite(mutation)) or np.any(np.array(mutation) >= 2) or np.any(np.array(mutation) < 0):\n raise ValueError(\n \"The mutation constant must be a float in \"\n \"U[0, 2), or specified as a tuple(min, max)\"\n \" where min < max and min, max are in U[0, 2).\"\n )\n\n self.dither = None\n if hasattr(mutation, \"__iter__\") and len(mutation) > 1:\n self.dither = [mutation[0], mutation[1]]\n self.dither.sort()\n\n self.cross_over_probability = recombination\n\n self.func = func\n self.args = args\n\n # convert tuple of lower and upper bounds to limits\n # [(low_0, high_0), ..., (low_n, high_n]\n # -> [[low_0, ..., low_n], [high_0, ..., high_n]]\n self.limits = np.array(bounds, dtype=\"float\").T\n if np.size(self.limits, 0) != 2 or not np.all(np.isfinite(self.limits)):\n raise ValueError(\n \"bounds should be a sequence containing \" \"real valued (min, max) pairs for each value\" \" in x\"\n )\n\n if maxiter is None: # the default used to be None\n maxiter = 1000\n self.maxiter = maxiter\n if maxfun is None: # the default used to be None\n maxfun = np.inf\n self.maxfun = maxfun\n\n # population is scaled to between [0, 1].\n # We have to scale between parameter <-> population\n # save these arguments for _scale_parameter and\n # _unscale_parameter. This is an optimization\n self.__scale_arg1 = 0.5 * (self.limits[0] + self.limits[1])\n self.__scale_arg2 = np.fabs(self.limits[0] - self.limits[1])\n\n self.parameter_count = np.size(self.limits, 1)\n\n self.random_number_generator = check_random_state(seed)\n\n # default population initialization is a latin hypercube design, but\n # there are other population initializations possible.\n # the minimum is 5 because 'best2bin' requires a population that's at\n # least 5 long\n self.num_population_members = max(5, popsize * self.parameter_count)\n\n self.population_shape = (self.num_population_members, self.parameter_count)\n\n self._nfev = 0\n if isinstance(init, string_types):\n if init == \"latinhypercube\":\n self.init_population_lhs()\n elif init == \"random\":\n self.init_population_random()\n else:\n raise ValueError(self.__init_error_msg)\n else:\n self.init_population_array(init)\n\n self.disp = disp\n\n def init_population_lhs(self):\n \"\"\"\n Initializes the population with Latin Hypercube Sampling.\n Latin Hypercube Sampling ensures that each parameter is uniformly\n sampled over its range.\n \"\"\"\n rng = self.random_number_generator\n\n # Each parameter range needs to be sampled uniformly. The scaled\n # parameter range ([0, 1)) needs to be split into\n # `self.num_population_members` segments, each of which has the\n # following size:\n segsize = 1.0 / self.num_population_members\n\n # Within each segment we sample from a uniform random distribution.\n # We need to do this sampling for each parameter.\n samples = (\n segsize * rng.random_sample(self.population_shape)\n # Offset each segment to cover the entire parameter range\n # [0, 1)\n + np.linspace(0.0, 1.0, self.num_population_members, endpoint=False)[:, np.newaxis]\n )\n\n # Create an array for population of candidate solutions.\n self.population = np.zeros_like(samples)\n\n # Initialize population of candidate solutions by permutation of the\n # random samples.\n for j in range(self.parameter_count):\n order = rng.permutation(range(self.num_population_members))\n self.population[:, j] = samples[order, j]\n\n # reset population energies\n self.population_energies = np.ones(self.num_population_members) * np.inf\n\n # reset number of function evaluations counter\n self._nfev = 0\n\n def init_population_random(self):\n \"\"\"\n Initialises the population at random. This type of initialization\n can possess clustering, Latin Hypercube sampling is generally better.\n \"\"\"\n rng = self.random_number_generator\n self.population = rng.random_sample(self.population_shape)\n\n # reset population energies\n self.population_energies = np.ones(self.num_population_members) * np.inf\n\n # reset number of function evaluations counter\n self._nfev = 0\n\n def init_population_array(self, init):\n \"\"\"\n Initialises the population with a user specified population.\n Parameters\n ----------\n init : np.ndarray\n Array specifying subset of the initial population. The array should\n have shape (M, len(x)), where len(x) is the number of parameters.\n The population is clipped to the lower and upper `bounds`.\n \"\"\"\n # make sure you're using a float array\n popn = np.asfarray(init)\n\n if np.size(popn, 0) < 5 or popn.shape[1] != self.parameter_count or len(popn.shape) != 2:\n raise ValueError(\"The population supplied needs to have shape\" \" (M, len(x)), where M > 4.\")\n\n # scale values and clip to bounds, assigning to population\n self.population = np.clip(self._unscale_parameters(popn), 0, 1)\n\n self.num_population_members = np.size(self.population, 0)\n\n self.population_shape = (self.num_population_members, self.parameter_count)\n\n # reset population energies\n self.population_energies = np.ones(self.num_population_members) * np.inf\n\n # reset number of function evaluations counter\n self._nfev = 0\n\n @property\n def x(self):\n \"\"\"\n The best solution from the solver\n Returns\n -------\n x : ndarray\n The best solution from the solver.\n \"\"\"\n return self._scale_parameters(self.population[0])\n\n @property\n def convergence(self):\n \"\"\"\n The standard deviation of the population energies divided by their\n mean.\n \"\"\"\n return np.std(self.population_energies) / np.abs(np.mean(self.population_energies) + _MACHEPS)\n\n def solve(self):\n \"\"\"\n Runs the DifferentialEvolutionSolver.\n Returns\n -------\n res : OptimizeResult\n The optimization result represented as a ``OptimizeResult`` object.\n Important attributes are: ``x`` the solution array, ``success`` a\n Boolean flag indicating if the optimizer exited successfully and\n ``message`` which describes the cause of the termination. See\n `OptimizeResult` for a description of other attributes. If `polish`\n was employed, and a lower minimum was obtained by the polishing,\n then OptimizeResult also contains the ``jac`` attribute.\n \"\"\"\n nit, warning_flag = 0, False\n status_message = _status_message[\"success\"]\n\n # The population may have just been initialized (all entries are\n # np.inf). If it has you have to calculate the initial energies.\n # Although this is also done in the evolve generator it's possible\n # that someone can set maxiter=0, at which point we still want the\n # initial energies to be calculated (the following loop isn't run).\n if np.all(np.isinf(self.population_energies)):\n self._calculate_population_energies()\n\n # do the optimisation.\n for nit in range(1, self.maxiter + 1):\n # evolve the population by a generation\n try:\n next(self)\n except StopIteration:\n warning_flag = True\n status_message = _status_message[\"maxfev\"]\n break\n\n if self.disp:\n print(f\"differential_evolution step {nit}: f(x)= {self.population_energies[0]}\")\n\n # should the solver terminate?\n convergence = self.convergence\n\n if (\n self.callback\n and self.callback(\n self._scale_parameters(self.population[0]),\n convergence=self.tol / convergence,\n )\n is True\n ):\n warning_flag = True\n status_message = \"callback function requested stop early by returning True\"\n break\n\n intol = np.std(self.population_energies) <= self.atol + self.tol * np.abs(np.mean(self.population_energies))\n if warning_flag or intol:\n break\n\n else:\n status_message = _status_message[\"maxiter\"]\n warning_flag = True\n\n de_result = OptimizeResult(\n x=self.x,\n fun=self.population_energies[0],\n nfev=self._nfev,\n nit=nit,\n message=status_message,\n success=(warning_flag is not True),\n )\n\n if self.polish:\n result = minimize(\n self.func,\n np.copy(de_result.x),\n method=\"L-BFGS-B\",\n bounds=self.limits.T,\n args=self.args,\n )\n\n self._nfev += result.nfev\n de_result.nfev = self._nfev\n\n if result.fun < de_result.fun:\n de_result.fun = result.fun\n de_result.x = result.x\n de_result.jac = result.jac\n # to keep internal state consistent\n self.population_energies[0] = result.fun\n self.population[0] = self._unscale_parameters(result.x)\n\n return de_result\n\n def _calculate_population_energies(self):\n \"\"\"\n Calculate the energies of all the population members at the same time.\n Puts the best member in first place. Useful if the population has just\n been initialised.\n \"\"\"\n\n ##############\n # CHANGES: self.func operates on the entire parameters array\n ##############\n itersize = max(0, min(len(self.population), self.maxfun - self._nfev + 1))\n candidates = self.population[:itersize]\n parameters = np.array([self._scale_parameters(c) for c in candidates]) # TODO: can be vectorized\n energies = self.func(parameters, *self.args)\n self.population_energies = energies\n self._nfev += itersize\n\n # for index, candidate in enumerate(self.population):\n # if self._nfev > self.maxfun:\n # break\n\n # parameters = self._scale_parameters(candidate)\n # self.population_energies[index] = self.func(parameters,\n # *self.args)\n # self._nfev += 1\n\n ##############\n ##############\n\n minval = np.argmin(self.population_energies)\n\n # put the lowest energy into the best solution position.\n lowest_energy = self.population_energies[minval]\n self.population_energies[minval] = self.population_energies[0]\n self.population_energies[0] = lowest_energy\n\n self.population[[0, minval], :] = self.population[[minval, 0], :]\n\n def __iter__(self):\n return self\n\n def __next__(self):\n \"\"\"\n Evolve the population by a single generation\n Returns\n -------\n x : ndarray\n The best solution from the solver.\n fun : float\n Value of objective function obtained from the best solution.\n \"\"\"\n # the population may have just been initialized (all entries are\n # np.inf). If it has you have to calculate the initial energies\n if np.all(np.isinf(self.population_energies)):\n self._calculate_population_energies()\n\n if self.dither is not None:\n self.scale = self.random_number_generator.rand() * (self.dither[1] - self.dither[0]) + self.dither[0]\n\n ##############\n # CHANGES: self.func operates on the entire parameters array\n ##############\n\n itersize = max(0, min(self.num_population_members, self.maxfun - self._nfev + 1))\n trials = np.array([self._mutate(c) for c in range(itersize)]) # TODO:can be vectorized\n for trial in trials:\n self._ensure_constraint(trial)\n parameters = np.array([self._scale_parameters(trial) for trial in trials])\n energies = self.func(parameters, *self.args)\n self._nfev += itersize\n\n for candidate, (energy, trial) in enumerate(zip(energies, trials)):\n # if the energy of the trial candidate is lower than the\n # original population member then replace it\n if energy < self.population_energies[candidate]:\n self.population[candidate] = trial\n self.population_energies[candidate] = energy\n\n # if the trial candidate also has a lower energy than the\n # best solution then replace that as well\n if energy < self.population_energies[0]:\n self.population_energies[0] = energy\n self.population[0] = trial\n\n # for candidate in range(self.num_population_members):\n # if self._nfev > self.maxfun:\n # raise StopIteration\n\n # # create a trial solution\n # trial = self._mutate(candidate)\n\n # # ensuring that it's in the range [0, 1)\n # self._ensure_constraint(trial)\n\n # # scale from [0, 1) to the actual parameter value\n # parameters = self._scale_parameters(trial)\n\n # # determine the energy of the objective function\n # energy = self.func(parameters, *self.args)\n # self._nfev += 1\n\n # # if the energy of the trial candidate is lower than the\n # # original population member then replace it\n # if energy < self.population_energies[candidate]:\n # self.population[candidate] = trial\n # self.population_energies[candidate] = energy\n\n # # if the trial candidate also has a lower energy than the\n # # best solution then replace that as well\n # if energy < self.population_energies[0]:\n # self.population_energies[0] = energy\n # self.population[0] = trial\n\n ##############\n ##############\n\n return self.x, self.population_energies[0]\n\n def next(self):\n \"\"\"\n Evolve the population by a single generation\n Returns\n -------\n x : ndarray\n The best solution from the solver.\n fun : float\n Value of objective function obtained from the best solution.\n \"\"\"\n # next() is required for compatibility with Python2.7.\n return self.__next__()\n\n def _scale_parameters(self, trial):\n \"\"\"\n scale from a number between 0 and 1 to parameters.\n \"\"\"\n return self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2\n\n def _unscale_parameters(self, parameters):\n \"\"\"\n scale from parameters to a number between 0 and 1.\n \"\"\"\n return (parameters - self.__scale_arg1) / self.__scale_arg2 + 0.5\n\n def _ensure_constraint(self, trial):\n \"\"\"\n make sure the parameters lie between the limits\n \"\"\"\n for index in np.where((trial < 0) | (trial > 1))[0]:\n trial[index] = self.random_number_generator.rand()\n\n def _mutate(self, candidate): # pylint: disable=inconsistent-return-statements\n \"\"\"\n create a trial vector based on a mutation strategy\n \"\"\"\n trial = np.copy(self.population[candidate])\n\n rng = self.random_number_generator\n\n fill_point = rng.randint(0, self.parameter_count)\n\n if self.strategy in [\"currenttobest1exp\", \"currenttobest1bin\"]:\n bprime = self.mutation_func(candidate, self._select_samples(candidate, 5))\n else:\n bprime = self.mutation_func(self._select_samples(candidate, 5))\n\n if self.strategy in self._binomial:\n crossovers = rng.rand(self.parameter_count)\n crossovers = crossovers < self.cross_over_probability\n # the last one is always from the bprime vector for binomial\n # If you fill in modulo with a loop you have to set the last one to\n # true. If you don't use a loop then you can have any random entry\n # be True.\n crossovers[fill_point] = True\n trial = np.where(crossovers, bprime, trial)\n return trial\n\n if self.strategy in self._exponential:\n i = 0\n while i < self.parameter_count and rng.rand() < self.cross_over_probability:\n trial[fill_point] = bprime[fill_point]\n fill_point = (fill_point + 1) % self.parameter_count\n i += 1\n\n return trial\n\n def _best1(self, samples):\n \"\"\"\n best1bin, best1exp\n \"\"\"\n r_0, r_1 = samples[:2]\n return self.population[0] + self.scale * (self.population[r_0] - self.population[r_1])\n\n def _rand1(self, samples):\n \"\"\"\n rand1bin, rand1exp\n \"\"\"\n r_0, r_1, r_2 = samples[:3]\n return self.population[r_0] + self.scale * (self.population[r_1] - self.population[r_2])\n\n def _randtobest1(self, samples):\n \"\"\"\n randtobest1bin, randtobest1exp\n \"\"\"\n r_0, r_1, r_2 = samples[:3]\n bprime = np.copy(self.population[r_0])\n bprime += self.scale * (self.population[0] - bprime)\n bprime += self.scale * (self.population[r_1] - self.population[r_2])\n return bprime\n\n def _currenttobest1(self, candidate, samples):\n \"\"\"\n currenttobest1bin, currenttobest1exp\n \"\"\"\n r_0, r_1 = samples[:2]\n bprime = self.population[candidate] + self.scale * (\n self.population[0] - self.population[candidate] + self.population[r_0] - self.population[r_1]\n )\n return bprime\n\n def _best2(self, samples):\n \"\"\"\n best2bin, best2exp\n \"\"\"\n r_0, r_1, r_2, r_3 = samples[:4]\n bprime = self.population[0] + self.scale * (\n self.population[r_0] + self.population[r_1] - self.population[r_2] - self.population[r_3]\n )\n\n return bprime\n\n def _rand2(self, samples):\n \"\"\"\n rand2bin, rand2exp\n \"\"\"\n r_0, r_1, r_2, r_3, r_4 = samples\n bprime = self.population[r_0] + self.scale * (\n self.population[r_1] + self.population[r_2] - self.population[r_3] - self.population[r_4]\n )\n\n return bprime\n\n def _select_samples(self, candidate, number_samples):\n \"\"\"\n obtain random integers from range(self.num_population_members),\n without replacement. You can't have the original candidate either.\n \"\"\"\n idxs = list(range(self.num_population_members))\n idxs.remove(candidate)\n self.random_number_generator.shuffle(idxs)\n idxs = idxs[:number_samples]\n return idxs\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/rescaling_auto_conjugate_gradient.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n\n# Copyright (c) 2024 Keiichiro Yamamura\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the 'Rescaling-ACG' attack.\n\n| Paper link: https://arxiv.org/abs/2408.03972\n\"\"\"\nimport abc\nimport logging\nimport math\nfrom typing import Optional, Union, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format, projection, random_sphere, is_probability, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass RescalingAutoConjugateGradient(EvasionAttack):\n \"\"\"\n Implementation of the 'Rescaling-ACG' attack.\n The original implementation is https://github.com/yamamura-k/ReACG.\n\n | Paper link:\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"max_iter\",\n \"targeted\",\n \"nb_random_init\",\n \"batch_size\",\n \"loss_type\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n _predefined_losses = [None, \"cross_entropy\", \"difference_logits_ratio\"]\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n norm: Union[int, float, str] = np.inf,\n eps: float = 0.3,\n eps_step: float = 0.1,\n max_iter: int = 100,\n targeted: bool = False,\n nb_random_init: int = 5,\n batch_size: int = 32,\n loss_type: Optional[str] = None,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.RescalingAutoConjugateGradient` instance.\n\n :param estimator: An trained estimator.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param nb_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0\n starting at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param loss_type: Defines the loss to attack. Available options: None (Use loss defined by estimator),\n \"cross_entropy\", or \"difference_logits_ratio\"\n :param verbose: Show progress bars.\n \"\"\"\n from art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier\n\n if loss_type not in self._predefined_losses:\n raise ValueError(\n f\"The argument loss_type has an invalid value. The following options for `loss_type` are currently \"\n f\"supported: {self._predefined_losses}\"\n )\n\n if loss_type is None:\n if hasattr(estimator, \"predict\") and is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=np.float32))\n ):\n raise ValueError( # pragma: no cover\n \"AutoProjectedGradientDescent is expecting logits as estimator output, the provided \"\n \"estimator seems to predict probabilities.\"\n )\n\n estimator_reacg = estimator\n else:\n if isinstance(estimator, TensorFlowV2Classifier):\n import tensorflow as tf\n\n class TensorFlowV2Loss:\n \"\"\"abstract class of loss function of tensorflow v2\"\"\"\n\n @abc.abstractmethod\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n raise NotImplementedError\n\n if loss_type == \"cross_entropy\":\n\n class CrossEntropyLossV2(TensorFlowV2Loss):\n \"\"\"Class defining cross entropy loss with reduction options.\"\"\"\n\n def __init__(self, from_logits, reduction=\"sum\"):\n self.ce_loss = tf.keras.losses.CategoricalCrossentropy(\n from_logits=from_logits,\n reduction=tf.keras.losses.Reduction.NONE,\n )\n self.reduction = reduction\n\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n if self.reduction == \"mean\":\n return tf.reduce_mean(self.ce_loss(y_true, y_pred))\n if self.reduction == \"sum\":\n return tf.reduce_sum(self.ce_loss(y_true, y_pred))\n if self.reduction == \"none\":\n return self.ce_loss(y_true, y_pred)\n raise NotImplementedError()\n\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n _loss_object_tf: TensorFlowV2Loss = CrossEntropyLossV2(from_logits=False)\n else:\n _loss_object_tf = CrossEntropyLossV2(from_logits=True)\n elif loss_type == \"difference_logits_ratio\":\n if is_probability(estimator.predict(x=np.ones(shape=(1, *estimator.input_shape)))):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. \"\n \"If loss_type='difference_logits_ratio' the estimator has to to predict logits.\"\n )\n\n class DifferenceLogitsRatioTensorFlowV2(TensorFlowV2Loss):\n \"\"\"\n Callable class for Difference Logits Ratio loss in TensorFlow v2.\n \"\"\"\n\n def __init__(self):\n self.reduction = \"sum\"\n\n def __call__(self, y_true: tf.Tensor, y_pred: tf.Tensor, *args, **kwargs) -> tf.Tensor:\n i_y_true = tf.cast(tf.math.argmax(tf.cast(y_true, tf.int32), axis=1), tf.int32)\n i_y_pred_arg = tf.argsort(y_pred, axis=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = tf.stack(i_z_i_list)\n\n z_1 = tf.gather(y_pred, i_y_pred_arg[:, -1], axis=1, batch_dims=0)\n z_3 = tf.gather(y_pred, i_y_pred_arg[:, -3], axis=1, batch_dims=0)\n z_i = tf.gather(y_pred, i_z_i, axis=1, batch_dims=0)\n z_y = tf.gather(y_pred, i_y_true, axis=1, batch_dims=0)\n\n z_1 = tf.linalg.diag_part(z_1)\n z_3 = tf.linalg.diag_part(z_3)\n z_i = tf.linalg.diag_part(z_i)\n z_y = tf.linalg.diag_part(z_y)\n\n dlr = -(z_y - z_i) / (z_1 - z_3)\n if self.reduction == \"mean\":\n return tf.reduce_mean(dlr)\n if self.reduction == \"sum\":\n return tf.reduce_sum(dlr)\n if self.reduction == \"none\":\n return dlr\n raise NotImplementedError()\n\n _loss_object_tf = DifferenceLogitsRatioTensorFlowV2()\n else:\n raise NotImplementedError()\n\n estimator_reacg = TensorFlowV2Classifier(\n model=estimator.model,\n nb_classes=estimator.nb_classes,\n input_shape=estimator.input_shape,\n loss_object=_loss_object_tf,\n optimizer=estimator.optimizer,\n train_step=estimator.train_step,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n )\n elif isinstance(estimator, PyTorchClassifier):\n import torch\n\n if loss_type == \"cross_entropy\":\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=np.float32))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. If loss_type='cross_entropy' \"\n \"the estimator has to to predict logits.\"\n )\n\n class CrossEntropyLossTorch(torch.nn.modules.loss._Loss): # pylint: disable=W0212\n \"\"\"Class defining cross entropy loss with reduction options.\"\"\"\n\n def __init__(self, reduction=\"sum\"):\n super().__init__()\n self.ce_loss = torch.nn.CrossEntropyLoss(reduction=\"none\")\n self.reduction = reduction\n\n def __call__(self, y_true: torch.Tensor, y_pred: torch.Tensor, *args, **kwargs) -> torch.Tensor:\n if self.reduction == \"mean\":\n return self.ce_loss(y_true, y_pred).mean()\n if self.reduction == \"sum\":\n return self.ce_loss(y_true, y_pred).sum()\n if self.reduction == \"none\":\n return self.ce_loss(y_true, y_pred)\n raise NotImplementedError()\n\n def forward(\n self, input: torch.Tensor, target: torch.Tensor # pylint: disable=W0622\n ) -> torch.Tensor:\n \"\"\"\n Forward method.\n :param input: Predicted labels of shape (nb_samples, nb_classes).\n :param target: Target labels of shape (nb_samples, nb_classes).\n :return: Difference Logits Ratio Loss.\n \"\"\"\n return self.__call__(y_true=target, y_pred=input)\n\n _loss_object_pt: torch.nn.modules.loss._Loss = CrossEntropyLossTorch(reduction=\"mean\")\n\n elif loss_type == \"difference_logits_ratio\":\n if is_probability(\n estimator.predict(x=np.ones(shape=(1, *estimator.input_shape), dtype=ART_NUMPY_DTYPE))\n ):\n raise ValueError( # pragma: no cover\n \"The provided estimator seems to predict probabilities. \"\n \"If loss_type='difference_logits_ratio' the estimator has to to predict logits.\"\n )\n\n class DifferenceLogitsRatioPyTorch(torch.nn.modules.loss._Loss): # pylint: disable=W0212\n \"\"\"\n Callable class for Difference Logits Ratio loss in PyTorch.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.reduction = \"sum\"\n\n def __call__(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:\n if isinstance(y_true, np.ndarray):\n y_true = torch.from_numpy(y_true)\n if isinstance(y_pred, np.ndarray):\n y_pred = torch.from_numpy(y_pred)\n\n y_true = y_true.float()\n\n i_y_true = torch.argmax(y_true, dim=1)\n i_y_pred_arg = torch.argsort(y_pred, dim=1)\n i_z_i_list = []\n\n for i in range(y_true.shape[0]):\n if i_y_pred_arg[i, -1] != i_y_true[i]:\n i_z_i_list.append(i_y_pred_arg[i, -1])\n else:\n i_z_i_list.append(i_y_pred_arg[i, -2])\n\n i_z_i = torch.stack(i_z_i_list)\n\n z_1 = y_pred[:, i_y_pred_arg[:, -1]]\n z_3 = y_pred[:, i_y_pred_arg[:, -3]]\n z_i = y_pred[:, i_z_i]\n z_y = y_pred[:, i_y_true]\n\n z_1 = torch.diagonal(z_1)\n z_3 = torch.diagonal(z_3)\n z_i = torch.diagonal(z_i)\n z_y = torch.diagonal(z_y)\n\n dlr = (-(z_y - z_i) / (z_1 - z_3)).float()\n if self.reduction == \"mean\":\n return dlr.mean()\n if self.reduction == \"sum\":\n return dlr.sum()\n if self.reduction == \"none\":\n return dlr\n raise NotImplementedError()\n\n def forward(\n self, input: torch.Tensor, target: torch.Tensor # pylint: disable=W0622\n ) -> torch.Tensor:\n \"\"\"\n Forward method.\n :param input: Predicted labels of shape (nb_samples, nb_classes).\n :param target: Target labels of shape (nb_samples, nb_classes).\n :return: Difference Logits Ratio Loss.\n \"\"\"\n return self.__call__(y_true=target, y_pred=input)\n\n _loss_object_pt = DifferenceLogitsRatioPyTorch()\n else:\n raise NotImplementedError()\n\n estimator_reacg = PyTorchClassifier(\n model=estimator.model,\n loss=_loss_object_pt,\n input_shape=estimator.input_shape,\n nb_classes=estimator.nb_classes,\n optimizer=None,\n channels_first=estimator.channels_first,\n clip_values=estimator.clip_values,\n preprocessing_defences=estimator.preprocessing_defences,\n postprocessing_defences=estimator.postprocessing_defences,\n preprocessing=estimator.preprocessing,\n device_type=str(estimator._device),\n )\n\n else: # pragma: no cover\n raise ValueError(f\"The loss type {loss_type} is not supported for the provided estimator.\")\n\n super().__init__(estimator=estimator_reacg)\n self.norm = norm\n self.eps = eps\n self.eps_step = eps_step\n self.max_iter = max_iter\n self.targeted = targeted\n self.nb_random_init = nb_random_init\n self.batch_size = batch_size\n self.loss_type = loss_type\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = kwargs.get(\"mask\")\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)).astype(int)\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n for _ in trange(max(1, self.nb_random_init), desc=\"ReACG - restart\", disable=not self.verbose):\n # Determine correctly predicted samples\n y_pred = self.estimator.predict(x_adv)\n if self.targeted:\n sample_is_robust = np.argmax(y_pred, axis=1) != np.argmax(y, axis=1)\n elif not self.targeted:\n sample_is_robust = np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)\n\n if np.sum(sample_is_robust) == 0:\n break\n\n x_robust = x_adv[sample_is_robust]\n y_robust = y[sample_is_robust]\n x_init = x[sample_is_robust]\n\n n = x_robust.shape[0]\n m = np.prod(x_robust.shape[1:]).item()\n random_perturbation = (\n random_sphere(n, m, self.eps, self.norm).reshape(x_robust.shape).astype(ART_NUMPY_DTYPE)\n )\n\n x_robust = x_robust + random_perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_robust = np.clip(x_robust, clip_min, clip_max)\n\n perturbation = projection(x_robust - x_init, self.eps, self.norm)\n x_robust = x_init + perturbation\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_robust.shape[0] / float(self.batch_size))),\n desc=\"ReACG - batch\",\n leave=False,\n disable=not self.verbose,\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_k = x_robust[batch_index_1:batch_index_2].astype(ART_NUMPY_DTYPE)\n x_init_batch = x_init[batch_index_1:batch_index_2].astype(ART_NUMPY_DTYPE)\n y_batch = y_robust[batch_index_1:batch_index_2]\n\n p_0 = 0\n p_1 = 0.43\n var_w = [p_0, p_1]\n\n while True:\n p_j_p_1 = var_w[-1] + max(var_w[-1] - var_w[-2] - 0.24, 0.08)\n if p_j_p_1 > 1:\n break\n var_w.append(p_j_p_1)\n\n var_w = [math.ceil(p * self.max_iter) for p in var_w]\n\n # self.eta = np.full((self.batch_size, 1, 1, 1), 2 * self.eps_step).astype(ART_NUMPY_DTYPE)\n _batch_size = x_k.shape[0]\n eta = np.full((_batch_size,) + (1,) * len(self.estimator.input_shape), self.eps_step).astype(\n ART_NUMPY_DTYPE\n )\n self.count_condition_1 = np.zeros(shape=(_batch_size,))\n gradk_1 = np.zeros_like(x_k)\n cgradk_1 = np.zeros_like(x_k)\n cgradk = np.zeros_like(x_k)\n gradk_1_best = np.zeros_like(x_k)\n cgradk_1_best = np.zeros_like(x_k)\n gradk_1_tmp = np.zeros_like(x_k)\n cgradk_1_tmp = np.zeros_like(x_k)\n\n for k_iter in trange(self.max_iter, desc=\"ReACG - iteration\", leave=False, disable=not self.verbose):\n\n # Get perturbation, use small scalar to avoid division by 0\n tol = 10e-8\n\n # Get gradient wrt loss; invert it if attack is targeted\n grad = self.estimator.loss_gradient(x_k, y_batch) * (1 - 2 * int(self.targeted))\n if k_iter == 0:\n gradk_1 = grad.copy()\n cgradk_1 = grad.copy()\n cgradk = grad.copy()\n else:\n beta = get_beta(grad, gradk_1, cgradk_1)\n # Modify the coefficient beta when |beta| >> avg.(|grad / cgradk_1|)\n _beta_normalized = get_beta(\n grad / np.linalg.norm(grad), gradk_1 / np.linalg.norm(gradk_1), cgradk_1\n )\n grad_ratio_value = np.abs(grad / cgradk_1).reshape((_batch_size, -1))\n grad_ratio = grad_ratio_value.mean(1)\n normalize_inds = np.abs(beta).reshape((_batch_size,)) > grad_ratio\n smaller_beta_inds = (np.abs(beta) > np.abs(_beta_normalized)).reshape((_batch_size,))\n normalize_inds = np.logical_and(normalize_inds, smaller_beta_inds)\n beta[normalize_inds] = _beta_normalized[normalize_inds].copy()\n cgradk = grad + beta * cgradk_1\n\n # Apply norm bound\n if self.norm in [np.inf, \"inf\"]:\n grad = np.sign(cgradk)\n elif self.norm == 1:\n ind = tuple(range(1, len(x_k.shape)))\n cgradk = cgradk / (np.sum(np.abs(cgradk), axis=ind, keepdims=True) + tol)\n elif self.norm == 2:\n ind = tuple(range(1, len(x_k.shape)))\n cgradk = cgradk / (np.sqrt(np.sum(np.square(cgradk), axis=ind, keepdims=True)) + tol)\n assert x_k.shape == cgradk.shape\n\n perturbation = cgradk\n\n if mask is not None:\n perturbation = perturbation * (mask.astype(ART_NUMPY_DTYPE))\n\n # Apply perturbation and clip\n x_k_p_1 = x_k + eta * perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_k_p_1 = np.clip(x_k_p_1, clip_min, clip_max)\n\n if k_iter == 0:\n x_1 = x_k_p_1\n perturbation = projection(x_1 - x_init_batch, self.eps, self.norm)\n x_1 = x_init_batch + perturbation\n\n f_0 = self.estimator.compute_loss(x=x_k, y=y_batch, reduction=\"none\")\n f_1 = self.estimator.compute_loss(x=x_1, y=y_batch, reduction=\"none\")\n\n self.eta_w_j_m_1 = eta.copy()\n self.f_max_w_j_m_1 = f_0.copy()\n\n self.f_max = f_0.copy()\n self.x_max = x_k.copy()\n\n f1_ge_f0 = f_1 >= f_0\n f_1_tmp = f_1[f1_ge_f0].copy()\n self.f_max[f1_ge_f0] = f_1_tmp.copy()\n x_1_tmp = x_1[f1_ge_f0].copy()\n self.x_max[f1_ge_f0] = x_1_tmp.copy()\n self.count_condition_1[f1_ge_f0] += 1\n\n # Settings for next iteration k\n x_k = x_1\n gradk_1_best = gradk_1.copy()\n cgradk_1_best = cgradk_1.copy()\n\n else:\n perturbation = projection(x_k_p_1 - x_init_batch, self.eps, self.norm)\n x_k_p_1 = x_init_batch + perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_k_p_1 = np.clip(x_k_p_1, clip_min, clip_max)\n\n perturbation = projection(x_k_p_1 - x_init_batch, self.eps, self.norm)\n x_k_p_1 = x_init_batch + perturbation\n\n f_k_p_1 = self.estimator.compute_loss(x=x_k_p_1, y=y_batch, reduction=\"none\")\n\n if (f_k_p_1 == 0.0).all():\n x_k = x_k_p_1.copy()\n break\n\n if self.targeted:\n fk_ge_fm = f_k_p_1 < self.f_max # assume the loss function is cross-entropy\n else:\n fk_ge_fm = f_k_p_1 > self.f_max\n\n self.count_condition_1[fk_ge_fm] += 1\n # update the best points\n x_k_p_1_tmp = x_k_p_1[fk_ge_fm].copy()\n self.x_max[fk_ge_fm] = x_k_p_1_tmp.copy()\n f_k_p_1_tmp = f_k_p_1[fk_ge_fm].copy()\n self.f_max[fk_ge_fm] = f_k_p_1_tmp.copy()\n gradk_1_tmp = gradk_1[fk_ge_fm].copy()\n gradk_1_best[fk_ge_fm] = gradk_1_tmp.copy()\n cgradk_1_tmp = cgradk_1[fk_ge_fm].copy()\n cgradk_1_best[fk_ge_fm] = cgradk_1_tmp.copy()\n\n # update the search points\n x_k = x_k_p_1.copy()\n gradk_1 = grad.copy()\n cgradk_1 = cgradk.copy()\n\n if k_iter in var_w:\n\n rho = 0.75\n\n condition_1 = self.count_condition_1 < rho * (k_iter - var_w[var_w.index(k_iter) - 1])\n condition_2 = np.logical_and(\n (self.eta_w_j_m_1 == eta).squeeze(), self.f_max_w_j_m_1 == self.f_max\n )\n condition = np.logical_or(condition_1, condition_2)\n\n # halve the stepsize if the condition is satisfied\n eta[condition] /= 2\n # move to the best point\n x_max_tmp = self.x_max[condition].copy()\n x_k[condition] = x_max_tmp.copy()\n gradk_1_tmp = gradk_1_best[condition].copy()\n gradk_1[condition] = gradk_1_tmp.copy()\n cgradk_1_tmp = cgradk_1_best[condition].copy()\n cgradk_1[condition] = cgradk_1_tmp.copy()\n\n self.count_condition_1[:] = 0\n self.eta_w_j_m_1 = eta.copy()\n self.f_max_w_j_m_1 = self.f_max.copy()\n\n y_pred_adv_k = self.estimator.predict(x_k)\n if self.targeted:\n sample_is_not_robust_k = np.invert(np.argmax(y_pred_adv_k, axis=1) != np.argmax(y_batch, axis=1))\n elif not self.targeted:\n sample_is_not_robust_k = np.invert(np.argmax(y_pred_adv_k, axis=1) == np.argmax(y_batch, axis=1))\n\n x_robust[batch_index_1:batch_index_2][sample_is_not_robust_k] = x_k[sample_is_not_robust_k]\n\n x_adv[sample_is_robust] = x_robust\n\n return x_adv\n\n def _check_params(self) -> None:\n if self.norm not in [1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, or \"inf\".')\n\n if not isinstance(self.eps, (int, float)) or self.eps <= 0.0:\n raise ValueError(\"The argument eps has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.eps_step, (int, float)) or self.eps_step <= 0.0:\n raise ValueError(\"The argument eps_step has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The argument max_iter has to be of type int and larger than zero.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The argument targeted has to be of bool.\")\n\n if not isinstance(self.nb_random_init, int) or self.nb_random_init <= 0:\n raise ValueError(\"The argument nb_random_init has to be of type int and larger than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The argument batch_size has to be of type int and larger than zero.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n\ndef get_beta(gradk, gradk_1, cgradk_1):\n \"\"\"compute the coefficient beta required to update CG direction\"\"\"\n _batch_size = gradk.shape[0]\n _cgradk_1 = cgradk_1.reshape(_batch_size, -1)\n _gradk = -gradk.reshape(_batch_size, -1)\n _gradk_1 = -gradk_1.reshape(_batch_size, -1)\n delta_gradk = _gradk - _gradk_1\n betak = -(_gradk * delta_gradk).sum(axis=1) / (\n (_cgradk_1 * delta_gradk).sum(axis=1) + np.finfo(ART_NUMPY_DTYPE).eps\n )\n return betak.reshape((_batch_size,) + (1,) * (len(gradk.shape) - 1))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/saliency_map.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Jacobian-based Saliency Map attack `SaliencyMapMethod`. This is a white-box attack.\n\n| Paper link: https://arxiv.org/abs/1511.07528\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SaliencyMapMethod(EvasionAttack):\n \"\"\"\n Implementation of the Jacobian-based Saliency Map Attack (Papernot et al. 2016).\n\n | Paper link: https://arxiv.org/abs/1511.07528\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\"theta\", \"gamma\", \"batch_size\", \"verbose\"]\n _estimator_requirements = (BaseEstimator, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n theta: float = 0.1,\n gamma: float = 1.0,\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a SaliencyMapMethod instance.\n\n :param classifier: A trained classifier.\n :param theta: Amount of Perturbation introduced to each modified feature per step (can be positive or negative).\n :param gamma: Maximum fraction of features being perturbed (between 0 and 1).\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.theta = theta\n self.gamma = gamma\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n # Initialize variables\n dims = list(x.shape[1:])\n self._nb_features = np.prod(dims)\n x_adv = np.reshape(x.astype(ART_NUMPY_DTYPE), (-1, self._nb_features))\n preds = np.argmax(self.estimator.predict(x, batch_size=self.batch_size), axis=1)\n\n # Determine target classes for attack\n if y is None:\n # Randomly choose target from the incorrect classes for each sample\n from art.utils import random_targets\n\n targets = np.argmax(random_targets(preds, self.estimator.nb_classes), axis=1)\n else:\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n targets = np.argmax(y, axis=1)\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_adv.shape[0] / float(self.batch_size))), desc=\"JSMA\", disable=not self.verbose\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch = x_adv[batch_index_1:batch_index_2]\n\n # Main algorithm for each batch\n # Initialize the search space; optimize to remove features that can't be changed\n if self.estimator.clip_values is not None:\n search_space = np.zeros(batch.shape)\n clip_min, clip_max = self.estimator.clip_values\n if self.theta > 0:\n search_space[batch < clip_max] = 1\n else: # pragma: no cover\n search_space[batch > clip_min] = 1\n else:\n search_space = np.ones(batch.shape)\n\n # Get current predictions\n current_pred = preds[batch_index_1:batch_index_2]\n target = targets[batch_index_1:batch_index_2]\n active_indices = np.where(current_pred != target)[0]\n all_feat = np.zeros_like(batch)\n\n while active_indices.size != 0:\n # Compute saliency map\n feat_ind = self._saliency_map(\n np.reshape(batch, [batch.shape[0]] + dims)[active_indices],\n target[active_indices],\n search_space[active_indices],\n )\n\n # Update used features\n all_feat[active_indices, feat_ind[:, 0]] = 1\n all_feat[active_indices, feat_ind[:, 1]] = 1\n\n # Apply attack with clipping\n if self.estimator.clip_values is not None:\n # Prepare update depending on theta\n if self.theta > 0:\n clip_func, clip_value = np.minimum, clip_max # type: ignore\n else: # pragma: no cover\n clip_func, clip_value = np.maximum, clip_min # type: ignore\n\n # Update adversarial examples\n tmp_batch = batch[active_indices]\n tmp_batch[np.arange(len(active_indices)), feat_ind[:, 0]] = clip_func(\n clip_value,\n tmp_batch[np.arange(len(active_indices)), feat_ind[:, 0]] + self.theta,\n )\n tmp_batch[np.arange(len(active_indices)), feat_ind[:, 1]] = clip_func(\n clip_value,\n tmp_batch[np.arange(len(active_indices)), feat_ind[:, 1]] + self.theta,\n )\n batch[active_indices] = tmp_batch\n\n # Remove indices from search space if max/min values were reached\n search_space[batch == clip_value] = 0\n\n # Apply attack without clipping\n else:\n tmp_batch = batch[active_indices]\n tmp_batch[np.arange(len(active_indices)), feat_ind[:, 0]] += self.theta\n tmp_batch[np.arange(len(active_indices)), feat_ind[:, 1]] += self.theta\n batch[active_indices] = tmp_batch\n\n # Recompute model prediction\n current_pred = np.argmax(\n self.estimator.predict(np.reshape(batch, [batch.shape[0]] + dims)),\n axis=1,\n )\n\n # Update active_indices\n active_indices = np.where(\n (current_pred != target)\n * (np.sum(all_feat, axis=1) / self._nb_features <= self.gamma)\n * (np.sum(search_space, axis=1) > 0)\n )[0]\n\n x_adv[batch_index_1:batch_index_2] = batch\n\n x_adv = np.reshape(x_adv, x.shape)\n\n return x_adv\n\n def _saliency_map(self, x: np.ndarray, target: np.ndarray | int, search_space: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute the saliency map of `x`. Return the top 2 coefficients in `search_space` that maximize / minimize\n the saliency map.\n\n :param x: A batch of input samples.\n :param target: Target class for `x`.\n :param search_space: The set of valid pairs of feature indices to search.\n :return: The top 2 coefficients in `search_space` that maximize / minimize the saliency map.\n \"\"\"\n grads = self.estimator.class_gradient(x, label=target)\n grads = np.reshape(grads, (-1, self._nb_features))\n\n # Remove gradients for already used features\n used_features = 1 - search_space\n coeff = 2 * int(self.theta > 0) - 1\n grads[used_features == 1] = -np.inf * coeff\n\n if self.theta > 0:\n ind = np.argpartition(grads, -2, axis=1)[:, -2:]\n else: # pragma: no cover\n ind = np.argpartition(-grads, -2, axis=1)[:, -2:]\n\n return ind\n\n def _check_params(self) -> None:\n if self.gamma <= 0 or self.gamma > 1:\n raise ValueError(\"The total perturbation percentage `gamma` must be between 0 and 1.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/shadow_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the evasion attack `ShadowAttack`.\n\n| Paper link: https://arxiv.org/abs/2003.08937\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier\nfrom art.estimators.certification.randomized_smoothing import (\n TensorFlowV2RandomizedSmoothing,\n PyTorchRandomizedSmoothing,\n)\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import get_labels_np_array, check_and_transform_label_format\n\nlogger = logging.getLogger(__name__)\n\n\nclass ShadowAttack(EvasionAttack):\n \"\"\"\n Implementation of the Shadow Attack.\n\n | Paper link: https://arxiv.org/abs/2003.08937\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"sigma\",\n \"nb_steps\",\n \"learning_rate\",\n \"lambda_tv\",\n \"lambda_c\",\n \"lambda_s\",\n \"batch_size\",\n \"targeted\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n\n def __init__(\n self,\n estimator: (\n TensorFlowV2Classifier | TensorFlowV2RandomizedSmoothing | PyTorchClassifier | PyTorchRandomizedSmoothing\n ),\n sigma: float = 0.5,\n nb_steps: int = 300,\n learning_rate: float = 0.1,\n lambda_tv: float = 0.3,\n lambda_c: float = 1.0,\n lambda_s: float = 0.5,\n batch_size: int = 400,\n targeted: bool = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.ShadowAttack`.\n\n :param estimator: A trained classifier.\n :param sigma: Standard deviation random Gaussian Noise.\n :param nb_steps: Number of SGD steps.\n :param learning_rate: Learning rate for SGD.\n :param lambda_tv: Scalar penalty weight for total variation of the perturbation.\n :param lambda_c: Scalar penalty weight for change in the mean of each color channel of the perturbation.\n :param lambda_s: Scalar penalty weight for similarity of color channels in perturbation.\n :param batch_size: The size of the training batch.\n :param targeted: True if the attack is targeted.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.sigma = sigma\n self.batch_size = batch_size\n self.nb_steps = nb_steps\n self.learning_rate = learning_rate\n self.lambda_tv = lambda_tv\n self.lambda_c = lambda_c\n self.lambda_s = lambda_s\n self._targeted = targeted\n self.verbose = verbose\n self._check_params()\n\n self.framework: str | None\n if isinstance(self.estimator, (TensorFlowV2Classifier, TensorFlowV2RandomizedSmoothing)):\n self.framework = \"tensorflow\"\n elif isinstance(self.estimator, (PyTorchClassifier, PyTorchRandomizedSmoothing)):\n self.framework = \"pytorch\"\n else:\n self.framework = None\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array. This requires a lot of memory, therefore it accepts\n only a single samples as input, e.g. a batch of size 1.\n\n :param x: An array of a single original input sample.\n :param y: An array of a single target label.\n :return: An array with the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n logger.info(\"Using model predictions as correct labels for FGM.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n else:\n self.targeted = True\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if x.shape[0] > 1 or y.shape[0] > 1: # pragma: no cover\n raise ValueError(\"This attack only accepts a single sample as input.\")\n\n if x.ndim != 4: # pragma: no cover\n raise ValueError(\"Unrecognized input dimension. Shadow Attack can only be applied to image data.\")\n\n x = x.astype(ART_NUMPY_DTYPE)\n x_batch = np.repeat(x, repeats=self.batch_size, axis=0).astype(ART_NUMPY_DTYPE)\n x_batch = x_batch + np.random.normal(scale=self.sigma, size=x_batch.shape).astype(ART_NUMPY_DTYPE)\n y_batch = np.repeat(y, repeats=self.batch_size, axis=0)\n\n perturbation = (\n np.random.uniform(\n low=self.estimator.clip_values[0], high=self.estimator.clip_values[1], size=x.shape\n ).astype(ART_NUMPY_DTYPE)\n - (self.estimator.clip_values[1] - self.estimator.clip_values[0]) / 2\n )\n\n for _ in trange(self.nb_steps, desc=\"Shadow attack\", disable=not self.verbose):\n gradients_ce = np.mean(\n self.estimator.loss_gradient(x=x_batch + perturbation, y=y_batch, sampling=False)\n * (1 - 2 * int(self.targeted)),\n axis=0,\n keepdims=True,\n )\n gradients = gradients_ce - self._get_regularisation_loss_gradients(perturbation)\n perturbation += self.learning_rate * gradients\n\n x_p = x + perturbation\n x_adv = np.clip(x_p, a_min=self.estimator.clip_values[0], a_max=self.estimator.clip_values[1]).astype(\n ART_NUMPY_DTYPE\n )\n\n return x_adv\n\n def _get_regularisation_loss_gradients(self, perturbation: np.ndarray) -> np.ndarray:\n \"\"\"\n Get regularisation loss gradients.\n\n :param perturbation: The perturbation to be regularised.\n :return: The loss gradients of the perturbation.\n \"\"\"\n if not self.estimator.channels_first:\n perturbation = perturbation.transpose((0, 3, 1, 2))\n\n if self.framework == \"tensorflow\":\n import tensorflow as tf\n\n if tf.executing_eagerly():\n with tf.GradientTape() as tape:\n\n perturbation_t = tf.convert_to_tensor(perturbation)\n tape.watch(perturbation_t)\n\n x_t = perturbation_t[:, :, :, 1:] - perturbation_t[:, :, :, :-1]\n y_t = perturbation_t[:, :, 1:, :] - perturbation_t[:, :, :-1, :]\n loss_tv = tf.reduce_sum(x_t * x_t, axis=(1, 2, 3)) + tf.reduce_sum(y_t * y_t, axis=(1, 2, 3))\n\n if perturbation_t.shape[1] == 1:\n loss_s = 0.0\n elif perturbation_t.shape[1] == 3:\n loss_s = tf.norm(\n (perturbation_t[:, 0, :, :] - perturbation_t[:, 1, :, :]) ** 2\n + (perturbation_t[:, 1, :, :] - perturbation_t[:, 2, :, :]) ** 2\n + (perturbation_t[:, 0, :, :] - perturbation_t[:, 2, :, :]) ** 2,\n ord=2,\n axis=(1, 2),\n )\n else:\n raise ValueError(\"Value for number of channels in `perturbation_t.shape` not recognized.\")\n\n loss_c = tf.norm(tf.reduce_mean(tf.abs(perturbation_t), axis=[2, 3]), ord=2, axis=1) ** 2\n loss = self.lambda_tv * loss_tv + self.lambda_s * loss_s + self.lambda_c * loss_c\n gradients = tape.gradient(loss, perturbation_t).numpy()\n\n else: # pragma: no cover\n raise ValueError(\"Expecting eager execution.\")\n\n elif self.framework == \"pytorch\":\n import torch\n\n perturbation_t = torch.from_numpy(perturbation).to(\"cpu\")\n perturbation_t.requires_grad = True\n\n x_t = perturbation_t[:, :, :, 1:] - perturbation_t[:, :, :, :-1]\n y_t = perturbation_t[:, :, 1:, :] - perturbation_t[:, :, :-1, :]\n\n loss_tv = (x_t * x_t).sum(dim=(1, 2, 3)) + (y_t * y_t).sum(dim=(1, 2, 3))\n\n if perturbation_t.shape[1] == 1:\n loss_s = 0.0\n elif perturbation_t.shape[1] == 3:\n loss_s = (\n (perturbation_t[:, 0, :, :] - perturbation_t[:, 1, :, :]) ** 2\n + (perturbation_t[:, 1, :, :] - perturbation_t[:, 2, :, :]) ** 2\n + (perturbation_t[:, 0, :, :] - perturbation_t[:, 2, :, :]) ** 2\n ).norm(p=2, dim=(1, 2))\n else:\n raise ValueError(\"Value for number of channels in `perturbation_t.shape` not recognized.\")\n\n loss_c = perturbation_t.abs().mean([2, 3]).norm(dim=1) ** 2\n loss = torch.mean(self.lambda_tv * loss_tv + self.lambda_s * loss_s + self.lambda_c * loss_c)\n loss.backward()\n gradients = perturbation_t.grad.numpy() # type: ignore\n else:\n raise NotImplementedError\n\n if not self.estimator.channels_first:\n gradients = gradients.transpose(0, 2, 3, 1)\n\n return gradients\n\n def _check_params(self) -> None:\n if not isinstance(self.sigma, (int, float)):\n raise ValueError(\"The sigma must be of type int or float.\")\n\n if self.sigma <= 0:\n raise ValueError(\"The sigma must larger than zero.\")\n\n if not isinstance(self.nb_steps, int):\n raise ValueError(\"The number of steps must be of type int.\")\n\n if self.nb_steps <= 0:\n raise ValueError(\"The number of steps must larger than zero.\")\n\n if not isinstance(self.learning_rate, float):\n raise ValueError(\"The learning rate must be of type float.\")\n\n if self.learning_rate <= 0:\n raise ValueError(\"The learning rate must larger than zero.\")\n\n if not isinstance(self.lambda_tv, float):\n raise ValueError(\"The lambda_tv must be of type float.\")\n\n if self.lambda_tv < 0:\n raise ValueError(\"The lambda_tv must larger than zero.\")\n\n if not isinstance(self.lambda_c, float):\n raise ValueError(\"The lambda_c must be of type float.\")\n\n if self.lambda_c < 0:\n raise ValueError(\"The lambda_c must larger than zero.\")\n\n if not isinstance(self.lambda_s, float):\n raise ValueError(\"The lambda_s must be of type float.\")\n\n if self.lambda_s < 0:\n raise ValueError(\"The lambda_s must larger than zero.\")\n\n if not isinstance(self.batch_size, int):\n raise ValueError(\"The batch size must be of type int.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The sigma must larger than zero.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The targeted argument must be of type bool.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/sign_opt.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (c) 2022 Minhao Cheng\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nThis module implements the Sign-OPT attack `SignOPTAttack`. This is a query-efficient\nhard-label adversarial attack.\n\n| Paper link: https://arxiv.org/pdf/1909.10773.pdf\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\nimport time\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import compute_success, check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SignOPTAttack(EvasionAttack):\n \"\"\"\n Implements the Sign-OPT attack `SignOPTAttack`. This is a query-efficient\n hard-label adversarial attack.\n\n Paper link: https://arxiv.org/pdf/1909.10773.pdf\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"targeted\",\n \"epsilon\",\n \"num_trial\",\n \"max_iter\",\n \"query_limit\",\n \"K\",\n \"alpha\",\n \"beta\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\",\n targeted: bool = True,\n epsilon: float = 0.001,\n num_trial: int = 100,\n max_iter: int = 1000,\n query_limit: int = 20000,\n k: int = 200,\n alpha: float = 0.2,\n beta: float = 0.001,\n eval_perform: bool = False,\n batch_size: int = 64,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create a Sign_OPT attack instance.\n\n :param estimator: A trained classifier.\n :param targeted: Should the attack target one specific class.\n :param epsilon: A very small smoothing parameter.\n :param num_trial: A number of trials to calculate a good starting point\n :param max_iter: Maximum number of iterations.\n Default value is for untargeted attack, increase to recommended 5000 for targeted attacks.\n :param query_limit: Limitation for number of queries to prediction model.\n Default value is for untargeted attack, increase to recommended 40000 for targeted attacks.\n :param k: Number of random directions (for estimating the gradient)\n :param alpha: The step length for line search\n :param beta: The tolerance for line search\n :param batch_size: The size of the batch used by the estimator during inference.\n :param verbose: Show detailed information\n :param eval_perform: Evaluate performance with Avg. L2 and Success Rate with randomly choosing 100 samples\n \"\"\"\n\n super().__init__(estimator=estimator)\n self.targeted = targeted\n self.epsilon = epsilon\n self.num_trial = num_trial\n self.max_iter = max_iter\n self.query_limit = query_limit\n\n self.k = k\n self.alpha = alpha\n self.beta = beta\n\n self.batch_size = batch_size\n self.verbose = verbose\n\n self.eval_perform = eval_perform\n if eval_perform:\n self.logs = np.zeros(100)\n if self.estimator.clip_values is not None:\n self.clip_min, self.clip_max = self.estimator.clip_values\n self.enable_clipped = True\n else:\n self.enable_clipped = False\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of\n shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). If `self.targeted` is true, then `y` represents the target labels.\n :param kwargs: See below.\n\n :Keyword Arguments:\n * *x_init* --\n Initialisation samples of the same shape as `x` for targeted attacks.\n\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size)) # type: ignore\n\n targets = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=False)\n\n if targets is not None and self.estimator.nb_classes == 2 and targets.shape[1] == 1:\n raise ValueError( # pragma: no cover\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Assert that if attack is targeted, targets is provided\n if self.targeted and targets is None:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n x_init = kwargs.get(\"x_init\")\n\n # Get clip_min and clip_max infer them from data, otherwise, it is initialized by self.estimator\n if self.clip_min is None and self.clip_max is None:\n self.clip_min, self.clip_max = np.min(x), np.max(x)\n\n # Prediction from the original images\n preds = np.argmax(self.estimator.predict(x, batch_size=self.batch_size), axis=1)\n\n # Some initial setups\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n # Generate the adversarial samples\n counter = 0 # only do the performance tests with 100 samples\n for ind, val in enumerate(tqdm(x_adv, desc=\"Sign_OPT attack\", disable=not self.verbose)):\n if self.targeted:\n if targets[ind] == preds[ind]:\n if self.verbose:\n print(\"Image already targeted. No need to attack.\")\n continue\n\n if x_init is None:\n raise ValueError(\"`x_init` needs to be provided for a targeted attack.\")\n\n x_adv[ind], diff, succeed = self._attack( # diff and succeed are for performance test\n x_0=val,\n y_0=preds[ind],\n target=targets[ind],\n x_init=x_init,\n )\n else:\n x_adv[ind], diff, succeed = self._attack( # diff and succeed are for performance test\n x_0=val,\n y_0=preds[ind],\n )\n if succeed and self.eval_perform and counter < 100:\n self.logs[counter] = np.linalg.norm(diff)\n counter += 1\n\n if self.targeted is False:\n logger.info(\n \"Success rate of Sign_OPT attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, targets, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n return x_adv # all images with untargeted adversarial\n\n def _fine_grained_binary_search(\n self,\n x_0: np.ndarray,\n y_0: int,\n theta: np.ndarray,\n initial_lbd: float,\n current_best: float,\n target: int | None = None,\n ) -> tuple[float, int]:\n \"\"\"\n Perform fine-grained line search plus binary search for finding a good starting direction\n\n :param x_0: An array with the original input to be attacked.\n :param y_0: Target value.\n :param theta: Initial query direction.\n :param initial_lbd: Previous solution.\n :param current_best: Current best solution.\n :param target: Target value. If `self.targeted` is true, it presents the targeted label. Defaults to None.\n :return: Optimal solution for finding starting direction; the number of query performed\n \"\"\"\n if self.targeted:\n tolerate = 1e-5\n else:\n tolerate = 1e-3\n nquery = 0\n if initial_lbd > current_best:\n if (self.targeted and not self._is_label(x_0 + current_best * theta, target)) or (\n not self.targeted and self._is_label(x_0 + current_best * theta, y_0)\n ):\n nquery += 1\n return float(\"inf\"), nquery\n lbd = current_best\n else:\n lbd = initial_lbd\n\n lbd_hi = lbd\n lbd_lo = 0.0\n\n while (lbd_hi - lbd_lo) > tolerate:\n lbd_mid = (lbd_lo + lbd_hi) / 2.0\n nquery += 1\n if not self._is_label(x_0 + lbd_mid * theta, y_0):\n if self.targeted:\n lbd_lo = lbd_mid\n else:\n lbd_hi = lbd_mid\n else:\n if self.targeted:\n lbd_hi = lbd_mid\n else:\n lbd_lo = lbd_mid\n return lbd_hi, nquery\n\n def _fine_grained_binary_search_local(\n self,\n x_0: np.ndarray,\n y_0: int,\n theta: np.ndarray,\n target: int | None = None,\n initial_lbd: float = 1.0,\n tol: float = 1e-5,\n ) -> tuple[float, int]:\n \"\"\"\n Perform the line search in a local region plus binary search.\n Details in paper (Chen and Zhang, 2019), paper link: https://openreview.net/pdf?id=rJlk6iRqKX\n\n :param x_0: An array with the original input to be attacked.\n :param y_0: Target value.\n :param theta: Initial query direction.\n :param target: Target value. If `self.targeted` is true, it presents the targeted label. Defaults to None.\n :param initial_lbd: Previous solution. Defaults to 1.0.\n :param tol: Maximum tolerance of computed error. Stop computing if tol is reached.\n Defaults to 1e-5.\n :return: optimal solution in local; the number of query performed\n \"\"\"\n nquery = 0\n lbd = initial_lbd\n # For targeted: we want to expand(x1.01) boundary away from targeted dataset\n # For untargeted, we want to slim(x0.99) the boundary toward the original dataset\n if (self.targeted and not self._is_label(x_0 + lbd * theta, target)) or (\n not self.targeted and self._is_label(x_0 + lbd * theta, y_0)\n ):\n lbd_lo = lbd\n lbd_hi = lbd * 1.01\n nquery += 1\n while (self.targeted and not self._is_label(x_0 + lbd_hi * theta, target)) or (\n not self.targeted and self._is_label(x_0 + lbd_hi * theta, y_0)\n ):\n lbd_hi = lbd_hi * 1.01\n nquery += 1\n if lbd_hi > 20:\n return float(\"inf\"), nquery\n else:\n lbd_hi = lbd\n lbd_lo = lbd * 0.99\n nquery += 1\n while (self.targeted and self._is_label(x_0 + lbd_lo * theta, target)) or (\n not self.targeted and not self._is_label(x_0 + lbd_lo * theta, y_0)\n ):\n lbd_lo = lbd_lo * 0.99\n nquery += 1\n\n while (lbd_hi - lbd_lo) > tol:\n lbd_mid = (lbd_lo + lbd_hi) / 2.0\n nquery += 1\n if (self.targeted and self._is_label(x_0 + lbd_mid * theta, target)) or (\n not self.targeted and not self._is_label(x_0 + lbd_mid * theta, y_0)\n ):\n lbd_hi = lbd_mid\n else:\n lbd_lo = lbd_mid\n return lbd_hi, nquery\n\n def _is_label(self, x_0: np.ndarray, label: int | None) -> bool:\n \"\"\"\n Helper method to check if self.estimator predict input with label\n\n :param x_0: An array with the original input\n :param label: The predicted label\n :return: True if self.estimator predicts label for x_0; False otherwise\n \"\"\"\n if self.enable_clipped:\n x_0 = np.clip(x_0, self.clip_min, self.clip_max)\n pred = self.estimator.predict(np.expand_dims(x_0, axis=0), batch_size=self.batch_size)\n pred_y0 = np.argmax(pred)\n return pred_y0 == label\n\n def _predict_label(self, x_0: np.ndarray) -> np.signedinteger:\n \"\"\"\n Helper method to predict label for x_0\n\n :param x_0: An array with the original input\n :return: Predicted label\n \"\"\"\n if self.enable_clipped:\n x_0 = np.clip(x_0, self.clip_min, self.clip_max)\n pred = self.estimator.predict(np.expand_dims(x_0, axis=0), batch_size=self.batch_size)\n return np.argmax(pred)\n\n def _sign_grad(\n self, x_0: np.ndarray, y_0: int, epsilon: float, theta: np.ndarray, initial_lbd: float, target: int | None\n ) -> tuple[np.ndarray, int]:\n \"\"\"\n Evaluate the sign of gradient\n\n :param x_0: An array with the original inputs to be attacked.\n :param y_0: Target value.\n :param epsilon: A very small smoothing parameter.\n :param theta: Initial query direction.\n :param initial_lbd: Previous solution.\n :param target: Target value. If `self.targeted` is true, it presents the targeted label. Defaults to None.\n :return: the sign of gradient\n \"\"\"\n sign_grad = np.zeros(theta.shape).astype(np.float32)\n queries = 0\n # use orthogonal transform\n for _ in range(self.k): # for each u\n # Algorithm 1: Sign-OPT attack\n # A:Randomly sample u1, . . . , uQ from a Gaussian or Uniform distribution;\n u_g = np.random.randn(*theta.shape).astype(np.float32)\n # gaussian\n u_g /= np.linalg.norm(u_g)\n # function (3) in the paper\n new_theta = theta + epsilon * u_g\n new_theta /= np.linalg.norm(new_theta)\n sign = 1\n\n if self.targeted and self._is_label(x_0 + initial_lbd * new_theta, target):\n sign = -1\n elif not self.targeted and not self._is_label(x_0 + initial_lbd * new_theta, y_0):\n sign = -1\n\n queries += 1\n sign_grad += u_g * sign\n\n sign_grad /= self.k\n\n return sign_grad, queries\n\n def _attack(\n self,\n x_0: np.ndarray,\n y_0: int,\n target: int | None = None,\n x_init: np.ndarray | None = None,\n distortion: float | None = None,\n ) -> tuple[np.ndarray, np.ndarray, bool]:\n \"\"\"\n Perform attack\n\n :param x_0: An array with the original inputs to be attacked.\n :param y_0: Target value.\n :param target: Target value. If `self.targeted` is true, it presents the targeted label. Defaults to None.\n :param x_init: The pool of possible targets for finding initial direction. Only for targeted attack.\n :return: the adversarial sample to x_0\n \"\"\"\n query_count = 0\n ls_total = 0\n\n # init: Calculate a good starting point (direction)\n num_directions = self.num_trial\n best_theta, g_theta = np.zeros((0, 0)), float(\"inf\")\n if self.verbose:\n print(f\"Searching for the initial direction on {num_directions} random directions: \")\n if self.targeted and x_init is not None:\n if self.verbose:\n print(f\"this is targeted attack, org_label={y_0}, target={target}\")\n sample_count = 0\n for i, x_i in enumerate(x_init):\n # find a training data which label is target\n yi_pred = self._predict_label(x_i)\n query_count += 1\n if yi_pred != target:\n continue\n\n theta = x_i - x_0\n initial_lbd = np.linalg.norm(theta).item() # .item() convert numpy type to python type\n theta /= initial_lbd\n lbd, count = self._fine_grained_binary_search(x_0, y_0, theta, initial_lbd, g_theta, target)\n query_count += count\n if lbd < g_theta:\n best_theta, g_theta = theta, lbd\n sample_count += 1\n if sample_count >= self.num_trial or i > 500:\n break\n else:\n for i in range(num_directions):\n query_count += 1\n theta = np.random.randn(*x_0.shape).astype(np.float32) # gaussian distortion\n # register adv directions\n if not self._is_label(x_0 + theta, y_0):\n initial_lbd = np.linalg.norm(theta).item() # .item() convert numpy type to python type\n theta /= initial_lbd # l2 normalize: theta is normalized\n # getting smaller g_theta\n lbd, count = self._fine_grained_binary_search(x_0, y_0, theta, initial_lbd, g_theta)\n query_count += count\n if lbd < g_theta:\n best_theta, g_theta = theta, lbd\n if self.verbose:\n print(f\"Found distortion {g_theta} with iteration/num_directions={i}/{num_directions}\")\n\n # fail if it cannot find adv direction within `num_directions` Gaussian\n if g_theta == float(\"inf\"):\n if self.verbose:\n print(\"Couldn't find valid initial, failed\")\n return (\n x_0,\n np.zeros((0, 0)),\n False,\n )\n\n query_limit = self.query_limit\n alpha = self.alpha\n beta = self.beta\n timestart = time.time()\n # Begin Sign_OPT from here\n # Algorithm 1: Sign-OPT attack\n # A:Randomly sample u1, . . . , uQ from a Gaussian or Uniform distribution;\n # B:Compute g\u02c6 \u2190 ...\n # C:Update \u03b8t+1 \u2190 \u03b8t \u2212 \u03b7g\u02c6;\n # D:Evaluate g(\u03b8t) using the same search algorithm in\n # Cheng et al. (2019) https://openreview.net/pdf?id=rJlk6iRqKX,\n x_g, g_g = best_theta, g_theta\n distortions = [g_g]\n iterations = self.max_iter\n for i in range(iterations):\n sign_gradient, grad_queries = self._sign_grad(x_0, y_0, self.epsilon, x_g, g_g, target)\n\n # Line search of the step size of gradient descent\n ls_count = 0\n min_theta = x_g # next theta\n min_g2 = g_g # current g_theta\n # new_theta = np.zeros((0, 0))\n for _ in range(15):\n # Algorithm 1: Sign-OPT attack\n new_theta = x_g - alpha * sign_gradient\n new_theta /= np.linalg.norm(new_theta)\n # Algorithm 1: Sign-OPT attack\n # D:Evaluate g(\u03b8t) using the same search algorithm in\n # Cheng et al. (2019) https://openreview.net/pdf?id=rJlk6iRqKX,\n # **Algorithm 1 Compute g(\u03b8) locally**\n new_g2, count = self._fine_grained_binary_search_local(\n x_0, y_0, new_theta, target, initial_lbd=min_g2, tol=beta / 500\n )\n ls_count += count\n alpha = alpha * 2 # gradually increasing step size\n if new_g2 < min_g2:\n min_theta = new_theta\n min_g2 = new_g2\n else:\n break # meaning alpha is too big, so it needs to be reduced.\n\n if min_g2 >= g_g: # if the above code failed for the init alpha, we then try to decrease alpha\n for _ in range(15):\n alpha = alpha * 0.25\n new_theta = x_g - alpha * sign_gradient\n new_theta /= np.linalg.norm(new_theta)\n new_g2, count = self._fine_grained_binary_search_local(\n x_0, y_0, new_theta, target, initial_lbd=min_g2, tol=beta / 500\n )\n ls_count += count\n if new_g2 < g_g:\n min_theta = new_theta\n min_g2 = new_g2\n break\n\n if alpha < 1e-4: # if the above two blocks of code failed\n alpha = 1.0\n if self.verbose:\n print(\"Warning: not moving\")\n beta = beta * 0.1\n if beta < 1e-8:\n break\n\n # if all attempts failed, min_theta, min_g2 will be the current theta (i.e. not moving)\n x_g, g_g = min_theta, min_g2\n\n query_count += grad_queries + ls_count\n ls_total += ls_count\n distortions.append(g_g)\n\n if query_count > query_limit:\n if self.verbose:\n print(f\"query_count={query_count} > query_limit={query_limit}\")\n break\n\n if self.verbose and (i + 1) % 10 == 0:\n print(f\"Iteration {i+1} distortion {g_g} num_queries {query_count}\")\n timeend = time.time()\n succeed = False\n if self.targeted is False and (distortion is None or g_g < distortion):\n succeed = True\n if self.verbose:\n print(\n f\"Succeed distortion {g_g} org_label {y_0} predict_lable {target} \\\n queries {query_count} Line Search queries {ls_total}\"\n )\n target_pred = self._predict_label(x_0 + g_g * x_g)\n if target_pred == y_0:\n print(f\"WARNING: prediction on adv {target_pred} == org label {y_0}\")\n # return self._clip_value(x_0 + g_g * x_g), g_g * x_g, True\n elif self.targeted and self._is_label(x_0 + g_g * x_g, target):\n succeed = True\n if self.verbose:\n print(\n f\"Adversarial Example Found Successfully: distortion {g_g} target, \\\n {target} queries {query_count} Line Search queries {ls_total} Time: {timeend-timestart} seconds\"\n )\n # return self._clip_value(x_0 + g_g * x_g), g_g * x_g, True\n else:\n succeed = False\n if self.verbose:\n print(f\"Failed: distortion {g_g}\")\n return self._clip_value(x_0 + g_g * x_g), g_g * x_g, succeed\n\n def _clip_value(self, x_0: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply clipping to input array\n\n :param x_0: An array to be clipped\n :return: The array after clipping if clipping is enabled\n \"\"\"\n if self.enable_clipped:\n x_0 = np.clip(x_0, self.clip_min, self.clip_max)\n return x_0\n\n def _check_params(self) -> None:\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The argument `targeted` has to be of type bool.\")\n\n if self.epsilon <= 0:\n raise ValueError(\"The initial step size for the step towards the target must be positive.\")\n\n if not isinstance(self.num_trial, int) or self.num_trial < 0:\n raise ValueError(\"The number of trials must be a non-negative integer.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.query_limit, int) or self.query_limit <= 0:\n raise ValueError(\"The number of query_limit must be a positive integer.\")\n\n if not isinstance(self.k, int) or self.k <= 0:\n raise ValueError(\n \"The number of random directions (for estimating the gradient) must be a positive integer.\"\n )\n\n if self.alpha <= 0:\n raise ValueError(\"The value of alpha must be positive.\")\n\n if self.beta <= 0:\n raise ValueError(\"The value of beta must be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/simba.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the black-box attack `SimBA`.\n\n| Paper link: https://arxiv.org/abs/1905.07121\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.fftpack import idct\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.utils import is_probability\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SimBA(EvasionAttack):\n \"\"\"\n This class implements the black-box attack `SimBA`.\n\n | Paper link: https://arxiv.org/abs/1905.07121\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"attack\",\n \"max_iter\",\n \"epsilon\",\n \"order\",\n \"freq_dim\",\n \"stride\",\n \"targeted\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin, NeuralNetworkMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n attack: str = \"dct\",\n max_iter: int = 3000,\n order: str = \"random\",\n epsilon: float = 0.1,\n freq_dim: int = 4,\n stride: int = 1,\n targeted: bool = False,\n batch_size: int = 1,\n verbose: bool = True,\n ):\n \"\"\"\n Create a SimBA (dct) attack instance.\n\n :param classifier: A trained classifier predicting probabilities and not logits.\n :param attack: attack type: pixel (px) or DCT (dct) attacks\n :param max_iter: The maximum number of iterations.\n :param epsilon: Overshoot parameter.\n :param order: order of pixel attacks: random or diagonal (diag)\n :param freq_dim: dimensionality of 2D frequency space (DCT).\n :param stride: stride for block order (DCT).\n :param targeted: perform targeted attack\n :param batch_size: Batch size (but, batch process unavailable in this implementation)\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.attack = attack\n self.max_iter = max_iter\n self.epsilon = epsilon\n self.order = order\n self.freq_dim = freq_dim\n self.stride = stride\n self._targeted = targeted\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: An array with the true or target labels.\n :return: An array holding the adversarial examples.\n \"\"\"\n x = x.astype(ART_NUMPY_DTYPE)\n x_adv = x.copy()\n\n y_prob_pred = self.estimator.predict(x, batch_size=self.batch_size)\n\n if not is_probability(y_prob_pred[0]):\n raise ValueError(\n \"This attack requires an estimator predicting probabilities. It looks like the current \"\n \"estimator is not predicting probabilities\"\n )\n\n if self.estimator.nb_classes == 2 and y_prob_pred.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if divmod(x.shape[2] - self.freq_dim, self.stride)[1] != 0:\n raise ValueError(\n \"Incompatible value combination in image height/width, freq_dim and stride detected. \"\n \"Adapt these parameters to fulfill the following conditions: \"\n \"divmod(image_height - freq_dim, stride)[1] == 0 \"\n \"and \"\n \"divmod(image_width - freq_dim, stride)[1] == 0\"\n )\n\n if y is None:\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n logger.info(\"Using the model prediction as the correct label for SimBA.\")\n y_i = np.argmax(y_prob_pred, axis=1)\n else:\n y_i = np.argmax(y, axis=1)\n\n for i_sample in trange(x.shape[0], desc=\"SimBA - sample\", disable=not self.verbose):\n\n desired_label = y_i[i_sample]\n\n current_label = np.argmax(y_prob_pred, axis=1)[i_sample]\n last_prob = y_prob_pred[i_sample].reshape(-1)[desired_label]\n\n if self.estimator.channels_first:\n nb_channels = x.shape[1]\n else:\n nb_channels = x.shape[3]\n\n n_dims = np.prod(x[[0]].shape)\n\n if self.attack == \"px\":\n if self.order == \"diag\":\n indices = self.diagonal_order(x.shape[2], nb_channels)[: self.max_iter]\n elif self.order == \"random\":\n indices = np.random.permutation(n_dims)[: self.max_iter]\n indices_size = len(indices)\n while indices_size < self.max_iter:\n if self.order == \"diag\":\n tmp_indices = self.diagonal_order(x.shape[2], nb_channels)\n elif self.order == \"random\":\n tmp_indices = np.random.permutation(n_dims)\n indices = np.hstack((indices, tmp_indices))[: self.max_iter]\n indices_size = len(indices)\n elif self.attack == \"dct\":\n indices = self._block_order(x.shape[2], nb_channels, initial_size=self.freq_dim, stride=self.stride)[\n : self.max_iter\n ]\n indices_size = len(indices)\n while indices_size < self.max_iter:\n tmp_indices = self._block_order(\n x.shape[2], nb_channels, initial_size=self.freq_dim, stride=self.stride\n )\n indices = np.hstack((indices, tmp_indices))[: self.max_iter]\n indices_size = len(indices)\n\n def trans(var_z):\n return self._block_idct(var_z, block_size=x.shape[2])\n\n clip_min = -np.inf\n clip_max = np.inf\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n\n term_flag = 1\n if self.targeted:\n if desired_label != current_label:\n term_flag = 0\n else:\n if desired_label == current_label:\n term_flag = 0\n\n nb_iter = 0\n while term_flag == 0 and nb_iter < self.max_iter:\n diff = np.zeros(n_dims).astype(ART_NUMPY_DTYPE)\n diff[indices[nb_iter]] = self.epsilon\n\n if self.attack == \"dct\":\n left_preds = self.estimator.predict(\n np.clip(x[[i_sample]] - trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max),\n batch_size=self.batch_size,\n )\n elif self.attack == \"px\":\n left_preds = self.estimator.predict(\n np.clip(x[[i_sample]] - diff.reshape(x[[i_sample]].shape), clip_min, clip_max),\n batch_size=self.batch_size,\n )\n left_prob = left_preds.reshape(-1)[desired_label]\n\n if self.attack == \"dct\":\n right_preds = self.estimator.predict(\n np.clip(x[[i_sample]] + trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max),\n batch_size=self.batch_size,\n )\n elif self.attack == \"px\":\n right_preds = self.estimator.predict(\n np.clip(x[[i_sample]] + diff.reshape(x[[i_sample]].shape), clip_min, clip_max),\n batch_size=self.batch_size,\n )\n right_prob = right_preds.reshape(-1)[desired_label]\n\n # Use (2 * int(self.targeted) - 1) to shorten code?\n if self.targeted:\n if left_prob > last_prob:\n if left_prob > right_prob:\n if self.attack == \"dct\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] - trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max\n )\n elif self.attack == \"px\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] - diff.reshape(x[[i_sample]].shape), clip_min, clip_max\n )\n last_prob = left_prob\n current_label = np.argmax(left_preds, axis=1)[0]\n else:\n if self.attack == \"dct\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max\n )\n elif self.attack == \"px\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + diff.reshape(x[[i_sample]].shape), clip_min, clip_max\n )\n last_prob = right_prob\n current_label = np.argmax(right_preds, axis=1)[0]\n else:\n if right_prob > last_prob:\n if self.attack == \"dct\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max\n )\n elif self.attack == \"px\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + diff.reshape(x[[i_sample]].shape), clip_min, clip_max\n )\n last_prob = right_prob\n current_label = np.argmax(right_preds, axis=1)[0]\n else:\n if left_prob < last_prob:\n if left_prob < right_prob:\n if self.attack == \"dct\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] - trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max\n )\n elif self.attack == \"px\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] - diff.reshape(x[[i_sample]].shape), clip_min, clip_max\n )\n last_prob = left_prob\n current_label = np.argmax(left_preds, axis=1)[0]\n else:\n if self.attack == \"dct\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max\n )\n elif self.attack == \"px\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + diff.reshape(x[[i_sample]].shape), clip_min, clip_max\n )\n last_prob = right_prob\n current_label = np.argmax(right_preds, axis=1)[0]\n else:\n if right_prob < last_prob:\n if self.attack == \"dct\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + trans(diff.reshape(x[[i_sample]].shape)), clip_min, clip_max\n )\n elif self.attack == \"px\":\n x[[i_sample]] = np.clip(\n x[[i_sample]] + diff.reshape(x[[i_sample]].shape), clip_min, clip_max\n )\n last_prob = right_prob\n current_label = np.argmax(right_preds, axis=1)[0]\n\n if self.targeted:\n if desired_label == current_label:\n term_flag = 1\n else:\n if desired_label != current_label:\n term_flag = 1\n\n nb_iter = nb_iter + 1\n\n if nb_iter < self.max_iter:\n logger.info(\n \"SimBA (%s) %s attack succeed\", self.attack, [\"non-targeted\", \"targeted\"][int(self.targeted)]\n )\n else:\n logger.info(\n \"SimBA (%s) %s attack failed\", self.attack, [\"non-targeted\", \"targeted\"][int(self.targeted)]\n )\n\n x_adv[i_sample] = x[i_sample]\n\n return x_adv\n\n def _check_params(self) -> None:\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if self.epsilon < 0:\n raise ValueError(\"The overshoot parameter must not be negative.\")\n\n if self.batch_size != 1:\n raise ValueError(\"The batch size `batch_size` has to be 1 in this implementation.\")\n\n if not isinstance(self.stride, int) or self.stride <= 0:\n raise ValueError(\"The `stride` value must be a positive integer.\")\n\n if not isinstance(self.freq_dim, int) or self.freq_dim <= 0:\n raise ValueError(\"The `freq_dim` value must be a positive integer.\")\n\n if self.order not in (\"random\", \"diag\"):\n raise ValueError(\"The order of pixel attacks has to be `random` or `diag`.\")\n\n if self.attack not in (\"px\", \"dct\"):\n raise ValueError(\"The attack type has to be `px` or `dct`.\")\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"`targeted` has to be a Boolean value.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n def _block_order(self, img_size, channels, initial_size=2, stride=1):\n \"\"\"\n Defines a block order, starting with top-left (initial_size x initial_size) submatrix\n expanding by stride rows and columns whenever exhausted\n randomized within the block and across channels.\n e.g. (initial_size=2, stride=1)\n [1, 3, 6]\n [2, 4, 9]\n [5, 7, 8]\n\n :param img_size: image size (i.e., width or height).\n :param channels: the number of channels.\n :param initial size: initial size for submatrix.\n :param stride: stride size for expansion.\n\n :return order: An array holding the block order of DCT attacks.\n \"\"\"\n order = np.zeros((channels, img_size, img_size)).astype(ART_NUMPY_DTYPE)\n total_elems = channels * initial_size * initial_size\n perm = np.random.permutation(total_elems)\n order[:, :initial_size, :initial_size] = perm.reshape((channels, initial_size, initial_size))\n for i in range(initial_size, img_size, stride):\n num_elems = channels * (2 * stride * i + stride * stride)\n perm = np.random.permutation(num_elems) + total_elems\n num_first = channels * stride * (stride + i)\n order[:, : (i + stride), i : (i + stride)] = perm[:num_first].reshape((channels, -1, stride))\n order[:, i : (i + stride), :i] = perm[num_first:].reshape((channels, stride, -1))\n total_elems += num_elems\n\n if self.estimator.channels_first:\n return order.reshape(1, -1).squeeze().argsort()\n\n return order.transpose((1, 2, 0)).reshape(1, -1).squeeze().argsort()\n\n def _block_idct(self, x, block_size=8, masked=False, ratio=0.5):\n \"\"\"\n Applies IDCT to each block of size block_size.\n\n :param x: An array with the inputs to be attacked.\n :param block_size: block size for DCT attacks.\n :param masked: use the mask.\n :param ratio: Ratio of the lowest frequency directions in order to make the adversarial perturbation in the low\n frequency space.\n\n :return var_z: An array holding the order of DCT attacks.\n \"\"\"\n if not self.estimator.channels_first:\n x = x.transpose(0, 3, 1, 2)\n var_z = np.zeros(x.shape).astype(ART_NUMPY_DTYPE)\n num_blocks = int(x.shape[2] / block_size)\n mask = np.zeros((x.shape[0], x.shape[1], block_size, block_size))\n if not isinstance(ratio, float):\n for i in range(x.shape[0]):\n mask[i, :, : int(block_size * ratio[i]), : int(block_size * ratio[i])] = 1\n else:\n mask[:, :, : int(block_size * ratio), : int(block_size * ratio)] = 1\n for i in range(num_blocks):\n for j in range(num_blocks):\n submat = x[:, :, (i * block_size) : ((i + 1) * block_size), (j * block_size) : ((j + 1) * block_size)]\n if masked:\n submat = submat * mask\n var_z[:, :, (i * block_size) : ((i + 1) * block_size), (j * block_size) : ((j + 1) * block_size)] = (\n idct(idct(submat, axis=3, norm=\"ortho\"), axis=2, norm=\"ortho\")\n )\n\n if self.estimator.channels_first:\n return var_z\n\n return var_z.transpose((0, 2, 3, 1))\n\n def diagonal_order(self, image_size, channels):\n \"\"\"\n Defines a diagonal order for pixel attacks.\n order is fixed across diagonals but are randomized across channels and within the diagonal\n e.g.\n [1, 2, 5]\n [3, 4, 8]\n [6, 7, 9]\n\n :param image_size: image size (i.e., width or height)\n :param channels: the number of channels\n\n :return order: An array holding the diagonal order of pixel attacks.\n \"\"\"\n x = np.arange(0, image_size).cumsum()\n order = np.zeros((image_size, image_size)).astype(ART_NUMPY_DTYPE)\n for i in range(image_size):\n order[i, : (image_size - i)] = i + x[i:]\n for i in range(1, image_size):\n reverse = order[image_size - i - 1].take(\n [i for i in range(i - 1, -1, -1)]\n ) # pylint: disable=unnecessary-comprehension\n order[i, (image_size - i) :] = image_size * image_size - 1 - reverse\n if channels > 1:\n order_2d = order\n order = np.zeros((channels, image_size, image_size))\n for i in range(channels):\n order[i, :, :] = 3 * order_2d + i\n elif channels == 1:\n order = np.expand_dims(order, axis=0)\n\n if self.estimator.channels_first:\n return order.reshape(1, -1).squeeze().argsort()\n\n return order.transpose((1, 2, 0)).reshape(1, -1).squeeze().argsort()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/spatial_transformation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the spatial transformation attack `SpatialTransformation` using translation and rotation of\ninputs. The attack conducts black-box queries to the target model in a grid search over possible translations and\nrotations to find optimal attack parameters.\n\n| Paper link: https://arxiv.org/abs/1712.02779\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.ndimage import rotate, shift\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpatialTransformation(EvasionAttack):\n \"\"\"\n Implementation of the spatial transformation attack using translation and rotation of inputs. The attack conducts\n black-box queries to the target model in a grid search over possible translations and rotations to find optimal\n attack parameters.\n\n | Paper link: https://arxiv.org/abs/1712.02779\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"max_translation\",\n \"num_translations\",\n \"max_rotation\",\n \"num_rotations\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n max_translation: float = 0.0,\n num_translations: int = 1,\n max_rotation: float = 0.0,\n num_rotations: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n :param classifier: A trained classifier.\n :param max_translation: The maximum translation in any direction as percentage of image size. The value is\n expected to be in the range `[0, 100]`.\n :param num_translations: The number of translations to search on grid spacing per direction.\n :param max_rotation: The maximum rotation in either direction in degrees. The value is expected to be in the\n range `[0, 180]`.\n :param num_rotations: The number of rotations to search on grid spacing.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.max_translation = max_translation\n self.num_translations = num_translations\n self.max_rotation = max_rotation\n self.num_rotations = num_rotations\n self.verbose = verbose\n self._check_params()\n\n self.fooling_rate: float | None = None\n self.attack_trans_x: int | None = None\n self.attack_trans_y: int | None = None\n self.attack_rot: float | None = None\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the adversarial examples.\n \"\"\"\n logger.info(\"Computing spatial transformation based on grid search.\")\n\n if len(x.shape) == 2:\n raise ValueError(\n \"Feature vectors detected. The attack can only be applied to data with spatial\" \"dimensions.\"\n )\n\n if self.attack_trans_x is None or self.attack_trans_y is None or self.attack_rot is None:\n\n y_pred = self.estimator.predict(x, batch_size=1)\n if self.estimator.nb_classes == 2 and y_pred.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n y_pred_max = np.argmax(y_pred, axis=1)\n\n nb_instances = len(x)\n\n # Determine grids\n max_num_pixel_trans_x = int(round((x.shape[1] * self.max_translation / 100.0)))\n max_num_pixel_trans_y = int(round((x.shape[2] * self.max_translation / 100.0)))\n\n grid_trans_x = [\n int(round(g))\n for g in list(\n np.linspace(\n -max_num_pixel_trans_x,\n max_num_pixel_trans_x,\n num=self.num_translations,\n )\n )\n ]\n grid_trans_y = [\n int(round(g))\n for g in list(\n np.linspace(\n -max_num_pixel_trans_y,\n max_num_pixel_trans_y,\n num=self.num_translations,\n )\n )\n ]\n grid_rot = list(np.linspace(-self.max_rotation, self.max_rotation, num=self.num_rotations))\n\n # Remove duplicates\n grid_trans_x = list(set(grid_trans_x))\n grid_trans_y = list(set(grid_trans_y))\n grid_rot = list(set(grid_rot))\n\n grid_trans_x.sort()\n grid_trans_y.sort()\n grid_rot.sort()\n\n # Search for worst case\n fooling_rate = 0.0\n x_adv = np.copy(x)\n trans_x = 0\n trans_y = 0\n rot = 0.0\n\n # Initialize progress bar\n pbar = tqdm(\n total=len(grid_trans_x) * len(grid_trans_y) * len(grid_rot),\n desc=\"Spatial transformation\",\n disable=not self.verbose,\n )\n\n for trans_x_i in grid_trans_x:\n for trans_y_i in grid_trans_y:\n for rot_i in grid_rot:\n\n # Generate the adversarial examples\n x_adv_i = self._perturb(x, trans_x_i, trans_y_i, rot_i)\n\n # Compute the error rate\n y_adv_i = np.argmax(self.estimator.predict(x_adv_i, batch_size=1), axis=1)\n fooling_rate_i = np.sum(y_pred_max != y_adv_i) / nb_instances\n\n if fooling_rate_i > fooling_rate:\n fooling_rate = fooling_rate_i\n trans_x = trans_x_i\n trans_y = trans_y_i\n rot = rot_i\n x_adv = np.copy(x_adv_i)\n pbar.update(1)\n pbar.close()\n\n self.fooling_rate = fooling_rate\n self.attack_trans_x = trans_x\n self.attack_trans_y = trans_y\n self.attack_rot = rot\n\n logger.info(\n \"Success rate of spatial transformation attack: %.2f%%\",\n 100 * self.fooling_rate,\n )\n logger.info(\"Attack-translation in x: %.2f%%\", self.attack_trans_x)\n logger.info(\"Attack-translation in y: %.2f%%\", self.attack_trans_y)\n logger.info(\"Attack-rotation: %.2f%%\", self.attack_rot)\n\n else:\n x_adv = self._perturb(x, self.attack_trans_x, self.attack_trans_y, self.attack_rot)\n\n return x_adv\n\n def _perturb(self, x: np.ndarray, trans_x: int, trans_y: int, rot: float) -> np.ndarray:\n if not self.estimator.channels_first:\n x_adv = shift(x, [0, trans_x, trans_y, 0])\n x_adv = rotate(x_adv, angle=rot, axes=(1, 2), reshape=False)\n elif self.estimator.channels_first:\n x_adv = shift(x, [0, 0, trans_x, trans_y])\n x_adv = rotate(x_adv, angle=rot, axes=(2, 3), reshape=False)\n else:\n raise ValueError(\"Unsupported channel_first value.\")\n\n if self.estimator.clip_values is not None:\n np.clip(\n x_adv,\n self.estimator.clip_values[0],\n self.estimator.clip_values[1],\n out=x_adv,\n )\n\n return x_adv\n\n def _check_params(self) -> None:\n if not isinstance(self.max_translation, (float, int)) or self.max_translation < 0 or self.max_translation > 100:\n raise ValueError(\"The maximum translation must be in the range [0, 100].\")\n\n if not isinstance(self.num_translations, int) or self.num_translations <= 0:\n raise ValueError(\"The number of translations must be a positive integer.\")\n\n if not isinstance(self.max_rotation, (float, int)) or self.max_rotation < 0 or self.max_translation > 180:\n raise ValueError(\"The maximum rotation must be in the range [0, 180].\")\n\n if not isinstance(self.num_rotations, int) or self.num_rotations <= 0:\n raise ValueError(\"The number of rotations must be a positive integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/square_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the `SquareAttack` attack.\n\n| Paper link: https://arxiv.org/abs/1912.00049\n\"\"\"\nfrom __future__ import annotations\n\nimport bisect\nfrom collections.abc import Callable\nimport logging\nimport math\nimport random\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SquareAttack(EvasionAttack):\n \"\"\"\n This class implements the `SquareAttack` attack.\n\n | Paper link: https://arxiv.org/abs/1912.00049\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"adv_criterion\",\n \"loss\",\n \"max_iter\",\n \"eps\",\n \"p_init\",\n \"nb_restarts\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\",\n norm: int | float | str = np.inf,\n adv_criterion: Callable[[np.ndarray, np.ndarray], bool] | None = None,\n loss: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None,\n max_iter: int = 100,\n eps: float = 0.3,\n p_init: float = 0.8,\n nb_restarts: int = 1,\n batch_size: int = 128,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.SquareAttack` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 1 or 2.\n :param adv_criterion: The criterion which the attack should use in determining adversariality.\n :param loss: The loss function which the attack should use for optimization.\n :param max_iter: Maximum number of iterations.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param p_init: Initial fraction of elements.\n :param nb_restarts: Number of restarts.\n :param batch_size: Batch size for estimator evaluations.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.norm = norm\n\n if adv_criterion is not None:\n self.adv_criterion = adv_criterion\n elif isinstance(self.estimator, ClassifierMixin):\n self.adv_criterion = lambda y_pred, y: np.argmax(y_pred, axis=1) != np.argmax(y, axis=1)\n else: # pragma: no cover\n raise ValueError(\"No acceptable adversarial criterion available.\")\n\n if loss is not None:\n self.loss = loss\n elif isinstance(self.estimator, ClassifierMixin):\n self.loss = self._get_logits_diff\n else: # pragma: no cover\n raise ValueError(\"No acceptable loss available.\")\n\n self.max_iter = max_iter\n self.eps = eps\n self.p_init = p_init\n self.nb_restarts = nb_restarts\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def _get_logits_diff(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:\n y_pred = self.estimator.predict(x, batch_size=self.batch_size)\n\n logit_correct = np.take_along_axis(y_pred, np.expand_dims(np.argmax(y, axis=1), axis=1), axis=1)\n logit_highest_incorrect = np.take_along_axis(\n y_pred, np.expand_dims(np.argsort(y_pred, axis=1)[:, -2], axis=1), axis=1\n )\n\n return (logit_correct - logit_highest_incorrect)[:, 0]\n\n def _get_percentage_of_elements(self, i_iter: int) -> float:\n i_p = i_iter / self.max_iter\n intervals = [0.001, 0.005, 0.02, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8]\n p_ratio = [1, 1 / 2, 1 / 4, 1 / 8, 1 / 16, 1 / 32, 1 / 64, 1 / 128, 1 / 256, 1 / 512]\n i_ratio = bisect.bisect_left(intervals, i_p)\n\n return self.p_init * p_ratio[i_ratio]\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :return: An array holding the adversarial examples.\n \"\"\"\n if x.ndim != 4: # pragma: no cover\n raise ValueError(\"Unrecognized input dimension. Attack can only be applied to image data.\")\n\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n if isinstance(self.estimator, ClassifierMixin):\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n # Use model predictions as true labels\n logger.info(\"Using model predictions as true labels.\")\n y = self.estimator.predict(x, batch_size=self.batch_size)\n if isinstance(self.estimator, ClassifierMixin):\n y = get_labels_np_array(y)\n\n if isinstance(self.estimator, ClassifierMixin):\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if self.estimator.channels_first:\n channels = x.shape[1]\n height = x.shape[2]\n width = x.shape[3]\n else:\n height = x.shape[1]\n width = x.shape[2]\n channels = x.shape[3]\n\n for _ in trange(self.nb_restarts, desc=\"SquareAttack - restarts\", disable=not self.verbose):\n\n # Determine correctly predicted samples\n y_pred = self.estimator.predict(x_adv, batch_size=self.batch_size)\n sample_is_robust = np.logical_not(self.adv_criterion(y_pred, y))\n\n if np.sum(sample_is_robust) == 0: # pragma: no cover\n break\n\n # x_robust = x_adv[sample_is_robust]\n x_robust = x[sample_is_robust]\n y_robust = y[sample_is_robust]\n sample_loss_init = self.loss(x_robust, y_robust)\n\n if self.norm in [np.inf, \"inf\"]:\n\n if self.estimator.channels_first:\n size = (x_robust.shape[0], channels, 1, width)\n else:\n size = (x_robust.shape[0], 1, width, channels)\n\n # Add vertical stripe perturbations\n x_robust_new = np.clip(\n x_robust + self.eps * np.random.choice([-1, 1], size=size),\n a_min=self.estimator.clip_values[0],\n a_max=self.estimator.clip_values[1],\n ).astype(ART_NUMPY_DTYPE)\n\n sample_loss_new = self.loss(x_robust_new, y_robust)\n loss_improved = (sample_loss_new - sample_loss_init) < 0.0\n\n x_robust[loss_improved] = x_robust_new[loss_improved]\n\n x_adv[sample_is_robust] = x_robust\n\n for i_iter in trange(\n self.max_iter, desc=\"SquareAttack - iterations\", leave=False, disable=not self.verbose\n ):\n\n percentage_of_elements = self._get_percentage_of_elements(i_iter)\n\n # Determine correctly predicted samples\n y_pred = self.estimator.predict(x_adv, batch_size=self.batch_size)\n sample_is_robust = np.logical_not(self.adv_criterion(y_pred, y))\n\n if np.sum(sample_is_robust) == 0: # pragma: no cover\n break\n\n x_robust = x_adv[sample_is_robust]\n x_init = x[sample_is_robust]\n y_robust = y[sample_is_robust]\n\n sample_loss_init = self.loss(x_robust, y_robust)\n\n height_tile = max(int(round(math.sqrt(percentage_of_elements * height * width))), 1)\n\n height_mid = np.random.randint(0, height - height_tile)\n width_start = np.random.randint(0, width - height_tile)\n\n delta_new = np.zeros(self.estimator.input_shape)\n\n if self.estimator.channels_first:\n delta_new[:, height_mid : height_mid + height_tile, width_start : width_start + height_tile] = (\n np.random.choice([-2 * self.eps, 2 * self.eps], size=[channels, 1, 1])\n )\n else:\n delta_new[height_mid : height_mid + height_tile, width_start : width_start + height_tile, :] = (\n np.random.choice([-2 * self.eps, 2 * self.eps], size=[1, 1, channels])\n )\n\n x_robust_new = x_robust + delta_new\n\n x_robust_new = np.minimum(np.maximum(x_robust_new, x_init - self.eps), x_init + self.eps)\n\n x_robust_new = np.clip(\n x_robust_new, a_min=self.estimator.clip_values[0], a_max=self.estimator.clip_values[1]\n ).astype(ART_NUMPY_DTYPE)\n\n sample_loss_new = self.loss(x_robust_new, y_robust)\n loss_improved = (sample_loss_new - sample_loss_init) < 0.0\n\n x_robust[loss_improved] = x_robust_new[loss_improved]\n\n x_adv[sample_is_robust] = x_robust\n\n elif self.norm == 2:\n\n n_tiles = 5\n\n height_tile = height // n_tiles\n\n def _get_perturbation(height):\n delta = np.zeros([height, height])\n gaussian_perturbation = np.zeros([height // 2, height])\n\n x_c = height // 4\n y_c = height // 2\n\n for i_y in range(y_c):\n gaussian_perturbation[\n max(x_c, 0) : min(x_c + (2 * i_y + 1), height // 2),\n max(0, y_c) : min(y_c + (2 * i_y + 1), height),\n ] += 1.0 / ((i_y + 1) ** 2)\n x_c -= 1\n y_c -= 1\n\n gaussian_perturbation /= np.sqrt(np.sum(gaussian_perturbation**2))\n\n delta[: height // 2] = gaussian_perturbation\n delta[height // 2 : height // 2 + gaussian_perturbation.shape[0]] = -gaussian_perturbation\n\n delta /= np.sqrt(np.sum(delta**2))\n\n if random.random() > 0.5:\n delta = np.transpose(delta)\n\n if random.random() > 0.5:\n delta = -delta\n\n return delta\n\n delta_init = np.zeros(x_robust.shape, dtype=ART_NUMPY_DTYPE)\n\n height_start = 0\n for _ in range(n_tiles):\n width_start = 0\n for _ in range(n_tiles):\n if self.estimator.channels_first:\n perturbation_size = (1, 1, height_tile, height_tile)\n random_size = (x_robust.shape[0], channels, 1, 1)\n else:\n perturbation_size = (1, height_tile, height_tile, 1)\n random_size = (x_robust.shape[0], 1, 1, channels)\n\n perturbation = _get_perturbation(height_tile).reshape(perturbation_size) * np.random.choice(\n [-1, 1], size=random_size\n )\n\n if self.estimator.channels_first:\n delta_init[\n :, :, height_start : height_start + height_tile, width_start : width_start + height_tile\n ] += perturbation\n else:\n delta_init[\n :, height_start : height_start + height_tile, width_start : width_start + height_tile, :\n ] += perturbation\n width_start += height_tile\n height_start += height_tile\n\n x_robust_new = np.clip(\n x_robust + delta_init / np.sqrt(np.sum(delta_init**2, axis=(1, 2, 3), keepdims=True)) * self.eps,\n self.estimator.clip_values[0],\n self.estimator.clip_values[1],\n )\n\n sample_loss_new = self.loss(x_robust_new, y_robust)\n loss_improved = (sample_loss_new - sample_loss_init) < 0.0\n\n x_robust[loss_improved] = x_robust_new[loss_improved]\n\n x_adv[sample_is_robust] = x_robust\n\n for i_iter in trange(\n self.max_iter, desc=\"SquareAttack - iterations\", leave=False, disable=not self.verbose\n ):\n\n percentage_of_elements = self._get_percentage_of_elements(i_iter)\n\n # Determine correctly predicted samples\n y_pred = self.estimator.predict(x_adv, batch_size=self.batch_size)\n sample_is_robust = np.logical_not(self.adv_criterion(y_pred, y))\n\n if np.sum(sample_is_robust) == 0: # pragma: no cover\n break\n\n x_robust = x_adv[sample_is_robust]\n x_init = x[sample_is_robust]\n y_robust = y[sample_is_robust]\n\n sample_loss_init = self.loss(x_robust, y_robust)\n\n delta_x_robust_init = x_robust - x_init\n\n height_tile = max(int(round(math.sqrt(percentage_of_elements * height * width))), 3)\n\n if height_tile % 2 == 0:\n height_tile += 1\n height_tile_2 = height_tile\n\n height_start = np.random.randint(0, height - height_tile)\n width_start = np.random.randint(0, width - height_tile)\n\n new_deltas_mask = np.zeros(x_init.shape)\n if self.estimator.channels_first:\n new_deltas_mask[\n :, :, height_start : height_start + height_tile, width_start : width_start + height_tile\n ] = 1.0\n w_1_norm = np.sqrt(\n np.sum(\n delta_x_robust_init[\n :,\n :,\n height_start : height_start + height_tile,\n width_start : width_start + height_tile,\n ]\n ** 2,\n axis=(2, 3),\n keepdims=True,\n )\n )\n else:\n new_deltas_mask[\n :, height_start : height_start + height_tile, width_start : width_start + height_tile, :\n ] = 1.0\n w_1_norm = np.sqrt(\n np.sum(\n delta_x_robust_init[\n :,\n height_start : height_start + height_tile,\n width_start : width_start + height_tile,\n :,\n ]\n ** 2,\n axis=(1, 2),\n keepdims=True,\n )\n )\n\n height_2_start = np.random.randint(0, height - height_tile_2)\n width_2_start = np.random.randint(0, width - height_tile_2)\n\n new_deltas_mask_2 = np.zeros(x_init.shape)\n if self.estimator.channels_first:\n new_deltas_mask_2[\n :,\n :,\n height_2_start : height_2_start + height_tile_2,\n width_2_start : width_2_start + height_tile_2,\n ] = 1.0\n else:\n new_deltas_mask_2[\n :,\n height_2_start : height_2_start + height_tile_2,\n width_2_start : width_2_start + height_tile_2,\n :,\n ] = 1.0\n\n norms_x_robust = np.sqrt(np.sum((x_robust - x_init) ** 2, axis=(1, 2, 3), keepdims=True))\n w_norm = np.sqrt(\n np.sum(\n (delta_x_robust_init * np.maximum(new_deltas_mask, new_deltas_mask_2)) ** 2,\n axis=(1, 2, 3),\n keepdims=True,\n )\n )\n\n if self.estimator.channels_first:\n new_deltas_size = [x_init.shape[0], channels, height_tile, height_tile]\n random_choice_size = [x_init.shape[0], channels, 1, 1]\n perturbation_size = (1, 1, height_tile, height_tile)\n else:\n new_deltas_size = [x_init.shape[0], height_tile, height_tile, channels]\n random_choice_size = [x_init.shape[0], 1, 1, channels]\n perturbation_size = (1, height_tile, height_tile, 1)\n\n delta_new = (\n np.ones(new_deltas_size)\n * _get_perturbation(height_tile).reshape(perturbation_size)\n * np.random.choice([-1, 1], size=random_choice_size)\n )\n\n if self.estimator.channels_first:\n delta_new += delta_x_robust_init[\n :, :, height_start : height_start + height_tile, width_start : width_start + height_tile\n ] / (np.maximum(1e-9, w_1_norm))\n else:\n delta_new += delta_x_robust_init[\n :, height_start : height_start + height_tile, width_start : width_start + height_tile, :\n ] / (np.maximum(1e-9, w_1_norm))\n\n diff_norm = (self.eps * np.ones(delta_new.shape)) ** 2 - norms_x_robust**2\n diff_norm[diff_norm < 0.0] = 0.0\n\n if self.estimator.channels_first:\n delta_new /= np.sqrt(np.sum(delta_new**2, axis=(2, 3), keepdims=True)) * np.sqrt(\n diff_norm / channels + w_norm**2\n )\n delta_x_robust_init[\n :,\n :,\n height_2_start : height_2_start + height_tile_2,\n width_2_start : width_2_start + height_tile_2,\n ] = 0.0\n delta_x_robust_init[\n :, :, height_start : height_start + height_tile, width_start : width_start + height_tile\n ] = delta_new\n else:\n delta_new /= np.sqrt(np.sum(delta_new**2, axis=(1, 2), keepdims=True)) * np.sqrt(\n diff_norm / channels + w_norm**2\n )\n delta_x_robust_init[\n :,\n height_2_start : height_2_start + height_tile_2,\n width_2_start : width_2_start + height_tile_2,\n :,\n ] = 0.0\n delta_x_robust_init[\n :, height_start : height_start + height_tile, width_start : width_start + height_tile, :\n ] = delta_new\n\n x_robust_new = np.clip(\n x_init\n + self.eps\n * delta_x_robust_init\n / np.sqrt(np.sum(delta_x_robust_init**2, axis=(1, 2, 3), keepdims=True)),\n self.estimator.clip_values[0],\n self.estimator.clip_values[1],\n )\n\n sample_loss_new = self.loss(x_robust_new, y_robust)\n loss_improved = (sample_loss_new - sample_loss_init) < 0.0\n\n x_robust[loss_improved] = x_robust_new[loss_improved]\n\n x_adv[sample_is_robust] = x_robust\n\n return x_adv\n\n def _check_params(self) -> None:\n if self.norm not in [1, 2, np.inf, \"inf\"]:\n raise ValueError('The argument norm has to be either 1, 2, np.inf, or \"inf\".')\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The argument max_iter has to be of type int and larger than zero.\")\n\n if not isinstance(self.eps, (int, float)) or self.eps <= 0.0:\n raise ValueError(\"The argument eps has to be either of type int or float and larger than zero.\")\n\n if not isinstance(self.p_init, (int, float)) or self.p_init <= 0.0 or self.p_init >= 1.0:\n raise ValueError(\"The argument p_init has to be either of type int or float and in range [0, 1].\")\n\n if not isinstance(self.nb_restarts, int) or self.nb_restarts <= 0:\n raise ValueError(\"The argument nb_restarts has to be of type int and larger than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The argument batch_size has to be of type int and larger than zero.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/targeted_universal_perturbation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the universal adversarial perturbations attack `TargetedUniversalPerturbation`.\n\n| Paper link: https://arxiv.org/abs/1911.06502\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport random\nimport types\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import projection\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass TargetedUniversalPerturbation(EvasionAttack):\n \"\"\"\n Implementation of the attack from Hirano and Takemoto (2019). Computes a fixed perturbation to be applied to all\n future inputs. To this end, it can use any adversarial attack method.\n\n | Paper link: https://arxiv.org/abs/1911.06502\n \"\"\"\n\n attacks_dict = {\n \"fgsm\": \"art.attacks.evasion.fast_gradient.FastGradientMethod\",\n \"simba\": \"art.attacks.evasion.simba.SimBA\",\n }\n attack_params = EvasionAttack.attack_params + [\"attacker\", \"attacker_params\", \"delta\", \"max_iter\", \"eps\", \"norm\"]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n attacker: str = \"fgsm\",\n attacker_params: dict[str, Any] | None = None,\n delta: float = 0.2,\n max_iter: int = 20,\n eps: float = 10.0,\n norm: int | float | str = np.inf,\n ):\n \"\"\"\n :param classifier: A trained classifier.\n :param attacker: Adversarial attack name. Default is 'fgsm'. Supported names: 'simba'.\n :param attacker_params: Parameters specific to the adversarial attack. If this parameter is not specified,\n the default parameters of the chosen attack will be used.\n :param delta: The maximum acceptable rate of correctly classified adversarial examples by the classifier.\n The attack will stop when the targeted success rate exceeds `(1 - delta)`.\n 'delta' should be in the range `[0, 1]`.\n :param max_iter: The maximum number of iterations for computing universal perturbation.\n :param eps: The perturbation magnitude, which controls the strength of the universal perturbation applied\n to the input samples. A larger `eps` value will result in a more noticeable perturbation,\n potentially leading to higher attack success rates but also increasing the visual distortion\n in the generated adversarial examples. Default is `10.0`.\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 2\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.attacker = attacker\n self.attacker_params = attacker_params\n self.delta = delta\n self.max_iter = max_iter\n self.eps = eps\n self.norm = norm\n self._targeted = True\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: The target labels for the targeted perturbation. The shape of y should match the number of instances\n in x.\n :return: An array holding the adversarial examples.\n :raises: `ValueError`: if the labels `y` are None or if the attack has not been tested for binary\n classification with a single output classifier.\n \"\"\"\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n logger.info(\"Computing targeted universal perturbation based on %s attack.\", self.attacker)\n\n # Init universal perturbation\n noise = np.zeros_like(x[[0]])\n fooling_rate = 0.0\n targeted_success_rate = 0.0\n nb_instances = len(x)\n\n # Instantiate the middle attacker and get the predicted labels\n attacker = self._get_attack(self.attacker, self.attacker_params)\n pred_y = self.estimator.predict(x, batch_size=1)\n pred_y_max = np.argmax(pred_y, axis=1)\n\n # Start to generate the adversarial examples\n nb_iter = 0\n while targeted_success_rate < 1.0 - self.delta and nb_iter < self.max_iter:\n # Go through all the examples randomly\n rnd_idx = random.sample(range(nb_instances), nb_instances)\n\n # Go through the data set and compute the perturbation increments sequentially\n for _, (e_x, e_y) in enumerate(zip(x[rnd_idx], y[rnd_idx])):\n x_i = e_x[None, ...]\n y_i = e_y[None, ...]\n\n current_label = np.argmax(self.estimator.predict(x_i + noise)[0])\n target_label = np.argmax(y_i)\n\n if current_label != target_label:\n # Compute adversarial perturbation\n adv_xi = attacker.generate(x_i + noise, y=y_i)\n\n new_label = np.argmax(self.estimator.predict(adv_xi)[0])\n\n # If the class has changed, update v\n if new_label == target_label:\n noise = adv_xi - x_i\n\n # Project on L_p ball\n noise = projection(noise, self.eps, self.norm)\n nb_iter += 1\n\n # Apply attack and clip\n x_adv = x + noise\n if hasattr(self.estimator, \"clip_values\") and self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = np.clip(x_adv, clip_min, clip_max)\n\n # Compute the error rate\n y_adv = np.argmax(self.estimator.predict(x_adv, batch_size=1), axis=1)\n fooling_rate = np.sum(pred_y_max != y_adv) / nb_instances\n targeted_success_rate = np.sum(y_adv == np.argmax(y, axis=1)) / nb_instances\n\n self.fooling_rate = fooling_rate\n self.targeted_success_rate = targeted_success_rate\n self.converged = nb_iter < self.max_iter\n self.noise = noise\n logger.info(\"Fooling rate of universal perturbation attack: %.2f%%\", 100 * fooling_rate)\n logger.info(\"Targeted success rate of universal perturbation attack: %.2f%%\", 100 * targeted_success_rate)\n\n return x_adv\n\n def _check_params(self) -> None:\n if not isinstance(self.delta, (float, int)) or self.delta < 0 or self.delta > 1:\n raise ValueError(\"The desired accuracy must be in the range [0, 1].\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if not isinstance(self.eps, (float, int)) or self.eps <= 0:\n raise ValueError(\"The eps coefficient must be a positive float.\")\n\n def _get_attack(self, a_name: str, params: dict[str, Any] | None = None) -> EvasionAttack:\n \"\"\"\n Get an attack object from its name.\n\n :param a_name: attack name.\n :param params: attack params.\n :return: attack object\n \"\"\"\n try:\n attack_class = self._get_class(self.attacks_dict[a_name])\n a_instance = attack_class(self.estimator) # type: ignore\n\n if params:\n a_instance.set_params(**params)\n\n return a_instance\n\n except KeyError:\n raise NotImplementedError(f\"{a_name} attack not supported\") from KeyError\n\n @staticmethod\n def _get_class(class_name: str) -> types.ModuleType:\n \"\"\"\n Get a class module from its name.\n\n :param class_name: Full name of a class.\n :return: The class `module`.\n \"\"\"\n sub_mods = class_name.split(\".\")\n module_ = __import__(\".\".join(sub_mods[:-1]), fromlist=sub_mods[-1])\n class_module = getattr(module_, sub_mods[-1])\n\n return class_module\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/universal_perturbation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the universal adversarial perturbations attack `UniversalPerturbation`. This is a white-box\nattack.\n\n| Paper link: https://arxiv.org/abs/1610.08401\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport random\nimport types\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import projection, get_labels_np_array, check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass UniversalPerturbation(EvasionAttack):\n \"\"\"\n Implementation of the attack from Moosavi-Dezfooli et al. (2016). Computes a fixed perturbation to be applied to all\n future inputs. To this end, it can use any adversarial attack method.\n\n | Paper link: https://arxiv.org/abs/1610.08401\n \"\"\"\n\n attacks_dict = {\n \"carlini\": \"art.attacks.evasion.carlini.CarliniL2Method\",\n \"carlini_inf\": \"art.attacks.evasion.carlini.CarliniLInfMethod\",\n \"deepfool\": \"art.attacks.evasion.deepfool.DeepFool\",\n \"ead\": \"art.attacks.evasion.elastic_net.ElasticNet\",\n \"fgsm\": \"art.attacks.evasion.fast_gradient.FastGradientMethod\",\n \"bim\": \"art.attacks.evasion.iterative_method.BasicIterativeMethod\",\n \"pgd\": \"art.attacks.evasion.projected_gradient_descent.projected_gradient_descent.ProjectedGradientDescent\",\n \"newtonfool\": \"art.attacks.evasion.newtonfool.NewtonFool\",\n \"jsma\": \"art.attacks.evasion.saliency_map.SaliencyMapMethod\",\n \"vat\": \"art.attacks.evasion.virtual_adversarial.VirtualAdversarialMethod\",\n \"simba\": \"art.attacks.evasion.simba.SimBA\",\n }\n attack_params = EvasionAttack.attack_params + [\n \"attacker\",\n \"attacker_params\",\n \"delta\",\n \"max_iter\",\n \"eps\",\n \"norm\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n attacker: str = \"deepfool\",\n attacker_params: dict[str, Any] | None = None,\n delta: float = 0.2,\n max_iter: int = 20,\n eps: float = 10.0,\n norm: int | float | str = np.inf,\n batch_size: int = 32,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n :param classifier: A trained classifier.\n :param attacker: Adversarial attack name. Default is 'deepfool'. Supported names: 'carlini', 'carlini_inf',\n 'deepfool', 'fgsm', 'bim', 'pgd', 'margin', 'ead', 'newtonfool', 'jsma', 'vat', 'simba'.\n :param attacker_params: Parameters specific to the adversarial attack. If this parameter is not specified,\n the default parameters of the chosen attack will be used.\n :param delta: desired accuracy\n :param max_iter: The maximum number of iterations for computing universal perturbation.\n :param eps: Attack step size (input variation).\n :param norm: The norm of the adversarial perturbation. Possible values: \"inf\", np.inf, 2.\n :param batch_size: Batch size for model evaluations in UniversalPerturbation.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.attacker = attacker\n self.attacker_params = attacker_params\n self.delta = delta\n self.max_iter = max_iter\n self.eps = eps\n self.norm = norm\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n # Attack properties\n self._fooling_rate: float | None = None\n self._converged: bool | None = None\n self._noise: np.ndarray | None = None\n\n @property\n def fooling_rate(self) -> float | None:\n \"\"\"\n The fooling rate of the universal perturbation on the most recent call to `generate`.\n\n :return: Fooling Rate.\n \"\"\"\n return self._fooling_rate\n\n @property\n def converged(self) -> bool | None:\n \"\"\"\n The convergence of universal perturbation generation.\n\n :return: `True` if generation of universal perturbation has converged.\n \"\"\"\n return self._converged\n\n @property\n def noise(self) -> np.ndarray | None:\n \"\"\"\n The universal perturbation.\n\n :return: Universal perturbation.\n \"\"\"\n return self._noise\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the adversarial examples.\n \"\"\"\n logger.info(\"Computing universal perturbation based on %s attack.\", self.attacker)\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n # Use model predictions as true labels\n logger.info(\"Using model predictions as true labels.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n y_index = np.argmax(y, axis=1)\n\n # Init universal perturbation\n noise = np.zeros_like(x[[0]])\n fooling_rate = 0.0\n nb_instances = len(x)\n\n # Instantiate the middle attacker\n attacker = self._get_attack(self.attacker, self.attacker_params)\n\n # Generate the adversarial examples\n nb_iter = 0\n pbar = tqdm(total=self.max_iter, desc=\"Universal perturbation\", disable=not self.verbose)\n\n while fooling_rate < 1.0 - self.delta and nb_iter < self.max_iter:\n # Go through all the examples randomly\n rnd_idx = random.sample(range(nb_instances), nb_instances)\n\n # Go through the data set and compute the perturbation increments sequentially\n for j, ex in enumerate(x[rnd_idx]):\n x_i = ex[None, ...]\n\n current_label = np.argmax(self.estimator.predict(x_i + noise)[0])\n original_label = y_index[rnd_idx][j]\n\n if current_label == original_label:\n # Compute adversarial perturbation\n adv_xi = attacker.generate(x_i + noise, y=y[rnd_idx][[j]])\n new_label = np.argmax(self.estimator.predict(adv_xi)[0])\n\n # If the class has changed, update v\n if current_label != new_label:\n noise = adv_xi - x_i\n\n # Project on L_p ball\n noise = projection(noise, self.eps, self.norm)\n nb_iter += 1\n pbar.update(1)\n\n # Apply attack and clip\n x_adv = x + noise\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = np.clip(x_adv, clip_min, clip_max)\n\n # Compute the error rate\n y_adv = np.argmax(self.estimator.predict(x_adv, batch_size=1), axis=1)\n fooling_rate = np.sum(y_index != y_adv) / nb_instances\n\n pbar.close()\n self._fooling_rate = fooling_rate\n self._converged = nb_iter < self.max_iter\n self._noise = noise\n logger.info(\"Success rate of universal perturbation attack: %.2f%%\", 100 * fooling_rate)\n\n return x_adv\n\n def _get_attack(self, a_name: str, params: dict[str, Any] | None = None) -> EvasionAttack:\n \"\"\"\n Get an attack object from its name.\n\n :param a_name: Attack name.\n :param params: Attack params.\n :return: Attack object.\n :raises NotImplementedError: If the attack is not supported.\n \"\"\"\n try:\n attack_class = self._get_class(self.attacks_dict[a_name])\n a_instance = attack_class(self.estimator) # type: ignore\n\n if params:\n a_instance.set_params(**params)\n\n return a_instance\n except KeyError:\n raise NotImplementedError(f\"{a_name} attack not supported\") from KeyError\n\n @staticmethod\n def _get_class(class_name: str) -> types.ModuleType:\n \"\"\"\n Get a class module from its name.\n\n :param class_name: Full name of a class.\n :return: The class `module`.\n \"\"\"\n sub_mods = class_name.split(\".\")\n module_ = __import__(\".\".join(sub_mods[:-1]), fromlist=sub_mods[-1])\n class_module = getattr(module_, sub_mods[-1])\n\n return class_module\n\n def _check_params(self) -> None:\n if not isinstance(self.delta, (float, int)) or self.delta < 0 or self.delta > 1:\n raise ValueError(\"The desired accuracy must be in the range [0, 1].\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if not isinstance(self.eps, (float, int)) or self.eps <= 0:\n raise ValueError(\"The eps coefficient must be a positive float.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The batch_size must be a positive integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/virtual_adversarial.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the virtual adversarial attack. It was originally used for virtual adversarial training.\n\n| Paper link: https://arxiv.org/abs/1507.00677\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass VirtualAdversarialMethod(EvasionAttack):\n \"\"\"\n This attack was originally proposed by Miyato et al. (2016) and was used for virtual adversarial training.\n\n | Paper link: https://arxiv.org/abs/1507.00677\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"eps\",\n \"finite_diff\",\n \"max_iter\",\n \"batch_size\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n max_iter: int = 10,\n finite_diff: float = 1e-6,\n eps: float = 0.1,\n batch_size: int = 1,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a :class:`.VirtualAdversarialMethod` instance.\n\n :param classifier: A trained classifier.\n :param eps: Attack step (max input variation).\n :param finite_diff: The finite difference parameter.\n :param max_iter: The maximum number of iterations.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n self.finite_diff = finite_diff\n self.eps = eps\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: An array with the original labels to be predicted.\n :return: An array holding the adversarial examples.\n \"\"\"\n x_adv = x.astype(ART_NUMPY_DTYPE)\n preds = self.estimator.predict(x_adv, batch_size=self.batch_size)\n\n if self.estimator.nb_classes == 2 and preds.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if (preds < 0.0).any() or (preds > 1.0).any():\n raise TypeError(\n \"This attack requires a classifier predicting probabilities in the range [0, 1] as output.\"\n \"Values smaller than 0.0 or larger than 1.0 have been detected.\"\n )\n # preds_rescaled = self._rescale(preds) # Rescaling needs more testing\n preds_rescaled = preds\n\n # Compute perturbation with implicit batching\n for batch_id in trange(\n int(np.ceil(x_adv.shape[0] / float(self.batch_size))), desc=\"VAT\", disable=not self.verbose\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch = x_adv[batch_index_1:batch_index_2]\n batch = batch.reshape((batch.shape[0], -1))\n\n # Main algorithm for each batch\n var_d = np.random.randn(*batch.shape).astype(ART_NUMPY_DTYPE)\n\n # Main loop of the algorithm\n for _ in range(self.max_iter):\n var_d = self._normalize(var_d)\n preds_new = self.estimator.predict((batch + var_d).reshape((-1,) + self.estimator.input_shape))\n if (preds_new < 0.0).any() or (preds_new > 1.0).any():\n raise TypeError(\n \"This attack requires a classifier predicting probabilities in the range [0, 1] as \"\n \"output. Values smaller than 0.0 or larger than 1.0 have been detected.\"\n )\n # preds_new_rescaled = self._rescale(preds_new) # Rescaling needs more testing\n preds_new_rescaled = preds_new\n\n from scipy.stats import entropy\n\n kl_div1 = entropy(\n np.transpose(preds_rescaled[batch_index_1:batch_index_2]),\n np.transpose(preds_new_rescaled),\n )\n\n var_d_new = np.zeros(var_d.shape).astype(ART_NUMPY_DTYPE)\n for current_index in range(var_d.shape[1]):\n var_d[:, current_index] += self.finite_diff\n preds_new = self.estimator.predict((batch + var_d).reshape((-1,) + self.estimator.input_shape))\n if (preds_new < 0.0).any() or (preds_new > 1.0).any():\n raise TypeError(\n \"This attack requires a classifier predicting probabilities in the range [0, 1]\"\n \"as output. Values smaller than 0.0 or larger than 1.0 have been detected.\"\n )\n # preds_new_rescaled = self._rescale(preds_new) # Rescaling needs more testing\n preds_new_rescaled = preds_new\n\n kl_div2 = entropy(\n np.transpose(preds_rescaled[batch_index_1:batch_index_2]),\n np.transpose(preds_new_rescaled),\n )\n var_d_new[:, current_index] = (kl_div2 - kl_div1) / self.finite_diff\n var_d[:, current_index] -= self.finite_diff\n var_d = var_d_new\n\n # Apply perturbation and clip\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv[batch_index_1:batch_index_2] = np.clip(\n batch + self.eps * self._normalize(var_d), clip_min, clip_max\n ).reshape((-1,) + self.estimator.input_shape)\n else:\n x_adv[batch_index_1:batch_index_2] = (batch + self.eps * self._normalize(var_d)).reshape(\n (-1,) + self.estimator.input_shape\n )\n\n return x_adv\n\n @staticmethod\n def _normalize(x: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply L_2 batch normalization on `x`.\n\n :param x: The input array batch to normalize.\n :return: The normalized version of `x`.\n \"\"\"\n norm = np.atleast_1d(np.linalg.norm(x, axis=1))\n norm[norm == 0] = 1\n normalized_x = x / np.expand_dims(norm, axis=1)\n\n return normalized_x\n\n @staticmethod\n def _rescale(x: np.ndarray) -> np.ndarray: # pragma: no cover\n \"\"\"\n Rescale values of `x` to the range (0, 1]. The interval is open on the left side, using values close to zero\n instead. This is to avoid values that are invalid for further KL divergence computation.\n\n :param x: Input array.\n :return: Rescaled value of `x`.\n \"\"\"\n # Tolerance range avoids actually setting minimum value to 0, as this value is invalid for KL divergence\n tol = 1e-5\n\n current_range = np.amax(x, axis=1, keepdims=True) - np.amin(x, axis=1, keepdims=True)\n current_range[current_range == 0] = 1\n res = (x - np.amin(x, axis=1, keepdims=True) + tol) / current_range\n return res\n\n def _check_params(self) -> None:\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if self.eps <= 0:\n raise ValueError(\"The attack step must be positive.\")\n\n if not isinstance(self.finite_diff, float) or self.finite_diff <= 0:\n raise ValueError(\"The finite difference parameter must be a positive float.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/wasserstein.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements ``Wasserstein Adversarial Examples via Projected Sinkhorn Iterations`` as evasion attack.\n\n| Paper link: https://arxiv.org/abs/1902.07906\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.special import lambertw\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import get_labels_np_array, check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\nEPS_LOG = 10**-10\n\n\nclass Wasserstein(EvasionAttack):\n \"\"\"\n Implements ``Wasserstein Adversarial Examples via Projected Sinkhorn Iterations`` as evasion attack.\n\n | Paper link: https://arxiv.org/abs/1902.07906\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"targeted\",\n \"regularization\",\n \"p\",\n \"kernel_size\",\n \"eps_step\",\n \"norm\",\n \"ball\",\n \"eps\",\n \"eps_iter\",\n \"eps_factor\",\n \"max_iter\",\n \"conjugate_sinkhorn_max_iter\",\n \"projected_sinkhorn_max_iter\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n targeted: bool = False,\n regularization: float = 3000.0,\n p: int = 2,\n kernel_size: int = 5,\n eps_step: float = 0.1,\n norm: str = \"wasserstein\",\n ball: str = \"wasserstein\",\n eps: float = 0.3,\n eps_iter: int = 10,\n eps_factor: float = 1.1,\n max_iter: int = 400,\n conjugate_sinkhorn_max_iter: int = 400,\n projected_sinkhorn_max_iter: int = 400,\n batch_size: int = 1,\n verbose: bool = True,\n ):\n \"\"\"\n Create a Wasserstein attack instance.\n\n :param estimator: A trained estimator.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param regularization: Entropy regularization.\n :param p: The p-wasserstein distance.\n :param kernel_size: Kernel size for computing the cost matrix.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param norm: The norm of the adversarial perturbation. Possible values: `inf`, `1`, `2` or `wasserstein`.\n :param ball: The ball of the adversarial perturbation. Possible values: `inf`, `1`, `2` or `wasserstein`.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_iter: Number of iterations to increase the epsilon.\n :param eps_factor: Factor to increase the epsilon.\n :param max_iter: The maximum number of iterations.\n :param conjugate_sinkhorn_max_iter: The maximum number of iterations for the conjugate sinkhorn optimizer.\n :param projected_sinkhorn_max_iter: The maximum number of iterations for the projected sinkhorn optimizer.\n :param batch_size: Size of batches.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self._targeted = targeted\n self.regularization = regularization\n self.p = p # pylint: disable=invalid-name\n self.kernel_size = kernel_size\n self.eps_step = eps_step\n self.norm = norm\n self.ball = ball\n self.eps = eps\n self.eps_iter = eps_iter\n self.eps_factor = eps_factor\n self.max_iter = max_iter\n self.conjugate_sinkhorn_max_iter = conjugate_sinkhorn_max_iter\n self.projected_sinkhorn_max_iter = projected_sinkhorn_max_iter\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param cost_matrix: A non-negative cost matrix.\n :type cost_matrix: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n x_adv = x.copy().astype(ART_NUMPY_DTYPE)\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted:\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n targets = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n else:\n targets = y\n\n if self.estimator.nb_classes == 2 and targets.shape[1] == 1:\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Compute the cost matrix if needed\n cost_matrix = kwargs.get(\"cost_matrix\")\n if cost_matrix is None:\n cost_matrix = self._compute_cost_matrix(self.p, self.kernel_size)\n\n # Compute perturbation with implicit batching\n nb_batches = int(np.ceil(x.shape[0] / float(self.batch_size)))\n for batch_id in trange(nb_batches, desc=\"Wasserstein\", disable=not self.verbose):\n logger.debug(\"Processing batch %i out of %i\", batch_id, nb_batches)\n\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch = x_adv[batch_index_1:batch_index_2]\n batch_labels = targets[batch_index_1:batch_index_2]\n\n x_adv[batch_index_1:batch_index_2] = self._generate_batch(batch, batch_labels, cost_matrix)\n\n return x_adv\n\n def _generate_batch(self, x: np.ndarray, targets: np.ndarray, cost_matrix: np.ndarray) -> np.ndarray:\n \"\"\"\n Generate a batch of adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param targets: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n :param cost_matrix: A non-negative cost matrix.\n :return: Adversarial examples.\n \"\"\"\n adv_x = x.copy().astype(ART_NUMPY_DTYPE)\n adv_x_best = x.copy().astype(ART_NUMPY_DTYPE)\n\n if self.targeted:\n err = np.argmax(self.estimator.predict(adv_x, batch_size=x.shape[0]), axis=1) == np.argmax(targets, axis=1)\n else:\n err = np.argmax(self.estimator.predict(adv_x, batch_size=x.shape[0]), axis=1) != np.argmax(targets, axis=1)\n\n err_best = err\n eps_ = np.ones(x.shape[0]) * self.eps\n\n for i in range(self.max_iter):\n adv_x = self._compute(adv_x, x, targets, cost_matrix, eps_, err)\n\n if self.targeted:\n err = np.argmax(self.estimator.predict(adv_x, batch_size=x.shape[0]), axis=1) == np.argmax(\n targets, axis=1\n )\n\n else:\n err = np.argmax(self.estimator.predict(adv_x, batch_size=x.shape[0]), axis=1) != np.argmax(\n targets, axis=1\n )\n\n if np.mean(err) > np.mean(err_best):\n err_best = err\n adv_x_best = adv_x.copy()\n\n if np.mean(err) == 1:\n break\n\n if (i + 1) % self.eps_iter == 0:\n eps_[~err] *= self.eps_factor\n\n return adv_x_best\n\n def _compute(\n self,\n x_adv: np.ndarray,\n x_init: np.ndarray,\n y: np.ndarray,\n cost_matrix: np.ndarray,\n eps: np.ndarray,\n err: np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n Compute adversarial examples for one iteration.\n\n :param x_adv: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param cost_matrix: A non-negative cost matrix.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param err: Current successful adversarial examples.\n :return: Adversarial examples.\n \"\"\"\n # Compute and apply perturbation\n x_adv[~err] = self._compute_apply_perturbation(x_adv, y, cost_matrix)[~err]\n\n # Do projection\n x_adv[~err] = self._apply_projection(x_adv, x_init, cost_matrix, eps)[~err]\n\n # Clip x_adv\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = np.clip(x_adv, clip_min, clip_max)\n\n return x_adv\n\n def _compute_apply_perturbation(self, x: np.ndarray, y: np.ndarray, cost_matrix: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute and apply perturbations.\n\n :param x: Current adversarial examples.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param cost_matrix: A non-negative cost matrix.\n :return: Adversarial examples.\n \"\"\"\n # Pick a small scalar to avoid division by 0\n tol = 10e-8\n\n # Get gradient wrt loss; invert it if attack is targeted\n grad = self.estimator.loss_gradient(x, y) * (1 - 2 * int(self.targeted))\n\n # Apply norm bound\n if self.norm == \"inf\":\n grad = np.sign(grad)\n x_adv = x + self.eps_step * grad\n\n elif self.norm == \"1\":\n ind = tuple(range(1, len(x.shape)))\n grad = grad / (np.sum(np.abs(grad), axis=ind, keepdims=True) + tol)\n x_adv = x + self.eps_step * grad\n\n elif self.norm == \"2\":\n ind = tuple(range(1, len(x.shape)))\n grad = grad / (np.sqrt(np.sum(np.square(grad), axis=ind, keepdims=True)) + tol)\n x_adv = x + self.eps_step * grad\n\n elif self.norm == \"wasserstein\":\n x_adv = self._conjugate_sinkhorn(x, grad, cost_matrix)\n\n else:\n raise NotImplementedError(\n \"Values of `norm` different from `1`, `2`, `inf` and `wasserstein` are currently not supported.\"\n )\n\n return x_adv\n\n def _apply_projection(\n self, x: np.ndarray, x_init: np.ndarray, cost_matrix: np.ndarray, eps: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n Apply projection on the ball of size `eps`.\n\n :param x: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param cost_matrix: A non-negative cost matrix.\n :param eps: Maximum perturbation that the attacker can introduce.\n :return: Adversarial examples.\n \"\"\"\n # Pick a small scalar to avoid division by 0\n tol = 10e-8\n\n if self.ball == \"2\":\n values = x - x_init\n values_tmp = values.reshape((values.shape[0], -1))\n\n values_tmp = values_tmp * np.expand_dims(\n np.minimum(1.0, eps / (np.linalg.norm(values_tmp, axis=1) + tol)), axis=1\n )\n\n values = values_tmp.reshape(values.shape)\n\n x_adv = values + x_init\n\n elif self.ball == \"1\":\n values = x - x_init\n values_tmp = values.reshape((values.shape[0], -1))\n\n values_tmp = values_tmp * np.expand_dims(\n np.minimum(1.0, eps / (np.linalg.norm(values_tmp, axis=1, ord=1) + tol)), axis=1\n )\n\n values = values_tmp.reshape(values.shape)\n x_adv = values + x_init\n\n elif self.ball == \"inf\":\n values = x - x_init\n values_tmp = values.reshape((values.shape[0], -1))\n\n values_tmp = np.sign(values_tmp) * np.minimum(abs(values_tmp), np.expand_dims(eps, -1))\n\n values = values_tmp.reshape(values.shape)\n x_adv = values + x_init\n\n elif self.ball == \"wasserstein\":\n x_adv = self._projected_sinkhorn(x, x_init, cost_matrix, eps)\n\n else:\n raise NotImplementedError(\n \"Values of `ball` different from `1`, `2`, `inf` and `wasserstein` are currently not supported.\"\n )\n\n return x_adv\n\n def _conjugate_sinkhorn(self, x: np.ndarray, grad: np.ndarray, cost_matrix: np.ndarray) -> np.ndarray:\n \"\"\"\n The conjugate sinkhorn_optimizer.\n\n :param x: Current adversarial examples.\n :param grad: The loss gradients.\n :param cost_matrix: A non-negative cost matrix.\n :return: Adversarial examples.\n \"\"\"\n # Normalize inputs\n normalization = x.reshape(x.shape[0], -1).sum(-1).reshape(x.shape[0], 1, 1, 1)\n x = x.copy() / normalization\n\n # Dimension size for each example\n m = np.prod(x.shape[1:])\n\n # Initialize\n alpha = np.log(np.ones(x.shape) / m) + 0.5\n exp_alpha = np.exp(-alpha)\n\n beta = -self.regularization * grad\n beta = beta.astype(np.float64)\n exp_beta = np.exp(-beta)\n\n # Check for overflow\n if (exp_beta == np.inf).any():\n raise ValueError(\"Overflow error in `_conjugate_sinkhorn` for exponential beta.\")\n\n cost_matrix_new = cost_matrix.copy() + 1\n cost_matrix_new = np.expand_dims(np.expand_dims(cost_matrix_new, 0), 0)\n\n i_nonzero = self._batch_dot(x, self._local_transport(cost_matrix_new, grad, self.kernel_size)) != 0\n i_nonzero_ = np.zeros(alpha.shape).astype(bool)\n i_nonzero_[:, :, :, :] = np.expand_dims(np.expand_dims(np.expand_dims(i_nonzero, -1), -1), -1)\n\n psi = np.ones(x.shape[0])\n\n var_k = np.expand_dims(np.expand_dims(np.expand_dims(psi, -1), -1), -1)\n var_k = np.exp(-var_k * cost_matrix - 1)\n\n convergence = np.array([-np.inf])\n\n for _ in range(self.conjugate_sinkhorn_max_iter):\n # Block coordinate descent iterates\n x[x == 0.0] = EPS_LOG # Prevent divide by zero in np.log\n alpha[i_nonzero_] = (np.log(self._local_transport(var_k, exp_beta, self.kernel_size)) - np.log(x))[\n i_nonzero_\n ]\n exp_alpha = np.exp(-alpha)\n\n # Newton step\n var_g = -self.eps_step + self._batch_dot(\n exp_alpha, self._local_transport(cost_matrix * var_k, exp_beta, self.kernel_size)\n )\n\n var_h = -self._batch_dot(\n exp_alpha, self._local_transport(cost_matrix * cost_matrix * var_k, exp_beta, self.kernel_size)\n )\n\n delta = var_g / var_h\n\n # Ensure psi >= 0\n tmp = np.ones(delta.shape)\n neg = psi - tmp * delta < 0\n\n while neg.any() and np.min(tmp) > 1e-2:\n tmp[neg] /= 2\n neg = psi - tmp * delta < 0\n\n psi[i_nonzero] = np.maximum(psi - tmp * delta, 0)[i_nonzero]\n\n # Update K\n var_k = np.expand_dims(np.expand_dims(np.expand_dims(psi, -1), -1), -1)\n var_k = np.exp(-var_k * cost_matrix - 1)\n\n # Check for convergence\n next_convergence = self._conjugated_sinkhorn_evaluation(x, alpha, exp_alpha, exp_beta, psi, var_k)\n\n if (np.abs(convergence - next_convergence) <= 1e-4 + 1e-4 * np.abs(next_convergence)).all():\n break\n\n convergence = next_convergence\n\n result = exp_beta * self._local_transport(var_k, exp_alpha, self.kernel_size)\n result[~i_nonzero] = 0\n result *= normalization\n\n return result\n\n def _projected_sinkhorn(\n self, x: np.ndarray, x_init: np.ndarray, cost_matrix: np.ndarray, eps: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n The projected sinkhorn_optimizer.\n\n :param x: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param cost_matrix: A non-negative cost matrix.\n :param eps: Maximum perturbation that the attacker can introduce.\n :return: Adversarial examples.\n \"\"\"\n # Normalize inputs\n normalization = x_init.reshape(x.shape[0], -1).sum(-1).reshape(x.shape[0], 1, 1, 1)\n x = x.copy() / normalization\n x_init = x_init.copy() / normalization\n\n # Dimension size for each example\n m = np.prod(x_init.shape[1:])\n\n # Initialize\n beta = np.log(np.ones(x.shape) / m)\n exp_beta = np.exp(-beta)\n\n psi = np.ones(x.shape[0])\n\n var_k = np.expand_dims(np.expand_dims(np.expand_dims(psi, -1), -1), -1)\n var_k = np.exp(-var_k * cost_matrix - 1)\n\n convergence = np.array([-np.inf])\n\n for _ in range(self.projected_sinkhorn_max_iter):\n # Block coordinate descent iterates\n x_init[x_init == 0.0] = EPS_LOG # Prevent divide by zero in np.log\n alpha = np.log(self._local_transport(var_k, exp_beta, self.kernel_size)) - np.log(x_init)\n exp_alpha = np.exp(-alpha)\n\n beta = (\n self.regularization\n * np.exp(self.regularization * x)\n * self._local_transport(var_k, exp_alpha, self.kernel_size)\n )\n beta[beta > 1e-10] = np.real(lambertw(beta[beta > 1e-10]))\n beta -= self.regularization * x\n exp_beta = np.exp(-beta)\n\n # Newton step\n var_g = -eps + self._batch_dot(\n exp_alpha, self._local_transport(cost_matrix * var_k, exp_beta, self.kernel_size)\n )\n\n var_h = -self._batch_dot(\n exp_alpha, self._local_transport(cost_matrix * cost_matrix * var_k, exp_beta, self.kernel_size)\n )\n\n delta = var_g / var_h\n\n # Ensure psi >= 0\n tmp = np.ones(delta.shape)\n neg = psi - tmp * delta < 0\n\n while neg.any() and np.min(tmp) > 1e-2:\n tmp[neg] /= 2\n neg = psi - tmp * delta < 0\n\n psi = np.maximum(psi - tmp * delta, 0)\n\n # Update K\n var_k = np.expand_dims(np.expand_dims(np.expand_dims(psi, -1), -1), -1)\n var_k = np.exp(-var_k * cost_matrix - 1)\n\n # Check for convergence\n next_convergence = self._projected_sinkhorn_evaluation(\n x,\n x_init,\n alpha,\n exp_alpha,\n beta,\n exp_beta,\n psi,\n var_k,\n eps,\n )\n\n if (np.abs(convergence - next_convergence) <= 1e-4 + 1e-4 * np.abs(next_convergence)).all():\n break\n\n convergence = next_convergence\n\n result = (beta / self.regularization + x) * normalization\n\n return result\n\n @staticmethod\n def _compute_cost_matrix(var_p: int, kernel_size: int) -> np.ndarray:\n \"\"\"\n Compute the default cost matrix.\n\n :param var_p: The p-wasserstein distance.\n :param kernel_size: Kernel size for computing the cost matrix.\n :return: The cost matrix.\n \"\"\"\n center = kernel_size // 2\n cost_matrix = np.zeros((kernel_size, kernel_size))\n\n for i in range(kernel_size):\n for j in range(kernel_size):\n # The code of the paper of this attack (https://arxiv.org/abs/1902.07906) implements the cost as:\n # cost_matrix[i, j] = (abs(i - center) ** 2 + abs(j - center) ** 2) ** (p / 2)\n # which only can reproduce L2-norm for p=1 correctly\n cost_matrix[i, j] = (abs(i - center) ** var_p + abs(j - center) ** var_p) ** (1 / var_p)\n\n return cost_matrix\n\n @staticmethod\n def _batch_dot(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute batch dot product.\n\n :param x: Sample batch.\n :param y: Sample batch.\n :return: Batch dot product.\n \"\"\"\n batch_size = x.shape[0]\n assert batch_size == y.shape[0]\n\n var_x_ = x.reshape(batch_size, 1, -1)\n var_y_ = y.reshape(batch_size, -1, 1)\n\n result = np.matmul(var_x_, var_y_).reshape(batch_size)\n\n return result\n\n @staticmethod\n def _unfold(x: np.ndarray, kernel_size: int, padding: int) -> np.ndarray:\n \"\"\"\n Extract sliding local blocks from a batched input.\n\n :param x: A batched input of shape `batch x channel x width x height`.\n :param kernel_size: Kernel size for computing the cost matrix.\n :param padding: Controls the amount of implicit zero-paddings on both sides for padding number of points\n for each dimension before reshaping.\n :return: Sliding local blocks.\n \"\"\"\n # Do padding\n shape = tuple(np.array(x.shape[2:]) + padding * 2)\n x_pad = np.zeros(x.shape[:2] + shape)\n x_pad[:, :, padding : (shape[0] - padding), padding : (shape[1] - padding)] = x\n\n # Do unfolding\n res_dim_0 = x.shape[0]\n res_dim_1 = x.shape[1] * kernel_size**2\n res_dim_2 = (shape[0] - kernel_size + 1) * (shape[1] - kernel_size + 1)\n result = np.zeros((res_dim_0, res_dim_1, res_dim_2))\n\n for i in range(shape[0] - kernel_size + 1):\n for j in range(shape[1] - kernel_size + 1):\n patch = x_pad[:, :, i : (i + kernel_size), j : (j + kernel_size)]\n patch = patch.reshape(x.shape[0], -1)\n result[:, :, i * (shape[1] - kernel_size + 1) + j] = patch\n\n return result\n\n def _local_transport(self, var_k: np.ndarray, x: np.ndarray, kernel_size: int) -> np.ndarray:\n \"\"\"\n Compute local transport.\n\n :param var_k: K parameter in Algorithm 2 of the paper ``Wasserstein Adversarial Examples via Projected\n Sinkhorn Iterations``.\n :param x: An array to apply local transport.\n :param kernel_size: Kernel size for computing the cost matrix.\n :return: Local transport result.\n \"\"\"\n # Compute number of channels\n num_channels = x.shape[1 if self.estimator.channels_first else 3]\n\n # Expand channels\n var_k = np.repeat(var_k, num_channels, axis=1)\n\n # Swap channels to prepare for local transport computation\n if not self.estimator.channels_first:\n x = np.swapaxes(x, 1, 3)\n\n # Compute local transport\n unfold_x = self._unfold(x=x, kernel_size=kernel_size, padding=kernel_size // 2)\n unfold_x = unfold_x.swapaxes(-1, -2)\n unfold_x = unfold_x.reshape(*unfold_x.shape[:-1], num_channels, kernel_size**2)\n unfold_x = unfold_x.swapaxes(-2, -3)\n\n tmp_k = var_k.reshape(var_k.shape[0], num_channels, -1)\n tmp_k = np.expand_dims(tmp_k, -1)\n\n result = np.matmul(unfold_x, tmp_k)\n result = np.squeeze(result, -1)\n result = result.reshape(*result.shape[:-1], x.shape[-2], x.shape[-1])\n\n # Swap channels for final result\n if not self.estimator.channels_first:\n result = np.swapaxes(result, 1, 3)\n\n return result\n\n def _projected_sinkhorn_evaluation(\n self,\n x: np.ndarray,\n x_init: np.ndarray,\n alpha: np.ndarray,\n exp_alpha: np.ndarray,\n beta: np.ndarray,\n exp_beta: np.ndarray,\n psi: np.ndarray,\n var_k: np.ndarray,\n eps: np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n Function to evaluate the objective of the projected sinkhorn optimizer.\n\n :param x: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param alpha: Alpha parameter in Algorithm 2 of the paper ``Wasserstein Adversarial Examples via Projected\n Sinkhorn Iterations``.\n :param exp_alpha: Exponential of alpha.\n :param beta: Beta parameter in Algorithm 2 of the paper ``Wasserstein Adversarial Examples via Projected\n Sinkhorn Iterations``.\n :param exp_beta: Exponential of beta.\n :param psi: Psi parameter in Algorithm 2 of the paper ``Wasserstein Adversarial Examples via Projected\n Sinkhorn Iterations``.\n :param var_k: K parameter in Algorithm 2 of the paper ``Wasserstein Adversarial Examples via Projected\n Sinkhorn Iterations``.\n :param eps: Maximum perturbation that the attacker can introduce.\n :return: Evaluation result.\n \"\"\"\n return (\n -0.5 / self.regularization * self._batch_dot(beta, beta)\n - psi * eps\n - self._batch_dot(np.minimum(alpha, 1e10), x_init)\n - self._batch_dot(np.minimum(beta, 1e10), x)\n - self._batch_dot(exp_alpha, self._local_transport(var_k, exp_beta, self.kernel_size))\n )\n\n def _conjugated_sinkhorn_evaluation(\n self,\n x: np.ndarray,\n alpha: np.ndarray,\n exp_alpha: np.ndarray,\n exp_beta: np.ndarray,\n psi: np.ndarray,\n var_k: np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n Function to evaluate the objective of the conjugated sinkhorn optimizer.\n\n :param x: Current adversarial examples.\n :param alpha: Alpha parameter in the conjugated sinkhorn optimizer of the paper ``Wasserstein Adversarial\n Examples via Projected Sinkhorn Iterations``.\n :param exp_alpha: Exponential of alpha.\n :param exp_beta: Exponential of beta parameter in the conjugated sinkhorn optimizer of the paper ``Wasserstein\n Adversarial Examples via Projected Sinkhorn Iterations``.\n :param psi: Psi parameter in the conjugated sinkhorn optimizer of the paper ``Wasserstein Adversarial\n Examples via Projected Sinkhorn Iterations``.\n :param var_k: K parameter in the conjugated sinkhorn optimizer of the paper ``Wasserstein Adversarial Examples\n via Projected Sinkhorn Iterations``.\n :return: Evaluation result.\n \"\"\"\n return (\n -psi * self.eps_step\n - self._batch_dot(np.minimum(alpha, 1e38), x)\n - self._batch_dot(exp_alpha, self._local_transport(var_k, exp_beta, self.kernel_size))\n )\n\n def _check_params(self) -> None:\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The flag `targeted` has to be of type bool.\")\n\n if self.regularization <= 0:\n raise ValueError(\"The entropy regularization has to be greater than 0.\")\n\n if not isinstance(self.p, int):\n raise TypeError(\"The p-wasserstein has to be of type integer.\")\n\n if self.p < 1:\n raise ValueError(\"The p-wasserstein must be larger or equal to 1.\")\n\n if not isinstance(self.kernel_size, int):\n raise TypeError(\"The kernel size has to be of type integer.\")\n\n if self.kernel_size % 2 != 1:\n raise ValueError(\"Need odd kernel size.\")\n\n # Check if order of the norm is acceptable given current implementation\n if self.norm not in [\"inf\", \"1\", \"2\", \"wasserstein\"]:\n raise ValueError(\"Norm order must be either `inf`, `1`, `2` or `wasserstein`.\")\n\n # Check if order of the ball is acceptable given current implementation\n if self.ball not in [\"inf\", \"1\", \"2\", \"wasserstein\"]:\n raise ValueError(\"Ball order must be either `inf`, `1`, `2` or `wasserstein`.\")\n\n if self.eps <= 0:\n raise ValueError(\"The perturbation size `eps` has to be positive.\")\n\n if self.eps_step <= 0:\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n\n if self.norm == \"inf\" and self.eps_step > self.eps:\n raise ValueError(\n \"The iteration step `eps_step` has to be smaller than or equal to the total attack budget `eps`.\"\n )\n\n if self.eps_iter <= 0:\n raise ValueError(\"The number of epsilon iterations `eps_iter` has to be a positive integer.\")\n\n if self.eps_factor <= 1:\n raise ValueError(\"The epsilon factor must be larger than 1.\")\n\n if self.max_iter <= 0:\n raise ValueError(\"The number of iterations `max_iter` has to be a positive integer.\")\n\n if self.conjugate_sinkhorn_max_iter <= 0:\n raise ValueError(\"The number of iterations `conjugate_sinkhorn_max_iter` has to be a positive integer.\")\n\n if self.projected_sinkhorn_max_iter <= 0:\n raise ValueError(\"The number of iterations `projected_sinkhorn_max_iter` has to be a positive integer.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/zoo.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the zeroth-order optimization attack `ZooAttack`. This is a black-box attack. This attack is a\nvariant of the Carlini and Wagner attack which uses ADAM coordinate descent to perform numerical estimation of\ngradients.\n\n| Paper link: https://arxiv.org/abs/1708.03999\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.ndimage import zoom\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import (\n compute_success,\n get_labels_np_array,\n check_and_transform_label_format,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ZooAttack(EvasionAttack):\n \"\"\"\n The black-box zeroth-order optimization attack from Pin-Yu Chen et al. (2018). This attack is a variant of the\n C&W attack which uses ADAM coordinate descent to perform numerical estimation of gradients.\n\n | Paper link: https://arxiv.org/abs/1708.03999\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"confidence\",\n \"targeted\",\n \"learning_rate\",\n \"max_iter\",\n \"binary_search_steps\",\n \"initial_const\",\n \"abort_early\",\n \"use_resize\",\n \"use_importance\",\n \"nb_parallel\",\n \"batch_size\",\n \"variable_h\",\n \"verbose\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n confidence: float = 0.0,\n targeted: bool = False,\n learning_rate: float = 1e-2,\n max_iter: int = 10,\n binary_search_steps: int = 1,\n initial_const: float = 1e-3,\n abort_early: bool = True,\n use_resize: bool = True,\n use_importance: bool = True,\n nb_parallel: int = 128,\n batch_size: int = 1,\n variable_h: float = 1e-4,\n verbose: bool = True,\n ):\n \"\"\"\n Create a ZOO attack instance.\n\n :param classifier: A trained classifier.\n :param confidence: Confidence of adversarial examples: a higher value produces examples that are farther\n away, from the original input, but classified with higher confidence as the target class.\n :param targeted: Should the attack target one specific class.\n :param learning_rate: The initial learning rate for the attack algorithm. Smaller values produce better\n results but are slower to converge.\n :param max_iter: The maximum number of iterations.\n :param binary_search_steps: Number of times to adjust constant with binary search (positive value).\n :param initial_const: The initial trade-off constant `c` to use to tune the relative importance of distance\n and confidence. If `binary_search_steps` is large, the initial constant is not important, as discussed in\n Carlini and Wagner (2016).\n :param abort_early: `True` if gradient descent should be abandoned when it gets stuck.\n :param use_resize: `True` if to use the resizing strategy from the paper: first, compute attack on inputs\n resized to 32x32, then increase size if needed to 64x64, followed by 128x128.\n :param use_importance: `True` if to use importance sampling when choosing coordinates to update.\n :param nb_parallel: Number of coordinate updates to run in parallel. A higher value for `nb_parallel` should\n be preferred over a large batch size.\n :param batch_size: Internal size of batches on which adversarial samples are generated. Small batch sizes are\n encouraged for ZOO, as the algorithm already runs `nb_parallel` coordinate updates in parallel for each\n sample. The batch size is a multiplier of `nb_parallel` in terms of memory consumption.\n :param variable_h: Step size for numerical estimation of derivatives.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n if len(classifier.input_shape) == 1:\n self.input_is_feature_vector = True\n if batch_size != 1:\n raise ValueError(\n \"The current implementation of Zeroth-Order Optimisation attack only supports \"\n \"`batch_size=1` with feature vectors as input.\"\n )\n else:\n self.input_is_feature_vector = False\n\n self.confidence = confidence\n self._targeted = targeted\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.binary_search_steps = binary_search_steps\n self.initial_const = initial_const\n self.abort_early = abort_early\n self.use_resize = use_resize\n self.use_importance = use_importance\n self.nb_parallel = nb_parallel\n self.batch_size = batch_size\n self.variable_h = variable_h\n self.verbose = verbose\n self._check_params()\n\n # Initialize some internal variables\n self._init_size = 32\n if self.abort_early:\n self._early_stop_iters = self.max_iter // 10 if self.max_iter >= 10 else self.max_iter\n\n # Initialize noise variable to zero\n if self.input_is_feature_vector:\n self.use_resize = False\n self.use_importance = False\n logger.info( # pragma: no cover\n \"Disable resizing and importance sampling because feature vector input has been detected.\"\n )\n\n if self.use_resize:\n if not self.estimator.channels_first:\n dims = (batch_size, self._init_size, self._init_size, self.estimator.input_shape[-1])\n else: # pragma: no cover\n dims = (batch_size, self.estimator.input_shape[0], self._init_size, self._init_size)\n self._current_noise = np.zeros(dims, dtype=ART_NUMPY_DTYPE)\n else:\n self._current_noise = np.zeros((batch_size,) + self.estimator.input_shape, dtype=ART_NUMPY_DTYPE)\n self._sample_prob = np.ones(self._current_noise.size, dtype=ART_NUMPY_DTYPE) / self._current_noise.size\n\n self.adam_mean: np.ndarray | None = None\n self.adam_var: np.ndarray | None = None\n self.adam_epochs: np.ndarray | None = None\n\n def _loss(\n self, x: np.ndarray, x_adv: np.ndarray, target: np.ndarray, c_weight: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Compute the loss function values.\n\n :param x: An array with the original input.\n :param x_adv: An array with the adversarial input.\n :param target: An array with the target class (one-hot encoded).\n :param c_weight: Weight of the loss term aiming for classification as target.\n :return: A tuple holding the current logits, `L_2` distortion and overall loss.\n \"\"\"\n l2dist = np.sum(np.square(x - x_adv).reshape(x_adv.shape[0], -1), axis=1)\n ratios = [1.0] + [\n int(new_size) / int(old_size) for new_size, old_size in zip(self.estimator.input_shape, x.shape[1:])\n ]\n preds = self.estimator.predict(np.array(zoom(x_adv, zoom=ratios)), batch_size=self.batch_size)\n z_target = np.sum(preds * target, axis=1)\n z_other = np.max(\n preds * (1 - target) + (np.min(preds, axis=1) - 1)[:, np.newaxis] * target,\n axis=1,\n )\n\n if self.targeted:\n # If targeted, optimize for making the target class most likely\n loss = np.maximum(z_other - z_target + self.confidence, 0)\n else:\n # If untargeted, optimize for making any other class most likely\n loss = np.maximum(z_target - z_other + self.confidence, 0)\n\n return preds, l2dist, c_weight * loss + l2dist\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n # Check that `y` is provided for targeted attacks\n if self.targeted and y is None: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # No labels provided, use model prediction as correct class\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n # Compute adversarial examples with implicit batching\n nb_batches = int(np.ceil(x.shape[0] / float(self.batch_size)))\n x_adv_list = []\n for batch_id in trange(nb_batches, desc=\"ZOO\", disable=not self.verbose):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_batch = x[batch_index_1:batch_index_2]\n y_batch = y[batch_index_1:batch_index_2]\n res = self._generate_batch(x_batch, y_batch)\n x_adv_list.append(res)\n x_adv = np.vstack(x_adv_list)\n\n # Apply clip\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n np.clip(x_adv, clip_min, clip_max, out=x_adv)\n\n # Log success rate of the ZOO attack\n logger.info(\n \"Success rate of ZOO attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),\n )\n\n return x_adv\n\n def _generate_batch(self, x_batch: np.ndarray, y_batch: np.ndarray) -> np.ndarray:\n \"\"\"\n Run the attack on a batch of images and labels.\n\n :param x_batch: A batch of original examples.\n :param y_batch: A batch of targets (0-1 hot).\n :return: A batch of adversarial examples.\n \"\"\"\n # Initialize binary search\n c_current = self.initial_const * np.ones(x_batch.shape[0])\n c_lower_bound = np.zeros(x_batch.shape[0])\n c_upper_bound = 1e10 * np.ones(x_batch.shape[0])\n\n # Initialize the best distortions and best attacks globally\n o_best_dist = np.inf * np.ones(x_batch.shape[0])\n o_best_attack = x_batch.copy()\n\n # Start with a binary search\n for bss in range(self.binary_search_steps):\n logger.debug(\n \"Binary search step %i out of %i (c_mean==%f)\",\n bss,\n self.binary_search_steps,\n np.mean(c_current),\n )\n\n # Run with 1 specific binary search step\n best_dist, best_label, best_attack = self._generate_bss(x_batch, y_batch, c_current)\n\n # Update best results so far\n o_best_attack[best_dist < o_best_dist] = best_attack[best_dist < o_best_dist]\n o_best_dist[best_dist < o_best_dist] = best_dist[best_dist < o_best_dist]\n\n # Adjust the constant as needed\n c_current, c_lower_bound, c_upper_bound = self._update_const(\n y_batch, best_label, c_current, c_lower_bound, c_upper_bound\n )\n\n return o_best_attack\n\n def _update_const(\n self,\n y_batch: np.ndarray,\n best_label: np.ndarray,\n c_batch: np.ndarray,\n c_lower_bound: np.ndarray,\n c_upper_bound: np.ndarray,\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Update constant `c_batch` from the ZOO objective. This characterizes the trade-off between attack strength and\n amount of noise introduced.\n\n :param y_batch: A batch of targets (0-1 hot).\n :param best_label: A batch of best labels.\n :param c_batch: A batch of constants.\n :param c_lower_bound: A batch of lower bound constants.\n :param c_upper_bound: A batch of upper bound constants.\n :return: A tuple of three batches of updated constants and lower/upper bounds.\n \"\"\"\n\n comparison = [\n self._compare(best_label[i], np.argmax(y_batch[i])) and best_label[i] != -np.inf\n for i in range(len(c_batch))\n ]\n for i, comp in enumerate(comparison):\n if comp:\n # Successful attack\n c_upper_bound[i] = min(c_upper_bound[i], c_batch[i])\n if c_upper_bound[i] < 1e9:\n c_batch[i] = (c_lower_bound[i] + c_upper_bound[i]) / 2\n else:\n # Failure attack\n c_lower_bound[i] = max(c_lower_bound[i], c_batch[i])\n c_batch[i] = (c_lower_bound[i] + c_upper_bound[i]) / 2 if c_upper_bound[i] < 1e9 else c_batch[i] * 10\n\n return c_batch, c_lower_bound, c_upper_bound\n\n def _compare(self, object1: Any, object2: Any) -> bool:\n \"\"\"\n Check two objects for equality if the attack is targeted, otherwise check for inequality.\n\n :param object1: First object to compare.\n :param object2: Second object to compare.\n :return: When the attack is targeted, returns \"True\" if object are equal otherwise \"False\". When the attack is\n untargeted, the function returns \"True\" when the objects are different otherwise \"False\".\n\n \"\"\"\n return object1 == object2 if self.targeted else object1 != object2\n\n def _generate_bss(\n self, x_batch: np.ndarray, y_batch: np.ndarray, c_batch: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Generate adversarial examples for a batch of inputs with a specific batch of constants.\n\n :param x_batch: A batch of original examples.\n :param y_batch: A batch of targets (0-1 hot).\n :param c_batch: A batch of constants.\n :return: A tuple of the best elastic distances, best labels, best attacks.\n \"\"\"\n\n x_orig = x_batch.astype(ART_NUMPY_DTYPE)\n fine_tuning = np.full(x_batch.shape[0], False, dtype=bool)\n prev_loss = 1e6 * np.ones(x_batch.shape[0])\n prev_l2dist = np.zeros(x_batch.shape[0])\n\n # Resize and initialize Adam\n if self.use_resize:\n x_orig = self._resize_image(x_orig, self._init_size, self._init_size, True)\n assert (x_orig != 0).any()\n x_adv = x_orig.copy()\n else:\n x_orig = x_batch\n self._reset_adam(np.prod(self.estimator.input_shape).item())\n if x_batch.shape == self._current_noise.shape:\n self._current_noise.fill(0)\n else:\n self._current_noise = np.zeros(x_batch.shape, dtype=ART_NUMPY_DTYPE)\n x_adv = x_orig.copy()\n\n # Initialize the best distortions, best changed labels and best attacks\n best_dist = np.inf * np.ones(x_adv.shape[0])\n best_label = -np.inf * np.ones(x_adv.shape[0])\n best_attack = np.array([x_adv[i] for i in range(x_adv.shape[0])])\n\n for iter_ in range(self.max_iter):\n logger.debug(\"Iteration step %i out of %i\", iter_, self.max_iter)\n\n # Upscaling for very large number of iterations\n if self.use_resize:\n if iter_ == 2000:\n x_adv = self._resize_image(x_adv, 64, 64)\n x_orig = zoom(\n x_orig,\n [\n 1,\n x_adv.shape[1] / x_orig.shape[1],\n x_adv.shape[2] / x_orig.shape[2],\n x_adv.shape[3] / x_orig.shape[3],\n ],\n )\n elif iter_ == 10000:\n x_adv = self._resize_image(x_adv, 128, 128)\n x_orig = zoom(\n x_orig,\n [\n 1,\n x_adv.shape[1] / x_orig.shape[1],\n x_adv.shape[2] / x_orig.shape[2],\n x_adv.shape[3] / x_orig.shape[3],\n ],\n )\n\n # Compute adversarial examples and loss\n x_adv = self._optimizer(x_adv, y_batch, c_batch)\n preds, l2dist, loss = self._loss(x_orig, x_adv, y_batch, c_batch)\n\n # Reset Adam if a valid example has been found to avoid overshoot\n mask_fine_tune = (~fine_tuning) & (loss == l2dist) & (prev_loss != prev_l2dist)\n fine_tuning[mask_fine_tune] = True\n self._reset_adam(self.adam_mean.size, np.repeat(mask_fine_tune, x_adv[0].size)) # type: ignore\n prev_l2dist = l2dist\n\n # Abort early if no improvement is obtained\n if self.abort_early and iter_ % self._early_stop_iters == 0:\n if (loss > 0.9999 * prev_loss).all():\n break\n prev_loss = loss\n\n # Adjust the best result\n labels_batch = np.argmax(y_batch, axis=1)\n for i, (dist, pred) in enumerate(zip(l2dist, np.argmax(preds, axis=1))):\n if dist < best_dist[i] and self._compare(pred, labels_batch[i]):\n best_dist[i] = dist\n best_attack[i] = x_adv[i]\n best_label[i] = pred\n\n # Resize images to original size before returning\n best_attack = np.array(best_attack)\n if self.use_resize:\n if not self.estimator.channels_first:\n best_attack = zoom(\n best_attack,\n [\n 1,\n int(x_batch.shape[1]) / best_attack.shape[1],\n int(x_batch.shape[2]) / best_attack.shape[2],\n 1,\n ],\n )\n else:\n best_attack = zoom(\n best_attack,\n [\n 1,\n 1,\n int(x_batch.shape[2]) / best_attack.shape[2],\n int(x_batch.shape[2]) / best_attack.shape[3],\n ],\n )\n\n return best_dist, best_label, best_attack\n\n def _optimizer(self, x: np.ndarray, targets: np.ndarray, c_batch: np.ndarray) -> np.ndarray:\n # Variation of input for computing loss, same as in original implementation\n coord_batch = np.repeat(self._current_noise, 2 * self.nb_parallel, axis=0)\n coord_batch = coord_batch.reshape(2 * self.nb_parallel * self._current_noise.shape[0], -1)\n\n # Sample indices to prioritize for optimization\n if self.use_importance and np.unique(self._sample_prob).size != 1:\n indices = (\n np.random.choice(\n coord_batch.shape[-1] * x.shape[0],\n self.nb_parallel * self._current_noise.shape[0],\n replace=False,\n p=self._sample_prob.flatten(),\n )\n % coord_batch.shape[-1]\n )\n else:\n try:\n indices = (\n np.random.choice(\n coord_batch.shape[-1] * x.shape[0],\n self.nb_parallel * self._current_noise.shape[0],\n replace=False,\n )\n % coord_batch.shape[-1]\n )\n except ValueError as error: # pragma: no cover\n if \"Cannot take a larger sample than population when 'replace=False'\" in str(error):\n raise ValueError(\n \"Too many samples are requested for the random indices. Try to reduce the number of parallel\"\n \"coordinate updates `nb_parallel`.\"\n ) from error\n\n raise error\n\n # Create the batch of modifications to run\n for i in range(self.nb_parallel * self._current_noise.shape[0]):\n coord_batch[2 * i, indices[i]] += self.variable_h\n coord_batch[2 * i + 1, indices[i]] -= self.variable_h\n\n # Compute loss for all samples and coordinates, then optimize\n expanded_x = np.repeat(x, 2 * self.nb_parallel, axis=0).reshape((-1,) + x.shape[1:])\n expanded_targets = np.repeat(targets, 2 * self.nb_parallel, axis=0).reshape((-1,) + targets.shape[1:])\n expanded_c = np.repeat(c_batch, 2 * self.nb_parallel)\n _, _, loss = self._loss(\n expanded_x,\n expanded_x + coord_batch.reshape(expanded_x.shape),\n expanded_targets,\n expanded_c,\n )\n if self.adam_mean is not None and self.adam_var is not None and self.adam_epochs is not None:\n self._current_noise = self._optimizer_adam_coordinate(\n loss,\n indices,\n self.adam_mean,\n self.adam_var,\n self._current_noise,\n self.learning_rate,\n self.adam_epochs,\n True,\n )\n else:\n raise ValueError(\"Unexpected `None` in `adam_mean`, `adam_var` or `adam_epochs` detected.\")\n\n if self.use_importance and self._current_noise.shape[2] > self._init_size:\n self._sample_prob = self._get_prob(self._current_noise).flatten()\n\n return x + self._current_noise\n\n def _optimizer_adam_coordinate(\n self,\n losses: np.ndarray,\n index: np.ndarray,\n mean: np.ndarray,\n var: np.ndarray,\n current_noise: np.ndarray,\n learning_rate: float,\n adam_epochs: np.ndarray,\n proj: bool,\n ) -> np.ndarray:\n \"\"\"\n Implementation of the ADAM optimizer for coordinate descent.\n\n :param losses: Overall loss.\n :param index: Indices of the coordinates to update.\n :param mean: The mean of the gradient (first moment).\n :param var: The uncentered variance of the gradient (second moment).\n :param current_noise: Current noise.\n :param learning_rate: Learning rate for Adam optimizer.\n :param adam_epochs: Epochs to run the Adam optimizer.\n :param proj: Whether to project the noise to the L_p ball.\n :return: Updated noise for coordinate descent.\n \"\"\"\n beta1, beta2 = 0.9, 0.999\n\n # Estimate grads from loss variation (constant `h` from the paper is fixed to .0001)\n grads = np.array([(losses[i] - losses[i + 1]) / (2 * self.variable_h) for i in range(0, len(losses), 2)])\n\n # ADAM update\n mean[index] = beta1 * mean[index] + (1 - beta1) * grads\n var[index] = beta2 * var[index] + (1 - beta2) * grads**2\n\n corr = (np.sqrt(1 - np.power(beta2, adam_epochs[index]))) / (1 - np.power(beta1, adam_epochs[index]))\n orig_shape = current_noise.shape\n current_noise = current_noise.reshape(-1)\n current_noise[index] -= learning_rate * corr * mean[index] / (np.sqrt(var[index]) + 1e-8)\n adam_epochs[index] += 1\n\n if proj and hasattr(self.estimator, \"clip_values\") and self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n current_noise[index] = np.clip(current_noise[index], clip_min, clip_max)\n\n return current_noise.reshape(orig_shape)\n\n def _reset_adam(self, nb_vars: int, indices: np.ndarray | None = None) -> None:\n # If variables are already there and at the right size, reset values\n if self.adam_mean is not None and self.adam_mean.size == nb_vars:\n if indices is None:\n self.adam_mean.fill(0)\n self.adam_var.fill(0) # type: ignore\n self.adam_epochs.fill(1) # type: ignore\n else:\n self.adam_mean[indices] = 0\n self.adam_var[indices] = 0 # type: ignore\n self.adam_epochs[indices] = 1 # type: ignore\n else:\n # Allocate Adam variables\n self.adam_mean = np.zeros(nb_vars, dtype=ART_NUMPY_DTYPE)\n self.adam_var = np.zeros(nb_vars, dtype=ART_NUMPY_DTYPE)\n self.adam_epochs = np.ones(nb_vars, dtype=int)\n\n def _resize_image(self, x: np.ndarray, size_x: int, size_y: int, reset: bool = False) -> np.ndarray:\n if not self.estimator.channels_first:\n dims = (x.shape[0], size_x, size_y, x.shape[-1])\n else:\n dims = (x.shape[0], x.shape[1], size_x, size_y)\n nb_vars = np.prod(dims).item()\n\n if reset:\n # Reset variables to original size and value\n if dims == x.shape:\n resized_x = x\n if x.shape == self._current_noise.shape:\n self._current_noise.fill(0)\n else:\n self._current_noise = np.zeros(x.shape, dtype=ART_NUMPY_DTYPE)\n else:\n resized_x = zoom(\n x,\n (\n 1,\n dims[1] / x.shape[1],\n dims[2] / x.shape[2],\n dims[3] / x.shape[3],\n ),\n )\n self._current_noise = np.zeros(dims, dtype=ART_NUMPY_DTYPE)\n self._sample_prob = np.ones(nb_vars, dtype=ART_NUMPY_DTYPE) / nb_vars\n else:\n # Rescale variables and reset values\n resized_x = zoom(x, (1, dims[1] / x.shape[1], dims[2] / x.shape[2], dims[3] / x.shape[3]))\n self._sample_prob = self._get_prob(self._current_noise, double=True).flatten()\n self._current_noise = np.zeros(dims, dtype=ART_NUMPY_DTYPE)\n\n # Reset Adam\n self._reset_adam(nb_vars)\n\n return resized_x\n\n def _get_prob(self, prev_noise: np.ndarray, double: bool = False) -> np.ndarray:\n dims = list(prev_noise.shape)\n channel_index = 1 if self.estimator.channels_first else 3\n\n # Double size if needed\n if double:\n dims = [2 * size if i not in [0, channel_index] else size for i, size in enumerate(dims)]\n\n prob = np.empty(shape=dims, dtype=np.float32)\n image = np.abs(prev_noise)\n\n for channel in range(prev_noise.shape[channel_index]):\n if not self.estimator.channels_first:\n image_pool = self._max_pooling(image[:, :, :, channel], dims[1] // 8)\n if double:\n prob[:, :, :, channel] = np.abs(zoom(image_pool, [1, 2, 2]))\n else:\n prob[:, :, :, channel] = image_pool\n elif self.estimator.channels_first:\n image_pool = self._max_pooling(image[:, channel, :, :], dims[2] // 8)\n if double:\n prob[:, channel, :, :] = np.abs(zoom(image_pool, [1, 2, 2]))\n else:\n prob[:, channel, :, :] = image_pool\n\n prob /= np.sum(prob)\n\n return prob\n\n @staticmethod\n def _max_pooling(image: np.ndarray, kernel_size: int) -> np.ndarray:\n img_pool = np.copy(image)\n for i in range(0, image.shape[1], kernel_size):\n for j in range(0, image.shape[2], kernel_size):\n img_pool[:, i : i + kernel_size, j : j + kernel_size] = np.max(\n image[:, i : i + kernel_size, j : j + kernel_size],\n axis=(1, 2),\n keepdims=True,\n )\n\n return img_pool\n\n def _check_params(self) -> None:\n if not isinstance(self.binary_search_steps, int) or self.binary_search_steps < 0:\n raise ValueError(\"The number of binary search steps must be a non-negative integer.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.nb_parallel, int) or self.nb_parallel < 1:\n raise ValueError(\"The number of parallel coordinates must be an integer greater than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size < 1:\n raise ValueError(\"The batch size must be an integer greater than zero.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_patch/adversarial_patch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the adversarial patch attack `AdversarialPatch`. This attack generates an adversarial patch that\ncan be printed into the physical world with a common printer. The patch can be used to fool image and video classifiers.\n\n| Paper link: https://arxiv.org/abs/1712.09665\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch_numpy import AdversarialPatchNumpy\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch_tensorflow import AdversarialPatchTensorFlowV2\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch_pytorch import AdversarialPatchPyTorch\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier\nfrom art.attacks.attack import EvasionAttack\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialPatch(EvasionAttack):\n \"\"\"\n Implementation of the adversarial patch attack for square and rectangular images and videos.\n\n | Paper link: https://arxiv.org/abs/1712.09665\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"rotation_max\",\n \"scale_min\",\n \"scale_max\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"targeted\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n rotation_max: float = 22.5,\n scale_min: float = 0.1,\n scale_max: float = 1.0,\n learning_rate: float = 5.0,\n max_iter: int = 500,\n batch_size: int = 16,\n patch_shape: tuple[int, int, int] | None = None,\n targeted: bool = True,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.AdversarialPatch`.\n\n :param classifier: A trained classifier.\n :param rotation_max: The maximum rotation applied to random patches. The value is expected to be in the\n range `[0, 180]`.\n :param scale_min: The minimum scaling applied to random patches. The value should be in the range `[0, 1]`,\n but less than `scale_max`.\n :param scale_max: The maximum scaling applied to random patches. The value should be in the range `[0, 1]`, but\n larger than `scale_min.`\n :param learning_rate: The learning rate of the optimization.\n :param max_iter: The number of optimization steps.\n :param batch_size: The size of the training batch.\n :param patch_shape: The shape of the adversarial patch as a tuple of shape (width, height, nb_channels).\n Currently only supported for `TensorFlowV2Classifier`. For classifiers of other frameworks\n the `patch_shape` is set to the shape of the input samples.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n if self.estimator.clip_values is None: # pragma: no cover\n raise ValueError(\"Adversarial Patch attack requires a classifier with clip_values.\")\n\n self._attack: AdversarialPatchTensorFlowV2 | AdversarialPatchPyTorch | AdversarialPatchNumpy\n if isinstance(self.estimator, TensorFlowV2Classifier):\n self._attack = AdversarialPatchTensorFlowV2(\n classifier=classifier,\n rotation_max=rotation_max,\n scale_min=scale_min,\n scale_max=scale_max,\n learning_rate=learning_rate,\n max_iter=max_iter,\n batch_size=batch_size,\n patch_shape=patch_shape,\n targeted=targeted,\n verbose=verbose,\n )\n elif isinstance(self.estimator, PyTorchClassifier):\n if patch_shape is not None:\n self._attack = AdversarialPatchPyTorch(\n estimator=classifier,\n rotation_max=rotation_max,\n scale_min=scale_min,\n scale_max=scale_max,\n distortion_scale_max=0.0,\n learning_rate=learning_rate,\n max_iter=max_iter,\n batch_size=batch_size,\n patch_shape=patch_shape,\n patch_type=\"circle\",\n targeted=targeted,\n verbose=verbose,\n )\n else:\n raise ValueError(\"`patch_shape` cannot be `None` for `AdversarialPatchPyTorch`.\")\n else:\n self._attack = AdversarialPatchNumpy(\n classifier=classifier,\n rotation_max=rotation_max,\n scale_min=scale_min,\n scale_max=scale_max,\n learning_rate=learning_rate,\n max_iter=max_iter,\n batch_size=batch_size,\n targeted=targeted,\n verbose=verbose,\n )\n self._check_params()\n\n def generate( # type: ignore\n self, x: np.ndarray, y: np.ndarray | None = None, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate an adversarial patch and return the patch and its mask in arrays.\n\n :param x: An array with the original input images of shape NHWC or NCHW or input videos of shape NFHWC or NFCHW.\n :param y: An array with the original true labels.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :type mask: `np.ndarray`\n :param reset_patch: If `True` reset patch to initial values of mean of minimal and maximal clip value, else if\n `False` (default) restart from previous patch values created by previous call to `generate`\n or mean of minimal and maximal clip value if first call to `generate`.\n :type reset_patch: bool\n :return: An array with adversarial patch and an array of the patch mask.\n \"\"\"\n logger.info(\"Creating adversarial patch.\")\n\n if len(x.shape) == 2: # pragma: no cover\n raise ValueError(\n \"Feature vectors detected. The adversarial patch can only be applied to data with spatial \"\n \"dimensions.\"\n )\n\n return self._attack.generate(x=x, y=y, **kwargs)\n\n def apply_patch(\n self, x: np.ndarray, scale: float, patch_external: np.ndarray | None = None, **kwargs\n ) -> np.ndarray:\n \"\"\"\n A function to apply the learned adversarial patch to images or videos.\n\n :param x: Instances to apply randomly transformed patch.\n :param scale: Scale of the applied patch in relation to the classifier input shape.\n :param patch_external: External patch to apply to images `x`.\n :return: The patched instances.\n \"\"\"\n return self._attack.apply_patch(x, scale, patch_external=patch_external, **kwargs)\n\n def reset_patch(self, initial_patch_value: float | np.ndarray | None) -> None:\n \"\"\"\n Reset the adversarial patch.\n\n :param initial_patch_value: Patch value to use for resetting the patch.\n \"\"\"\n self._attack.reset_patch(initial_patch_value=initial_patch_value)\n\n def insert_transformed_patch(self, x: np.ndarray, patch: np.ndarray, image_coords: np.ndarray):\n \"\"\"\n Insert patch to image based on given or selected coordinates.\n\n :param x: The image to insert the patch.\n :param patch: The patch to be transformed and inserted.\n :param image_coords: The coordinates of the 4 corners of the transformed, inserted patch of shape\n [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] in pixel units going in clockwise direction, starting with upper\n left corner.\n :return: The input `x` with the patch inserted.\n \"\"\"\n return self._attack.insert_transformed_patch(x, patch, image_coords)\n\n def set_params(self, **kwargs) -> None:\n super().set_params(**kwargs)\n self._attack.set_params(**kwargs)\n\n def _check_params(self) -> None:\n if not isinstance(self._attack.rotation_max, (float, int)):\n raise ValueError(\"The maximum rotation of the random patches must be of type float.\")\n if self._attack.rotation_max < 0 or self._attack.rotation_max > 180.0:\n raise ValueError(\"The maximum rotation of the random patches must be between 0 and 180 degrees.\")\n\n if not isinstance(self._attack.scale_min, float):\n raise ValueError(\"The minimum scale of the random patched must be of type float.\")\n if self._attack.scale_min < 0 or self._attack.scale_min >= self._attack.scale_max:\n raise ValueError(\n \"The minimum scale of the random patched must be greater than 0 and less than the maximum scaling.\"\n )\n\n if not isinstance(self._attack.scale_max, float):\n raise ValueError(\"The maximum scale of the random patched must be of type float.\")\n if self._attack.scale_max > 1:\n raise ValueError(\"The maximum scale of the random patched must not be greater than 1.\")\n\n if not isinstance(self._attack.learning_rate, float):\n raise ValueError(\"The learning rate must be of type float.\")\n\n if not self._attack.learning_rate > 0.0:\n raise ValueError(\"The learning rate must be greater than 0.0.\")\n\n if not isinstance(self._attack.max_iter, int):\n raise ValueError(\"The number of optimization steps must be of type int.\")\n if not self._attack.max_iter > 0:\n raise ValueError(\"The number of optimization steps must be greater than 0.\")\n\n if not isinstance(self._attack.batch_size, int):\n raise ValueError(\"The batch size must be of type int.\")\n if not self._attack.batch_size > 0:\n raise ValueError(\"The batch size must be greater than 0.\")\n\n if not isinstance(self._attack.targeted, bool):\n raise ValueError(\"The argument `targeted` has to be of type bool.\")\n\n if not isinstance(self._attack.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_patch/adversarial_patch_numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the adversarial patch attack `AdversarialPatch`. This attack generates an adversarial patch that\ncan be printed into the physical world with a common printer. The patch can be used to fool image and video classifiers.\n\n| Paper link: https://arxiv.org/abs/1712.09665\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport math\nfrom typing import TYPE_CHECKING\n\nimport random\nimport numpy as np\nfrom scipy.ndimage import rotate, shift, zoom\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.adversarial_patch.utils import insert_transformed_patch\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialPatchNumpy(EvasionAttack):\n \"\"\"\n Implementation of the adversarial patch attack for square and rectangular images and videos in Numpy.\n\n | Paper link: https://arxiv.org/abs/1712.09665\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"rotation_max\",\n \"scale_min\",\n \"scale_max\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n target: int = 0,\n rotation_max: float = 22.5,\n scale_min: float = 0.1,\n scale_max: float = 1.0,\n learning_rate: float = 5.0,\n max_iter: int = 500,\n clip_patch: list | tuple | None = None,\n batch_size: int = 16,\n targeted: bool = True,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of the :class:`.AdversarialPatchNumpy`.\n\n :param classifier: A trained classifier.\n :param target: The target label for the created patch.\n :param rotation_max: The maximum rotation applied to random patches. The value is expected to be in the\n range `[0, 180]`.\n :param scale_min: The minimum scaling applied to random patches. The value should be in the range `[0, 1]`,\n but less than `scale_max`.\n :param scale_max: The maximum scaling applied to random patches. The value should be in the range `[0, 1]`, but\n larger than `scale_min.`\n :param learning_rate: The learning rate of the optimization.\n :param max_iter: The number of optimization steps.\n :param clip_patch: The minimum and maximum values for each channel in the form\n [(float, float), (float, float), (float, float)].\n :param batch_size: The size of the training batch.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False). Currently only targeted\n attacks are supported.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.target = target\n self.rotation_max = rotation_max\n self.scale_min = scale_min\n self.scale_max = scale_max\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.clip_patch = clip_patch\n self.targeted = targeted\n self.verbose = verbose\n self._check_params()\n\n if len(self.estimator.input_shape) not in [3, 4]:\n raise ValueError(\n \"Unexpected input_shape in estimator detected. AdversarialPatch is expecting images or videos as input.\"\n )\n\n self.input_shape = self.estimator.input_shape\n\n self.nb_dims = len(self.input_shape)\n if self.nb_dims == 3:\n if self.estimator.channels_first:\n self.i_c = 0\n self.i_h = 1\n self.i_w = 2\n else:\n self.i_h = 0\n self.i_w = 1\n self.i_c = 2\n elif self.nb_dims == 4:\n if self.estimator.channels_first:\n self.i_c = 1\n self.i_h = 2\n self.i_w = 3\n else:\n self.i_h = 1\n self.i_w = 2\n self.i_c = 3\n\n smallest_image_edge = np.minimum(self.input_shape[self.i_h], self.input_shape[self.i_w])\n nb_channels = self.input_shape[self.i_c]\n\n if self.estimator.channels_first:\n self.patch_shape = (nb_channels, smallest_image_edge, smallest_image_edge)\n else:\n self.patch_shape = (smallest_image_edge, smallest_image_edge, nb_channels)\n\n self.patch: np.ndarray\n self.mean_value = (\n self.estimator.clip_values[1] - self.estimator.clip_values[0]\n ) / 2.0 + self.estimator.clip_values[0]\n self.reset_patch(self.mean_value)\n\n def generate( # type: ignore\n self, x: np.ndarray, y: np.ndarray | None = None, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate an adversarial patch and return the patch and its mask in arrays.\n\n :param x: An array with the original input images of shape NHWC or NCHW or input videos of shape NFHWC or NFCHW.\n :param y: An array with the original true labels.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :type mask: `np.ndarray`\n :param reset_patch: If `True` reset patch to initial values of mean of minimal and maximal clip value, else if\n `False` (default) restart from previous patch values created by previous call to `generate`\n or mean of minimal and maximal clip value if first call to `generate`.\n :type reset_patch: bool\n :return: An array with adversarial patch and an array of the patch mask.\n \"\"\"\n logger.info(\"Creating adversarial patch.\")\n\n test_input_shape = list(self.estimator.input_shape)\n\n for i, size in enumerate(self.estimator.input_shape):\n if size is None or size != x.shape[i + 1]:\n test_input_shape[i] = x.shape[i + 1]\n\n self.input_shape = tuple(test_input_shape)\n\n mask = kwargs.get(\"mask\")\n if mask is not None:\n mask = mask.copy()\n if mask is not None and (\n (mask.dtype != bool)\n or not (mask.shape[0] == 1 or mask.shape[0] == x.shape[0])\n or not (\n (mask.shape[1] == x.shape[1] and mask.shape[2] == x.shape[2])\n or (mask.shape[1] == x.shape[2] and mask.shape[2] == x.shape[3])\n )\n ):\n raise ValueError(\n \"The shape of `mask` has to be equal to the shape of a single samples (1, H, W) or the\"\n \"shape of `x` (N, H, W) without their channel dimensions.\"\n )\n\n if len(x.shape) == 2:\n raise ValueError(\n \"Feature vectors detected. The adversarial patch can only be applied to data with spatial \"\n \"dimensions.\"\n )\n\n if kwargs.get(\"reset_patch\"):\n self.reset_patch(self.mean_value)\n\n if y is not None:\n y_target = check_and_transform_label_format(labels=y, nb_classes=self.estimator.nb_classes)\n else:\n raise ValueError(\"Labels `y` cannot be `None`.\")\n\n for _ in trange(self.max_iter, desc=\"Adversarial Patch Numpy\", disable=not self.verbose):\n patched_images, patch_mask_transformed, transforms = self._augment_images_with_random_patch(\n x, self.patch, mask=mask\n )\n\n num_batches = int(math.ceil(x.shape[0] / self.batch_size))\n patch_gradients = np.zeros_like(self.patch)\n\n for i_batch in range(num_batches):\n i_batch_start = i_batch * self.batch_size\n i_batch_end = (i_batch + 1) * self.batch_size\n\n gradients = self.estimator.loss_gradient(\n patched_images[i_batch_start:i_batch_end],\n y_target[i_batch_start:i_batch_end],\n )\n\n for i_image in range(gradients.shape[0]):\n patch_gradients_i = self._reverse_transformation(\n gradients[i_image, :, :, :],\n patch_mask_transformed[i_image, :, :, :],\n transforms[i_image],\n )\n if self.nb_dims == 4:\n patch_gradients_i = np.mean(patch_gradients_i, axis=0)\n patch_gradients += patch_gradients_i\n\n # patch_gradients = patch_gradients / (num_batches * self.batch_size)\n self.patch -= patch_gradients * self.learning_rate\n if self.estimator.clip_values is not None:\n self.patch = np.clip(\n self.patch,\n a_min=self.estimator.clip_values[0],\n a_max=self.estimator.clip_values[1],\n )\n else:\n raise ValueError(\"Clip values of estimator cannot be None.\")\n\n return self.patch, self._get_circular_patch_mask()\n\n def apply_patch(\n self,\n x: np.ndarray,\n scale: float,\n patch_external: np.ndarray | None = None,\n mask: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n A function to apply the learned adversarial patch to images or videos.\n\n :param x: Instances to apply randomly transformed patch.\n :param scale: Scale of the applied patch in relation to the classifier input shape.\n :param patch_external: External patch to apply to images `x`.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :return: The patched instances.\n \"\"\"\n if mask is not None:\n mask = mask.copy()\n patch = patch_external if patch_external is not None else self.patch\n patched_x, _, _ = self._augment_images_with_random_patch(x, patch, mask=mask, scale=scale)\n return patched_x\n\n def _check_params(self) -> None:\n if not isinstance(self.rotation_max, (float, int)):\n raise ValueError(\"The maximum rotation of the random patches must be of type float.\")\n if self.rotation_max < 0 or self.rotation_max > 180.0:\n raise ValueError(\"The maximum rotation of the random patches must be between 0 and 180 degrees.\")\n\n if not isinstance(self.scale_min, float):\n raise ValueError(\"The minimum scale of the random patched must be of type float.\")\n if self.scale_min < 0 or self.scale_min > self.scale_max:\n raise ValueError(\n \"The minimum scale of the random patched must be greater than 0 and less than the maximum scaling.\"\n )\n\n if not isinstance(self.scale_max, float):\n raise ValueError(\"The maximum scale of the random patched must be of type float.\")\n if self.scale_max > 1:\n raise ValueError(\"The maximum scale of the random patched must not be greater than 1.\")\n\n if not isinstance(self.learning_rate, float):\n raise ValueError(\"The learning rate must be of type float.\")\n if self.learning_rate <= 0.0:\n raise ValueError(\"The learning rate must be greater than 0.0.\")\n\n if not isinstance(self.max_iter, int):\n raise ValueError(\"The number of optimization steps must be of type int.\")\n if self.max_iter <= 0:\n raise ValueError(\"The number of optimization steps must be greater than 0.\")\n\n if not isinstance(self.batch_size, int):\n raise ValueError(\"The batch size must be of type int.\")\n if self.batch_size <= 0:\n raise ValueError(\"The batch size must be greater than 0.\")\n\n if not isinstance(self.targeted, bool) and not self.targeted:\n raise ValueError(\n \"The argument `targeted` has to be of type bool. Currently AdversarialPatchNumpy only supports targeted\"\n \"attacks.\"\n )\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n def _get_circular_patch_mask(self, sharpness: int = 40) -> np.ndarray:\n \"\"\"\n Return a circular patch mask\n \"\"\"\n diameter = np.minimum(self.input_shape[self.i_h], self.input_shape[self.i_w])\n\n x = np.linspace(-1, 1, diameter)\n y = np.linspace(-1, 1, diameter)\n x_grid, y_grid = np.meshgrid(x, y, sparse=True)\n z_grid = (x_grid**2 + y_grid**2) ** sharpness\n\n mask = 1 - np.clip(z_grid, -1, 1)\n\n channel_index = 1 if self.estimator.channels_first else 3\n axis = channel_index - 1\n mask = np.expand_dims(mask, axis=axis)\n\n mask = np.broadcast_to(mask, self.patch_shape).astype(np.float32)\n\n if self.nb_dims == 4:\n mask = np.expand_dims(mask, axis=0)\n mask = np.repeat(mask, axis=0, repeats=self.input_shape[0]).astype(np.float32)\n\n return mask\n\n def _augment_images_with_random_patch(self, images, patch, mask=None, scale=None):\n \"\"\"\n Augment images with randomly rotated, shifted and scaled patch.\n \"\"\"\n transformations = []\n patched_images = []\n patch_mask_transformed_list = []\n\n for i_image in range(images.shape[0]):\n if mask is not None:\n if mask.shape[0] == 1:\n mask_2d = mask[0, :, :]\n else:\n mask_2d = mask[i_image, :, :]\n else:\n mask_2d = mask\n\n (\n patch_transformed,\n patch_mask_transformed,\n transformation,\n ) = self._random_transformation(patch, scale, mask_2d)\n\n inverted_patch_mask_transformed = 1 - patch_mask_transformed\n\n patched_image = (\n images[i_image, :, :, :] * inverted_patch_mask_transformed + patch_transformed * patch_mask_transformed\n )\n patched_image = np.expand_dims(patched_image, axis=0)\n patched_images.append(patched_image)\n\n patch_mask_transformed = np.expand_dims(patch_mask_transformed, axis=0)\n patch_mask_transformed_list.append(patch_mask_transformed)\n transformations.append(transformation)\n\n patched_images = np.concatenate(patched_images, axis=0)\n patch_mask_transformed_np = np.concatenate(patch_mask_transformed_list, axis=0)\n\n return patched_images, patch_mask_transformed_np, transformations\n\n def _rotate(self, x, angle):\n axes = (self.i_h, self.i_w)\n return rotate(x, angle=angle, reshape=False, axes=axes, order=1)\n\n def _scale(self, x, scale):\n zooms = None\n height, width = x.shape[self.i_h], x.shape[self.i_w]\n\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n zooms = (1.0, scale, scale)\n elif self.nb_dims == 4:\n zooms = (1.0, 1.0, scale, scale)\n elif not self.estimator.channels_first:\n if self.nb_dims == 3:\n zooms = (scale, scale, 1.0)\n elif self.nb_dims == 4:\n zooms = (1.0, scale, scale, 1.0)\n\n if scale < 1.0:\n scale_h = int(np.round(height * scale))\n scale_w = int(np.round(width * scale))\n top = (height - scale_h) // 2\n left = (width - scale_w) // 2\n\n x_out = np.zeros_like(x)\n\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n x_out[:, top : top + scale_h, left : left + scale_w] = zoom(x, zoom=zooms, order=1)\n elif self.nb_dims == 4:\n x_out[:, :, top : top + scale_h, left : left + scale_w] = zoom(x, zoom=zooms, order=1)\n else:\n if self.nb_dims == 3:\n x_out[top : top + scale_h, left : left + scale_w, :] = zoom(x, zoom=zooms, order=1)\n elif self.nb_dims == 4:\n x_out[:, top : top + scale_h, left : left + scale_w, :] = zoom(x, zoom=zooms, order=1)\n\n elif scale > 1.0:\n scale_h = int(np.round(height / scale)) + 1\n scale_w = int(np.round(width / scale)) + 1\n top = (height - scale_h) // 2\n left = (width - scale_w) // 2\n\n if scale_h <= height and scale_w <= width and top >= 0 and left >= 0:\n\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n x_out = zoom(x[:, top : top + scale_h, left : left + scale_w], zoom=zooms, order=1)\n elif self.nb_dims == 4:\n x_out = zoom(x[:, :, top : top + scale_h, left : left + scale_w], zoom=zooms, order=1)\n else:\n if self.nb_dims == 3:\n x_out = zoom(x[top : top + scale_h, left : left + scale_w, :], zoom=zooms, order=1)\n elif self.nb_dims == 4:\n x_out = zoom(x[:, top : top + scale_h, left : left + scale_w, :], zoom=zooms, order=1)\n\n else:\n x_out = x\n\n cut_top = (x_out.shape[self.i_h] - height) // 2\n cut_left = (x_out.shape[self.i_w] - width) // 2\n\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n x_out = x_out[:, cut_top : cut_top + height, cut_left : cut_left + width]\n elif self.nb_dims == 4:\n x_out = x_out[:, :, cut_top : cut_top + height, cut_left : cut_left + width]\n else:\n if self.nb_dims == 3:\n x_out = x_out[cut_top : cut_top + height, cut_left : cut_left + width, :]\n elif self.nb_dims == 4:\n x_out = x_out[:, cut_top : cut_top + height, cut_left : cut_left + width, :]\n\n else:\n x_out = x\n\n assert x.shape == x_out.shape\n\n return x_out\n\n def _shift(self, x, shift_h, shift_w):\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n shift_hw = (0, shift_h, shift_w)\n elif self.nb_dims == 4:\n shift_hw = (0, 0, shift_h, shift_w)\n else:\n if self.nb_dims == 3:\n shift_hw = (shift_h, shift_w, 0)\n elif self.nb_dims == 4:\n shift_hw = (0, shift_h, shift_w, 0)\n return shift(x, shift=shift_hw, order=1)\n\n def _random_transformation(self, patch, scale, mask_2d):\n patch_mask = self._get_circular_patch_mask()\n transformation = {}\n\n if self.nb_dims == 4:\n patch = np.expand_dims(patch, axis=0)\n patch = np.repeat(patch, axis=0, repeats=self.input_shape[0]).astype(np.float32)\n\n # rotate\n angle = random.uniform(-self.rotation_max, self.rotation_max)\n transformation[\"rotate\"] = angle\n patch = self._rotate(patch, angle)\n patch_mask = self._rotate(patch_mask, angle)\n\n # scale\n if scale is None:\n scale = random.uniform(self.scale_min, self.scale_max)\n patch = self._scale(patch, scale)\n patch_mask = self._scale(patch_mask, scale)\n transformation[\"scale\"] = scale\n\n # pad\n pad_h_before = int((self.input_shape[self.i_h] - patch.shape[self.i_h]) / 2)\n pad_h_after = int(self.input_shape[self.i_h] - pad_h_before - patch.shape[self.i_h])\n\n pad_w_before = int((self.input_shape[self.i_w] - patch.shape[self.i_w]) / 2)\n pad_w_after = int(self.input_shape[self.i_w] - pad_w_before - patch.shape[self.i_w])\n\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n pad_width = ((0, 0), (pad_h_before, pad_h_after), (pad_w_before, pad_w_after)) # type: ignore\n elif self.nb_dims == 4:\n pad_width = ((0, 0), (0, 0), (pad_h_before, pad_h_after), (pad_w_before, pad_w_after)) # type: ignore\n else:\n if self.nb_dims == 3:\n pad_width = ((pad_h_before, pad_h_after), (pad_w_before, pad_w_after), (0, 0)) # type: ignore\n elif self.nb_dims == 4:\n pad_width = ((0, 0), (pad_h_before, pad_h_after), (pad_w_before, pad_w_after), (0, 0)) # type: ignore\n\n transformation[\"pad_h_before\"] = pad_h_before\n transformation[\"pad_w_before\"] = pad_w_before\n\n patch = np.pad(\n patch,\n pad_width=pad_width,\n mode=\"constant\",\n constant_values=(0, 0),\n )\n patch_mask = np.pad(\n patch_mask,\n pad_width=pad_width,\n mode=\"constant\",\n constant_values=(0, 0),\n )\n\n # shift\n if mask_2d is None:\n shift_max_h = (self.input_shape[self.i_h] - self.patch_shape[self.i_h] * scale) / 2.0\n shift_max_w = (self.input_shape[self.i_w] - self.patch_shape[self.i_w] * scale) / 2.0\n if shift_max_h > 0 and shift_max_w > 0:\n shift_h = random.uniform(-shift_max_h, shift_max_h)\n shift_w = random.uniform(-shift_max_w, shift_max_w)\n patch = self._shift(patch, shift_h, shift_w)\n patch_mask = self._shift(patch_mask, shift_h, shift_w)\n else:\n shift_h = 0\n shift_w = 0\n else:\n edge_x_0 = int(self.patch_shape[self.i_h] * scale) // 2\n edge_x_1 = int(self.patch_shape[self.i_h] * scale) - edge_x_0\n edge_y_0 = int(self.patch_shape[self.i_w] * scale) // 2\n edge_y_1 = int(self.patch_shape[self.i_w] * scale) - edge_y_0\n\n mask_2d[0:edge_x_0, :] = False\n mask_2d[-edge_x_1:, :] = False\n mask_2d[:, 0:edge_y_0] = False\n mask_2d[:, -edge_y_1:] = False\n\n num_pos = np.argwhere(mask_2d).shape[0]\n pos_id = np.random.choice(num_pos, size=1)\n pos = np.argwhere(mask_2d)[pos_id[0]]\n shift_h = pos[0] - (self.input_shape[self.i_h]) / 2.0\n shift_w = pos[1] - (self.input_shape[self.i_w]) / 2.0\n\n patch = self._shift(patch, shift_h, shift_w)\n patch_mask = self._shift(patch_mask, shift_h, shift_w)\n\n transformation[\"shift_h\"] = shift_h\n transformation[\"shift_w\"] = shift_w\n\n return patch, patch_mask, transformation\n\n def _reverse_transformation(self, gradients: np.ndarray, patch_mask_transformed, transformation) -> np.ndarray:\n gradients = gradients * patch_mask_transformed\n\n # shift\n shift_h = transformation[\"shift_h\"]\n shift_w = transformation[\"shift_w\"]\n gradients = self._shift(gradients, -shift_h, -shift_w)\n\n # unpad\n\n pad_h_before = transformation[\"pad_h_before\"]\n pad_w_before = transformation[\"pad_w_before\"]\n\n if self.estimator.channels_first:\n height, width = self.patch_shape[1], self.patch_shape[2]\n else:\n height, width = self.patch_shape[0], self.patch_shape[1]\n\n if self.estimator.channels_first:\n if self.nb_dims == 3:\n gradients = gradients[:, pad_h_before : pad_h_before + height, pad_w_before : pad_w_before + width]\n elif self.nb_dims == 4:\n gradients = gradients[:, :, pad_h_before : pad_h_before + height, pad_w_before : pad_w_before + width]\n else:\n if self.nb_dims == 3:\n gradients = gradients[pad_h_before : pad_h_before + height, pad_w_before : pad_w_before + width, :]\n elif self.nb_dims == 4:\n gradients = gradients[:, pad_h_before : pad_h_before + height, pad_w_before : pad_w_before + width, :]\n\n # scale\n scale = transformation[\"scale\"]\n gradients = self._scale(gradients, 1.0 / scale)\n\n # rotate\n angle = transformation[\"rotate\"]\n gradients = self._rotate(gradients, -angle)\n\n return gradients\n\n def reset_patch(self, initial_patch_value: float | np.ndarray | None) -> None:\n \"\"\"\n Reset the adversarial patch.\n\n :param initial_patch_value: Patch value to use for resetting the patch.\n \"\"\"\n if initial_patch_value is None:\n self.patch = np.ones(shape=self.patch_shape).astype(np.float32) * self.mean_value\n elif isinstance(initial_patch_value, float):\n self.patch = np.ones(shape=self.patch_shape).astype(np.float32) * initial_patch_value\n elif self.patch is not None and self.patch.shape == initial_patch_value.shape:\n self.patch = initial_patch_value\n else:\n raise ValueError(\"Unexpected value for initial_patch_value.\")\n\n @staticmethod\n def insert_transformed_patch(x: np.ndarray, patch: np.ndarray, image_coords: np.ndarray):\n \"\"\"\n Insert patch to image based on given or selected coordinates.\n\n :param x: The image to insert the patch.\n :param patch: The patch to be transformed and inserted.\n :param image_coords: The coordinates of the 4 corners of the transformed, inserted patch of shape\n [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] in pixel units going in clockwise direction, starting with upper\n left corner.\n :return: The input `x` with the patch inserted.\n \"\"\"\n return insert_transformed_patch(x, patch, image_coords)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_patch/adversarial_patch_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the adversarial patch attack `AdversarialPatch`. This attack generates an adversarial patch that\ncan be printed into the physical world with a common printer. The patch can be used to fool image and video estimators.\n\n| Paper link: https://arxiv.org/abs/1712.09665\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport math\nfrom packaging.version import parse\nfrom typing import Any, cast, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.adversarial_patch.utils import insert_transformed_patch\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.utils import check_and_transform_label_format, is_probability, to_categorical\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE, PYTORCH_OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialPatchPyTorch(EvasionAttack):\n \"\"\"\n Implementation of the adversarial patch attack for square and rectangular images and videos in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1712.09665\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"rotation_max\",\n \"scale_min\",\n \"scale_max\",\n \"distortion_scale_max\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"patch_shape\",\n \"optimizer\",\n \"targeted\",\n \"summary_writer\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_NEURALNETWORK_TYPE | PYTORCH_OBJECT_DETECTOR_TYPE\",\n rotation_max: float = 22.5,\n scale_min: float = 0.1,\n scale_max: float = 1.0,\n distortion_scale_max: float = 0.0,\n learning_rate: float = 5.0,\n max_iter: int = 500,\n batch_size: int = 16,\n patch_shape: tuple[int, int, int] = (3, 224, 224),\n patch_location: tuple[int, int] | None = None,\n patch_type: str = \"circle\",\n optimizer: str = \"Adam\",\n targeted: bool = True,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.AdversarialPatchPyTorch`.\n\n :param estimator: A trained PyTorch estimator for classification or object detection.\n :param rotation_max: The maximum rotation applied to random patches. The value is expected to be in the\n range `[0, 180]`.\n :param scale_min: The minimum scaling applied to random patches. The value should be in the range `[0, 1]`,\n but less than `scale_max`.\n :param scale_max: The maximum scaling applied to random patches. The value should be in the range `[0, 1]`, but\n larger than `scale_min`.\n :param distortion_scale_max: The maximum distortion scale for perspective transformation in range `[0, 1]`. If\n distortion_scale_max=0.0 the perspective transformation sampling will be disabled.\n :param learning_rate: The learning rate of the optimization. For `optimizer=\"pgd\"` the learning rate gets\n multiplied with the sign of the loss gradients.\n :param max_iter: The number of optimization steps.\n :param batch_size: The size of the training batch.\n :param patch_shape: The shape of the adversarial patch as a tuple of shape CHW (nb_channels, height, width).\n :param patch_location: The location of the adversarial patch as a tuple of shape (upper left x, upper left y).\n :param patch_type: The patch type, either circle or square.\n :param optimizer: The optimization algorithm. Supported values: \"Adam\", and \"pgd\". \"pgd\" corresponds to\n projected gradient descent in L-Inf norm.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n import torch\n import torchvision\n\n torch_version = list(parse(torch.__version__.lower()).release)\n torchvision_version = list(parse(torchvision.__version__.lower()).release)\n assert (\n torch_version[0] >= 1 and torch_version[1] >= 7 or (torch_version[0] >= 2)\n ), \"AdversarialPatchPyTorch requires torch>=1.7.0\"\n assert (\n torchvision_version[0] >= 0 and torchvision_version[1] >= 8\n ), \"AdversarialPatchPyTorch requires torchvision>=0.8.0\"\n\n super().__init__(estimator=estimator, summary_writer=summary_writer)\n self.rotation_max = rotation_max\n self.scale_min = scale_min\n self.scale_max = scale_max\n self.distortion_scale_max = distortion_scale_max\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.patch_shape = patch_shape\n self.patch_location = patch_location\n self.patch_type = patch_type\n\n self.image_shape = estimator.input_shape\n self.targeted = targeted\n self.verbose = verbose\n self._check_params()\n\n self.i_h_patch = 1\n self.i_w_patch = 2\n\n self.input_shape = self.estimator.input_shape\n\n self.nb_dims = len(self.image_shape)\n if self.nb_dims == 3:\n self.i_h = 1\n self.i_w = 2\n elif self.nb_dims == 4:\n self.i_h = 2\n self.i_w = 3\n\n if self.patch_shape[1] != self.patch_shape[2]: # pragma: no cover\n raise ValueError(\"Patch height and width need to be the same.\")\n\n if not ( # pragma: no cover\n self.estimator.postprocessing_defences is None or self.estimator.postprocessing_defences == []\n ):\n raise ValueError(\n \"Framework-specific implementation of Adversarial Patch attack does not yet support \"\n + \"postprocessing defences.\"\n )\n\n mean_value = (self.estimator.clip_values[1] - self.estimator.clip_values[0]) / 2.0 + self.estimator.clip_values[\n 0\n ]\n self._initial_value = np.ones(self.patch_shape) * mean_value\n self._patch = torch.tensor(self._initial_value, requires_grad=True, device=self.estimator.device)\n\n self._optimizer_string = optimizer\n if self._optimizer_string == \"Adam\":\n self._optimizer = torch.optim.Adam([self._patch], lr=self.learning_rate)\n\n def _train_step(\n self,\n images: \"torch.Tensor\",\n target: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]],\n mask: \"torch.Tensor\" | None = None,\n ) -> \"torch.Tensor\":\n import torch\n\n self.estimator.model.zero_grad()\n loss = self._loss(images, target, mask)\n loss.backward(retain_graph=True)\n\n if self._optimizer_string == \"pgd\":\n if self._patch.grad is not None:\n gradients = self._patch.grad.sign() * self.learning_rate\n else:\n raise ValueError(\"Gradient term in PyTorch model is `None`.\")\n\n with torch.no_grad():\n self._patch[:] = torch.clamp(\n self._patch + gradients, min=self.estimator.clip_values[0], max=self.estimator.clip_values[1]\n )\n else:\n self._optimizer.step()\n\n with torch.no_grad():\n self._patch[:] = torch.clamp(\n self._patch, min=self.estimator.clip_values[0], max=self.estimator.clip_values[1]\n )\n\n return loss\n\n def _predictions(\n self, images: \"torch.Tensor\", mask: \"torch.Tensor\" | None, target: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n import torch\n\n patched_input = self._random_overlay(images, self._patch, mask=mask)\n patched_input = torch.clamp(\n patched_input,\n min=self.estimator.clip_values[0],\n max=self.estimator.clip_values[1],\n )\n\n predictions, target = self.estimator._predict_framework(patched_input, target)\n\n return predictions, target\n\n def _loss(\n self,\n images: \"torch.Tensor\",\n target: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]],\n mask: \"torch.Tensor\" | None,\n ) -> \"torch.Tensor\":\n import torch\n\n if isinstance(target, torch.Tensor):\n\n predictions, target = self._predictions(images, mask, target)\n\n if self.use_logits:\n loss = torch.nn.functional.cross_entropy(\n input=predictions, target=torch.argmax(target, dim=1), reduction=\"mean\"\n )\n else:\n loss = torch.nn.functional.nll_loss(\n input=predictions, target=torch.argmax(target, dim=1), reduction=\"mean\"\n )\n\n else:\n patched_input = self._random_overlay(images, self._patch, mask=mask)\n patched_input = torch.clamp(\n patched_input,\n min=self.estimator.clip_values[0],\n max=self.estimator.clip_values[1],\n )\n\n loss = self.estimator.compute_loss(x=patched_input, y=target)\n\n if (not self.targeted and self._optimizer_string != \"pgd\") or self.targeted and self._optimizer_string == \"pgd\":\n loss = -loss\n\n return loss\n\n def _get_circular_patch_mask(self, nb_samples: int, sharpness: int = 40) -> \"torch.Tensor\":\n \"\"\"\n Return a circular patch mask.\n \"\"\"\n import torch\n\n diameter = np.minimum(self.patch_shape[self.i_h_patch], self.patch_shape[self.i_w_patch])\n\n if self.patch_type == \"circle\":\n x = np.linspace(-1, 1, diameter)\n y = np.linspace(-1, 1, diameter)\n x_grid, y_grid = np.meshgrid(x, y, sparse=True)\n z_grid = (x_grid**2 + y_grid**2) ** sharpness\n image_mask: int | np.ndarray[Any, np.dtype[Any]] = 1 - np.clip(z_grid, -1, 1)\n elif self.patch_type == \"square\":\n image_mask = np.ones((diameter, diameter))\n\n image_mask = np.expand_dims(image_mask, axis=0)\n image_mask = np.broadcast_to(image_mask, self.patch_shape)\n image_mask_tensor = torch.Tensor(np.array(image_mask)).to(self.estimator.device)\n image_mask_tensor = torch.stack([image_mask_tensor] * nb_samples, dim=0)\n return image_mask_tensor\n\n def _random_overlay(\n self,\n images: \"torch.Tensor\",\n patch: \"torch.Tensor\",\n scale: float | None = None,\n mask: \"torch.Tensor\" | None = None,\n ) -> \"torch.Tensor\":\n import torch\n import torchvision\n\n # Ensure channels-first\n if not self.estimator.channels_first:\n images = torch.permute(images, (0, 3, 1, 2))\n\n nb_samples = images.shape[0]\n\n image_mask = self._get_circular_patch_mask(nb_samples=nb_samples)\n image_mask = image_mask.float()\n\n self.image_shape = images.shape[1:]\n\n smallest_image_edge = np.minimum(self.image_shape[self.i_h], self.image_shape[self.i_w])\n\n image_mask = torchvision.transforms.functional.resize(\n img=image_mask,\n size=(smallest_image_edge, smallest_image_edge),\n interpolation=2,\n )\n\n pad_h_before = int((self.image_shape[self.i_h] - image_mask.shape[self.i_h_patch + 1]) / 2)\n pad_h_after = int(self.image_shape[self.i_h] - pad_h_before - image_mask.shape[self.i_h_patch + 1])\n\n pad_w_before = int((self.image_shape[self.i_w] - image_mask.shape[self.i_w_patch + 1]) / 2)\n pad_w_after = int(self.image_shape[self.i_w] - pad_w_before - image_mask.shape[self.i_w_patch + 1])\n\n image_mask = torchvision.transforms.functional.pad(\n img=image_mask,\n padding=[pad_w_before, pad_h_before, pad_w_after, pad_h_after],\n fill=0,\n padding_mode=\"constant\",\n )\n\n if self.nb_dims == 4:\n image_mask = torch.unsqueeze(image_mask, dim=1)\n image_mask = torch.repeat_interleave(image_mask, dim=1, repeats=self.input_shape[0])\n\n image_mask = image_mask.float()\n\n patch = patch.float()\n padded_patch = torch.stack([patch] * nb_samples)\n\n padded_patch = torchvision.transforms.functional.resize(\n img=padded_patch,\n size=(smallest_image_edge, smallest_image_edge),\n interpolation=2,\n )\n\n padded_patch = torchvision.transforms.functional.pad(\n img=padded_patch,\n padding=[pad_w_before, pad_h_before, pad_w_after, pad_h_after],\n fill=0,\n padding_mode=\"constant\",\n )\n\n if self.nb_dims == 4:\n padded_patch = torch.unsqueeze(padded_patch, dim=1)\n padded_patch = torch.repeat_interleave(padded_patch, dim=1, repeats=self.input_shape[0])\n\n padded_patch = padded_patch.float()\n\n image_mask_list = []\n padded_patch_list = []\n\n for i_sample in range(nb_samples):\n if self.patch_location is None:\n if scale is None:\n im_scale = np.random.uniform(low=self.scale_min, high=self.scale_max)\n else:\n im_scale = scale\n else:\n im_scale = self.patch_shape[self.i_h] / smallest_image_edge\n\n if mask is None:\n if self.patch_location is None:\n padding_after_scaling_h = (\n self.image_shape[self.i_h] - im_scale * padded_patch.shape[self.i_h + 1]\n ) / 2.0\n padding_after_scaling_w = (\n self.image_shape[self.i_w] - im_scale * padded_patch.shape[self.i_w + 1]\n ) / 2.0\n x_shift = np.random.uniform(-padding_after_scaling_w, padding_after_scaling_w)\n y_shift = np.random.uniform(-padding_after_scaling_h, padding_after_scaling_h)\n else:\n padding_h = int(math.floor(self.image_shape[self.i_h] - self.patch_shape[self.i_h]) / 2.0)\n padding_w = int(math.floor(self.image_shape[self.i_w] - self.patch_shape[self.i_w]) / 2.0)\n x_shift = -padding_w + self.patch_location[0]\n y_shift = -padding_h + self.patch_location[1]\n else:\n mask_2d = mask[i_sample, :, :]\n\n edge_h_0 = int(im_scale * padded_patch.shape[self.i_h + 1]) // 2\n edge_h_1 = int(im_scale * padded_patch.shape[self.i_h + 1]) - edge_h_0\n edge_w_0 = int(im_scale * padded_patch.shape[self.i_w + 1]) // 2\n edge_w_1 = int(im_scale * padded_patch.shape[self.i_w + 1]) - edge_w_0\n\n mask_2d[0:edge_h_0, :] = False\n if edge_h_1 > 0:\n mask_2d[-edge_h_1:, :] = False\n mask_2d[:, 0:edge_w_0] = False\n if edge_w_1 > 0:\n mask_2d[:, -edge_w_1:] = False\n\n num_pos = np.nonzero(mask_2d.int())\n pos_id = np.random.choice(num_pos.shape[0], size=1, replace=False) # type: ignore\n pos = num_pos[pos_id[0]]\n y_shift = pos[0] - self.image_shape[self.i_h] // 2\n x_shift = pos[1] - self.image_shape[self.i_w] // 2\n\n phi_rotate = float(np.random.uniform(-self.rotation_max, self.rotation_max))\n\n image_mask_i = image_mask[i_sample]\n\n height = padded_patch.shape[self.i_h + 1]\n width = padded_patch.shape[self.i_w + 1]\n\n half_height = height // 2\n half_width = width // 2\n topleft = [\n int(torch.randint(0, int(self.distortion_scale_max * half_width) + 1, size=(1,)).item()),\n int(torch.randint(0, int(self.distortion_scale_max * half_height) + 1, size=(1,)).item()),\n ]\n topright = [\n int(torch.randint(width - int(self.distortion_scale_max * half_width) - 1, width, size=(1,)).item()),\n int(torch.randint(0, int(self.distortion_scale_max * half_height) + 1, size=(1,)).item()),\n ]\n botright = [\n int(torch.randint(width - int(self.distortion_scale_max * half_width) - 1, width, size=(1,)).item()),\n int(torch.randint(height - int(self.distortion_scale_max * half_height) - 1, height, size=(1,)).item()),\n ]\n botleft = [\n int(torch.randint(0, int(self.distortion_scale_max * half_width) + 1, size=(1,)).item()),\n int(torch.randint(height - int(self.distortion_scale_max * half_height) - 1, height, size=(1,)).item()),\n ]\n startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]\n endpoints = [topleft, topright, botright, botleft]\n\n image_mask_i = torchvision.transforms.functional.perspective(\n img=image_mask_i, startpoints=startpoints, endpoints=endpoints, interpolation=2, fill=None\n )\n\n image_mask_i = torchvision.transforms.functional.affine(\n img=image_mask_i,\n angle=phi_rotate,\n translate=[x_shift, y_shift],\n scale=im_scale,\n shear=[0, 0],\n interpolation=torchvision.transforms.InterpolationMode.NEAREST,\n fill=None,\n )\n\n image_mask_list.append(image_mask_i)\n\n padded_patch_i = padded_patch[i_sample]\n\n padded_patch_i = torchvision.transforms.functional.perspective(\n img=padded_patch_i, startpoints=startpoints, endpoints=endpoints, interpolation=2, fill=None\n )\n\n padded_patch_i = torchvision.transforms.functional.affine(\n img=padded_patch_i,\n angle=phi_rotate,\n translate=[x_shift, y_shift],\n scale=im_scale,\n shear=[0, 0],\n interpolation=torchvision.transforms.InterpolationMode.NEAREST,\n fill=None,\n )\n\n padded_patch_list.append(padded_patch_i)\n\n image_mask = torch.stack(image_mask_list, dim=0)\n padded_patch = torch.stack(padded_patch_list, dim=0)\n inverted_mask = (\n torch.from_numpy(np.ones(shape=image_mask.shape, dtype=np.float32)).to(self.estimator.device) - image_mask\n )\n\n patched_images = images * inverted_mask + padded_patch * image_mask\n\n if not self.estimator.channels_first:\n patched_images = torch.permute(patched_images, (0, 2, 3, 1))\n\n return patched_images\n\n def generate( # type: ignore\n self, x: np.ndarray, y: np.ndarray | list[dict[str, np.ndarray | \"torch.Tensor\"]] | None = None, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate an adversarial patch and return the patch and its mask in arrays.\n\n :param x: An array with the original input images of shape NCHW or input videos of shape NFCHW.\n :param y: True or target labels of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each\n input image. For untargeted attacks, if `y` is None the attack will attack the model predictions\n on `x`. The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :type mask: `np.ndarray`\n :return: An array with adversarial patch and an array of the patch mask.\n \"\"\"\n import torch\n\n shuffle = kwargs.get(\"shuffle\", True)\n mask = kwargs.get(\"mask\")\n if mask is not None:\n mask = mask.copy()\n mask = self._check_mask(mask=mask, x=x)\n\n if self.patch_location is not None and mask is not None:\n raise ValueError(\"Masks can only be used if the `patch_location` is `None`.\")\n\n if y is None and self.targeted:\n raise ValueError(\"The targeted version of AdversarialPatch attack requires provided target labels.\")\n\n if hasattr(self.estimator, \"nb_classes\"):\n\n y_array: np.ndarray\n\n if y is None: # pragma: no cover\n logger.info(\"Setting labels to estimator classification predictions.\")\n y_array = to_categorical(\n np.argmax(self.estimator.predict(x=x), axis=1), nb_classes=self.estimator.nb_classes\n )\n else:\n y_array = cast(np.ndarray, y)\n\n y = check_and_transform_label_format(labels=y_array, nb_classes=self.estimator.nb_classes)\n\n # check if logits or probabilities\n y_pred = self.estimator.predict(x=x[[0]])\n\n if is_probability(y_pred):\n self.use_logits = False\n else:\n self.use_logits = True\n else:\n if y is None: # pragma: no cover\n logger.info(\"Setting labels to estimator object detection predictions.\")\n y = self.estimator.predict(x=x)\n\n if isinstance(y, np.ndarray):\n x_tensor = torch.Tensor(x)\n y_tensor = torch.Tensor(y)\n\n if mask is None:\n dataset = torch.utils.data.TensorDataset(x_tensor, y_tensor)\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=self.batch_size,\n shuffle=shuffle,\n drop_last=False,\n )\n else:\n mask_tensor = torch.Tensor(mask)\n dataset = torch.utils.data.TensorDataset(x_tensor, y_tensor, mask_tensor)\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=self.batch_size,\n shuffle=shuffle,\n drop_last=False,\n )\n else:\n\n class ObjectDetectionDataset(torch.utils.data.Dataset):\n \"\"\"\n Object detection dataset in PyTorch.\n \"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __len__(self):\n return self.x.shape[0]\n\n def __getitem__(self, idx):\n img = torch.from_numpy(self.x[idx])\n\n target = {}\n target[\"boxes\"] = torch.from_numpy(self.y[idx][\"boxes\"])\n target[\"labels\"] = torch.from_numpy(self.y[idx][\"labels\"])\n target[\"scores\"] = torch.from_numpy(self.y[idx][\"scores\"])\n\n return img, target\n\n class ObjectDetectionDatasetMask(torch.utils.data.Dataset):\n \"\"\"\n Object detection dataset in PyTorch.\n \"\"\"\n\n def __init__(self, x, y, mask):\n self.x = x\n self.y = y\n self.mask = mask\n\n def __len__(self):\n return self.x.shape[0]\n\n def __getitem__(self, idx):\n img = torch.from_numpy(self.x[idx])\n\n target = {}\n target[\"boxes\"] = torch.from_numpy(self.y[idx][\"boxes\"])\n target[\"labels\"] = torch.from_numpy(self.y[idx][\"labels\"])\n target[\"scores\"] = torch.from_numpy(self.y[idx][\"scores\"])\n mask_i = torch.from_numpy(self.mask[idx])\n\n return img, target, mask_i\n\n dataset_object_detection: ObjectDetectionDataset | ObjectDetectionDatasetMask\n if mask is None:\n dataset_object_detection = ObjectDetectionDataset(x, y)\n else:\n dataset_object_detection = ObjectDetectionDatasetMask(x, y, mask)\n\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset_object_detection,\n batch_size=self.batch_size,\n shuffle=shuffle,\n drop_last=False,\n )\n\n for i_iter in trange(self.max_iter, desc=\"Adversarial Patch PyTorch\", disable=not self.verbose):\n if mask is None:\n for images, target in data_loader:\n images = images.to(self.estimator.device)\n if isinstance(target, torch.Tensor):\n target = target.to(self.estimator.device)\n else:\n targets = []\n for idx in range(target[\"boxes\"].shape[0]):\n targets.append(\n {\n \"boxes\": target[\"boxes\"][idx].to(self.estimator.device),\n \"labels\": target[\"labels\"][idx].to(self.estimator.device),\n \"scores\": target[\"scores\"][idx].to(self.estimator.device),\n }\n )\n target = targets\n _ = self._train_step(images=images, target=target, mask=None)\n else:\n for images, target, mask_i in data_loader:\n images = images.to(self.estimator.device)\n if isinstance(target, torch.Tensor):\n target = target.to(self.estimator.device)\n else:\n targets = []\n for idx in range(target[\"boxes\"].shape[0]):\n targets.append(\n {\n \"boxes\": target[\"boxes\"][idx].to(self.estimator.device),\n \"labels\": target[\"labels\"][idx].to(self.estimator.device),\n \"scores\": target[\"scores\"][idx].to(self.estimator.device),\n }\n )\n target = targets\n mask_i = mask_i.to(self.estimator.device)\n _ = self._train_step(images=images, target=target, mask=mask_i)\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n mask_tensor = torch.from_numpy(mask).to(self.estimator.device)\n x_patched = (\n self._random_overlay(\n images=torch.from_numpy(x).to(self.estimator.device), patch=self._patch, mask=mask_tensor\n )\n .detach()\n .cpu()\n .numpy()\n )\n\n self.summary_writer.update(\n batch_id=0,\n global_step=i_iter,\n grad=None,\n patch=self._patch,\n estimator=self.estimator,\n x=x_patched,\n y=y,\n targeted=self.targeted,\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return (\n self._patch.detach().cpu().numpy(),\n self._get_circular_patch_mask(nb_samples=1).cpu().numpy()[0],\n )\n\n def _check_mask(self, mask: np.ndarray | None, x: np.ndarray) -> np.ndarray | None:\n if mask is not None and ( # pragma: no cover\n (mask.dtype != bool)\n or not (mask.shape[0] == 1 or mask.shape[0] == x.shape[0])\n or not (mask.shape[1] == x.shape[self.i_h + 1] and mask.shape[2] == x.shape[self.i_w + 1])\n ):\n raise ValueError(\n \"The shape of `mask` has to be equal to the shape of a single samples (1, H, W) or the\"\n \"shape of `x` (N, H, W) without their channel dimensions.\"\n )\n\n if mask is not None and mask.shape[0] == 1:\n mask = np.repeat(mask, repeats=x.shape[0], axis=0)\n\n return mask\n\n def apply_patch(\n self,\n x: np.ndarray,\n scale: float,\n patch_external: np.ndarray | None = None,\n mask: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n A function to apply the learned adversarial patch to images or videos.\n\n :param x: Instances to apply randomly transformed patch.\n :param scale: Scale of the applied patch in relation to the estimator input shape.\n :param patch_external: External patch to apply to images `x`.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :return: The patched samples.\n \"\"\"\n import torch\n\n if mask is not None:\n mask = mask.copy()\n mask = self._check_mask(mask=mask, x=x)\n x_tensor = torch.Tensor(x).to(self.estimator.device)\n if mask is not None:\n mask_tensor = torch.Tensor(mask).to(self.estimator.device)\n else:\n mask_tensor = None\n if isinstance(patch_external, np.ndarray):\n patch_tensor = torch.Tensor(patch_external).to(self.estimator.device)\n else:\n patch_tensor = self._patch\n return (\n self._random_overlay(images=x_tensor, patch=patch_tensor, scale=scale, mask=mask_tensor)\n .detach()\n .cpu()\n .numpy()\n )\n\n def reset_patch(self, initial_patch_value: float | np.ndarray | None = None) -> None:\n \"\"\"\n Reset the adversarial patch.\n\n :param initial_patch_value: Patch value to use for resetting the patch.\n \"\"\"\n import torch\n\n if initial_patch_value is None:\n self._patch.data = torch.Tensor(self._initial_value).double()\n elif isinstance(initial_patch_value, float):\n initial_value = np.ones(self.patch_shape) * initial_patch_value\n self._patch.data = torch.Tensor(initial_value).double()\n elif self._patch.shape == initial_patch_value.shape:\n self._patch.data = torch.Tensor(initial_patch_value).double()\n else:\n raise ValueError(\"Unexpected value for initial_patch_value.\")\n\n @staticmethod\n def insert_transformed_patch(x: np.ndarray, patch: np.ndarray, image_coords: np.ndarray):\n \"\"\"\n Insert patch to image based on given or selected coordinates.\n\n :param x: The image to insert the patch.\n :param patch: The patch to be transformed and inserted.\n :param image_coords: The coordinates of the 4 corners of the transformed, inserted patch of shape\n [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] in pixel units going in clockwise direction, starting with upper\n left corner.\n :return: The input `x` with the patch inserted.\n \"\"\"\n return insert_transformed_patch(x, patch, image_coords)\n\n def _check_params(self) -> None:\n super()._check_params()\n\n if not isinstance(self.distortion_scale_max, (float, int)) or 1.0 <= self.distortion_scale_max < 0.0:\n raise ValueError(\"The maximum distortion scale has to be greater than or equal 0.0 or smaller than 1.0.\")\n\n if self.patch_location is not None and not (\n isinstance(self.patch_location, tuple)\n and len(self.patch_location) == 2\n and isinstance(self.patch_location[0], int)\n and self.patch_location[0] >= 0\n and isinstance(self.patch_location[1], int)\n and self.patch_location[1] >= 0\n ):\n raise ValueError(\n \"The patch location has to be either `None` or a tuple of two integers greater than or equal 0.\"\n )\n\n if self.patch_type not in [\"circle\", \"square\"]:\n raise ValueError(\"The patch type has to be either `circle` or `square`.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_patch/adversarial_patch_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the adversarial patch attack `AdversarialPatch`. This attack generates an adversarial patch that\ncan be printed into the physical world with a common printer. The patch can be used to fool image and video classifiers.\n\n| Paper link: https://arxiv.org/abs/1712.09665\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport math\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.adversarial_patch.utils import insert_transformed_patch\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format, is_probability, to_categorical\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialPatchTensorFlowV2(EvasionAttack):\n \"\"\"\n Implementation of the adversarial patch attack for square and rectangular images and videos in TensorFlow v2.\n\n | Paper link: https://arxiv.org/abs/1712.09665\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"rotation_max\",\n \"scale_min\",\n \"scale_max\",\n \"learning_rate\",\n \"max_iter\",\n \"batch_size\",\n \"patch_shape\",\n \"optimizer\",\n \"targeted\",\n \"summary_writer\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n rotation_max: float = 22.5,\n scale_min: float = 0.1,\n scale_max: float = 1.0,\n learning_rate: float = 5.0,\n max_iter: int = 500,\n batch_size: int = 16,\n patch_shape: tuple[int, int, int] | None = None,\n optimizer: str = \"Adam\",\n targeted: bool = True,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.AdversarialPatchTensorFlowV2`.\n\n :param classifier: A trained classifier.\n :param rotation_max: The maximum rotation applied to random patches. The value is expected to be in the\n range `[0, 180]`.\n :param scale_min: The minimum scaling applied to random patches. The value should be in the range `[0, 1]`,\n but less than `scale_max`.\n :param scale_max: The maximum scaling applied to random patches. The value should be in the range `[0, 1]`, but\n larger than `scale_min.`\n :param learning_rate: The learning rate of the optimization. For `optimizer=\"pgd\"` the learning rate gets\n multiplied with the sign of the loss gradients.\n :param max_iter: The number of optimization steps.\n :param batch_size: The size of the training batch.\n :param patch_shape: The shape of the adversarial patch as a tuple of shape HWC (width, height, nb_channels).\n :param optimizer: The optimization algorithm. Supported values: \"Adam\", and \"pgd\". \"pgd\" corresponds to\n projected gradient descent in L-Inf norm.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n import tensorflow as tf\n\n super().__init__(estimator=classifier, summary_writer=summary_writer)\n self.rotation_max = rotation_max\n self.scale_min = scale_min\n self.scale_max = scale_max\n self.learning_rate = learning_rate\n self.max_iter = max_iter\n self.batch_size = batch_size\n if patch_shape is None:\n self.patch_shape = self.estimator.input_shape\n else:\n self.patch_shape = patch_shape\n self.image_shape = classifier.input_shape\n self.targeted = targeted\n self.verbose = verbose\n self._check_params()\n\n if self.estimator.channels_first: # pragma: no cover\n raise ValueError(\"Color channel needs to be in last dimension.\")\n\n self.use_logits: bool | None = None\n\n self.i_h_patch = 0\n self.i_w_patch = 1\n\n self.nb_dims = len(self.image_shape)\n if self.nb_dims == 3:\n self.i_h = 0\n self.i_w = 1\n elif self.nb_dims == 4:\n self.i_h = 1\n self.i_w = 2\n\n if self.patch_shape[0] != self.patch_shape[1]: # pragma: no cover\n raise ValueError(\"Patch height and width need to be the same.\")\n\n if not ( # pragma: no cover\n self.estimator.postprocessing_defences is None or self.estimator.postprocessing_defences == []\n ):\n raise ValueError(\n \"Framework-specific implementation of Adversarial Patch attack does not yet support \"\n + \"postprocessing defences.\"\n )\n\n mean_value = (self.estimator.clip_values[1] - self.estimator.clip_values[0]) / 2.0 + self.estimator.clip_values[\n 0\n ]\n self._initial_value = np.ones(self.patch_shape) * mean_value\n self._patch = tf.Variable(\n initial_value=self._initial_value,\n shape=self.patch_shape,\n dtype=tf.float32,\n constraint=lambda x: tf.clip_by_value(x, self.estimator.clip_values[0], self.estimator.clip_values[1]),\n )\n\n self._optimizer_string = optimizer\n if self._optimizer_string == \"Adam\":\n self._optimizer = tf.keras.optimizers.Adam(\n learning_rate=self.learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name=\"Adam\"\n )\n\n def _train_step(\n self, images: \"tf.Tensor\", target: \"tf.Tensor\" | None = None, mask: \"tf.Tensor\" | None = None\n ) -> \"tf.Tensor\":\n import tensorflow as tf\n\n with tf.GradientTape() as tape:\n tape.watch(self._patch)\n loss = self._loss(images, target, mask)\n\n gradients = tape.gradient(loss, [self._patch])\n\n if (not self.targeted and self._optimizer_string != \"pgd\") or self.targeted and self._optimizer_string == \"pgd\":\n gradients = [-g for g in gradients]\n\n if self._optimizer_string == \"pgd\":\n gradients = tf.sign(gradients) * self.learning_rate\n\n self._patch = self._patch + tf.squeeze(gradients)\n\n self._patch = tf.clip_by_value(\n self._patch, clip_value_min=self.estimator.clip_values[0], clip_value_max=self.estimator.clip_values[1]\n )\n\n else:\n self._optimizer.apply_gradients(zip(gradients, [self._patch]))\n\n return loss\n\n def _predictions(self, images: \"tf.Tensor\", mask: \"tf.Tensor\" | None) -> \"tf.Tensor\":\n import tensorflow as tf\n\n patched_input = self._random_overlay(images, self._patch, mask=mask)\n\n patched_input = tf.clip_by_value(\n patched_input,\n clip_value_min=self.estimator.clip_values[0],\n clip_value_max=self.estimator.clip_values[1],\n )\n\n predictions = self.estimator._predict_framework(patched_input)\n\n return predictions\n\n def _loss(self, images: \"tf.Tensor\", target: \"tf.Tensor\", mask: \"tf.Tensor\" | None) -> \"tf.Tensor\":\n import tensorflow as tf\n\n predictions = self._predictions(images, mask)\n\n self._loss_per_example = tf.keras.losses.categorical_crossentropy(\n y_true=target, y_pred=predictions, from_logits=self.use_logits, label_smoothing=0\n )\n\n loss = tf.reduce_mean(self._loss_per_example)\n\n return loss\n\n def _get_circular_patch_mask(self, nb_samples: int, sharpness: int = 40) -> \"tf.Tensor\":\n \"\"\"\n Return a circular patch mask.\n \"\"\"\n import tensorflow as tf\n\n diameter = np.minimum(self.patch_shape[self.i_h_patch], self.patch_shape[self.i_w_patch])\n\n x = np.linspace(-1, 1, diameter)\n y = np.linspace(-1, 1, diameter)\n x_grid, y_grid = np.meshgrid(x, y, sparse=True)\n z_grid = (x_grid**2 + y_grid**2) ** sharpness\n\n image_mask = 1 - np.clip(z_grid, -1, 1)\n image_mask = np.expand_dims(image_mask, axis=2)\n image_mask = np.broadcast_to(image_mask, self.patch_shape)\n image_mask = tf.stack([image_mask] * nb_samples)\n return image_mask\n\n def _random_overlay(\n self,\n images: np.ndarray | \"tf.Tensor\",\n patch: np.ndarray | \"tf.Variable\",\n scale: float | None = None,\n mask: np.ndarray | \"tf.Tensor\" | None = None,\n ) -> \"tf.Tensor\":\n import tensorflow as tf\n\n nb_samples = images.shape[0]\n\n image_mask = self._get_circular_patch_mask(nb_samples=nb_samples)\n image_mask = tf.cast(image_mask, images.dtype)\n\n smallest_image_edge = np.minimum(self.image_shape[self.i_h], self.image_shape[self.i_w])\n\n image_mask = tf.image.resize(\n image_mask,\n size=(smallest_image_edge, smallest_image_edge),\n method=tf.image.ResizeMethod.BILINEAR,\n preserve_aspect_ratio=False,\n antialias=False,\n name=None,\n )\n\n pad_h_before = int((self.image_shape[self.i_h] - image_mask.shape.as_list()[self.i_h_patch + 1]) / 2)\n pad_h_after = int(self.image_shape[self.i_h] - pad_h_before - image_mask.shape[self.i_h_patch + 1])\n\n pad_w_before = int((self.image_shape[self.i_w] - image_mask.shape.as_list()[self.i_w_patch + 1]) / 2)\n pad_w_after = int(self.image_shape[self.i_w] - pad_w_before - image_mask.shape[self.i_w_patch + 1])\n\n image_mask = tf.pad(\n image_mask,\n paddings=tf.constant([[0, 0], [pad_h_before, pad_h_after], [pad_w_before, pad_w_after], [0, 0]]),\n mode=\"CONSTANT\",\n constant_values=0,\n name=None,\n )\n\n image_mask = tf.cast(image_mask, images.dtype)\n\n patch = tf.cast(patch, images.dtype)\n padded_patch = tf.stack([patch] * nb_samples)\n\n padded_patch = tf.image.resize(\n padded_patch,\n size=(smallest_image_edge, smallest_image_edge),\n method=tf.image.ResizeMethod.BILINEAR,\n preserve_aspect_ratio=False,\n antialias=False,\n name=None,\n )\n\n padded_patch = tf.pad(\n padded_patch,\n paddings=tf.constant([[0, 0], [pad_h_before, pad_h_after], [pad_w_before, pad_w_after], [0, 0]]),\n mode=\"CONSTANT\",\n constant_values=0,\n name=None,\n )\n\n padded_patch = tf.cast(padded_patch, images.dtype)\n\n transform_vectors = []\n translation_vectors = []\n\n for i_sample in range(nb_samples):\n if scale is None:\n im_scale = np.random.uniform(low=self.scale_min, high=self.scale_max)\n else:\n im_scale = scale\n\n if mask is None:\n padding_after_scaling_h = (\n self.image_shape[self.i_h] - im_scale * padded_patch.shape.as_list()[self.i_h + 1]\n ) / 2.0\n padding_after_scaling_w = (\n self.image_shape[self.i_w] - im_scale * padded_patch.shape.as_list()[self.i_w + 1]\n ) / 2.0\n x_shift = np.random.uniform(-padding_after_scaling_w, padding_after_scaling_w)\n y_shift = np.random.uniform(-padding_after_scaling_h, padding_after_scaling_h)\n else:\n mask_2d = mask[i_sample, :, :]\n\n edge_x_0 = int(im_scale * padded_patch.shape[self.i_w + 1]) // 2\n edge_x_1 = int(im_scale * padded_patch.shape[self.i_w + 1]) - edge_x_0\n edge_y_0 = int(im_scale * padded_patch.shape[self.i_h + 1]) // 2\n edge_y_1 = int(im_scale * padded_patch.shape[self.i_h + 1]) - edge_y_0\n\n mask_2d[0:edge_x_0, :] = False\n if edge_x_1 > 0:\n mask_2d[-edge_x_1:, :] = False\n mask_2d[:, 0:edge_y_0] = False\n if edge_y_1 > 0:\n mask_2d[:, -edge_y_1:] = False\n\n num_pos = np.argwhere(mask_2d).shape[0]\n pos_id = np.random.choice(num_pos, size=1)\n pos = np.argwhere(mask_2d)[pos_id[0]]\n x_shift = pos[1] - self.image_shape[self.i_w] // 2\n y_shift = pos[0] - self.image_shape[self.i_h] // 2\n\n phi_rotate = float(np.random.uniform(-self.rotation_max, self.rotation_max)) / 180.0 * math.pi\n\n # Rotation\n rotation_matrix = np.array(\n [\n [math.cos(-phi_rotate), -math.sin(-phi_rotate)],\n [math.sin(-phi_rotate), math.cos(-phi_rotate)],\n ]\n )\n\n # Scale\n xform_matrix = rotation_matrix * (1.0 / im_scale)\n a_0, a_1 = xform_matrix[0]\n b_0, b_1 = xform_matrix[1]\n\n x_origin = float(self.image_shape[self.i_w]) / 2\n y_origin = float(self.image_shape[self.i_h]) / 2\n\n x_origin_shifted, y_origin_shifted = np.matmul(xform_matrix, np.array([x_origin, y_origin]))\n\n x_origin_delta = x_origin - x_origin_shifted\n y_origin_delta = y_origin - y_origin_shifted\n\n # Run translation in a second step to position patch exactly inside the mask\n transform_vectors.append([a_0, a_1, x_origin_delta, b_0, b_1, y_origin_delta, 0, 0])\n translation_vectors.append([1, 0, -x_shift, 0, 1, -y_shift, 0, 0])\n\n image_mask = tf.raw_ops.ImageProjectiveTransformV3(\n images=image_mask,\n transforms=transform_vectors,\n interpolation=\"BILINEAR\",\n output_shape=tf.shape(image_mask)[1:3], # Preserve original shape\n fill_mode=\"REFLECT\", # Optional: can change to \"CONSTANT\", \"NEAREST\", etc.\n fill_value=0.0,\n )\n padded_patch = tf.raw_ops.ImageProjectiveTransformV3(\n images=padded_patch,\n transforms=transform_vectors,\n interpolation=\"BILINEAR\",\n output_shape=tf.shape(image_mask)[1:3], # Preserve original shape\n fill_mode=\"REFLECT\", # Optional: can change to \"CONSTANT\", \"NEAREST\", etc.\n fill_value=0.0,\n )\n\n image_mask = tf.raw_ops.ImageProjectiveTransformV3(\n images=image_mask,\n transforms=translation_vectors,\n interpolation=\"BILINEAR\",\n output_shape=tf.shape(image_mask)[1:3], # Preserve original shape\n fill_mode=\"REFLECT\", # Optional: can change to \"CONSTANT\", \"NEAREST\", etc.\n fill_value=0.0,\n )\n padded_patch = tf.raw_ops.ImageProjectiveTransformV3(\n images=padded_patch,\n transforms=translation_vectors,\n interpolation=\"BILINEAR\",\n output_shape=tf.shape(image_mask)[1:3], # Preserve original shape\n fill_mode=\"REFLECT\", # Optional: can change to \"CONSTANT\", \"NEAREST\", etc.\n fill_value=0.0,\n )\n\n if self.nb_dims == 4:\n image_mask = tf.stack([image_mask] * images.shape[1], axis=1)\n image_mask = tf.cast(image_mask, images.dtype)\n\n padded_patch = tf.stack([padded_patch] * images.shape[1], axis=1)\n padded_patch = tf.cast(padded_patch, images.dtype)\n\n inverted_mask = tf.constant(1, dtype=image_mask.dtype) - image_mask\n\n return images * inverted_mask + padded_patch * image_mask\n\n def generate( # type: ignore\n self, x: np.ndarray, y: np.ndarray | None = None, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate an adversarial patch and return the patch and its mask in arrays.\n\n :param x: An array with the original input images of shape NHWC or input videos of shape NFHWC.\n :param y: An array with the original true labels.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :type mask: `np.ndarray`\n :param reset_patch: If `True` reset patch to initial values of mean of minimal and maximal clip value, else if\n `False` (default) restart from previous patch values created by previous call to `generate`\n or mean of minimal and maximal clip value if first call to `generate`.\n :type reset_patch: bool\n :return: An array with adversarial patch and an array of the patch mask.\n \"\"\"\n import tensorflow as tf\n\n shuffle = kwargs.get(\"shuffle\", True)\n mask = kwargs.get(\"mask\")\n if mask is not None:\n mask = mask.copy()\n mask = self._check_mask(mask=mask, x=x)\n\n if y is None: # pragma: no cover\n logger.info(\"Setting labels to estimator predictions and running untargeted attack because `y=None`.\")\n y = to_categorical(np.argmax(self.estimator.predict(x=x), axis=1), nb_classes=self.estimator.nb_classes)\n\n if kwargs.get(\"reset_patch\"):\n self.reset_patch(initial_patch_value=self._initial_value)\n\n y = check_and_transform_label_format(labels=y, nb_classes=self.estimator.nb_classes)\n\n # check if logits or probabilities\n y_pred = self.estimator.predict(x=x[[0]])\n\n if is_probability(y_pred):\n self.use_logits = False\n else:\n self.use_logits = True\n\n if mask is None:\n if shuffle:\n dataset = tf.data.Dataset.from_tensor_slices((x, y)).shuffle(10000).batch(self.batch_size)\n else:\n dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(self.batch_size)\n else:\n if shuffle:\n dataset = tf.data.Dataset.from_tensor_slices((x, y, mask)).shuffle(10000).batch(self.batch_size)\n else:\n dataset = tf.data.Dataset.from_tensor_slices((x, y, mask)).batch(self.batch_size)\n\n for i_iter in trange(self.max_iter, desc=\"Adversarial Patch TensorFlow v2\", disable=not self.verbose):\n if mask is None:\n counter = 0\n for images, target in dataset:\n counter += 1\n _ = self._train_step(images=images, target=target, mask=None)\n else:\n for images, target, mask_i in dataset:\n _ = self._train_step(images=images, target=target, mask=mask_i)\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n x_patched = self._random_overlay(images=x, patch=self._patch, mask=mask)\n\n self.summary_writer.update(\n batch_id=0,\n global_step=i_iter,\n grad=None,\n patch=self._patch.numpy().transpose((2, 0, 1)),\n estimator=self.estimator,\n x=x_patched,\n y=y,\n targeted=self.targeted,\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return (\n self._patch.numpy(),\n self._get_circular_patch_mask(nb_samples=1).numpy()[0],\n )\n\n def _check_mask(self, mask: np.ndarray | None, x: np.ndarray) -> np.ndarray | None:\n if mask is not None and ( # pragma: no cover\n (mask.dtype != bool)\n or not (mask.shape[0] == 1 or mask.shape[0] == x.shape[0])\n or not (mask.shape[1] == x.shape[self.i_h + 1] and mask.shape[2] == x.shape[self.i_w + 1])\n ):\n raise ValueError(\n \"The shape of `mask` has to be equal to the shape of a single samples (1, H, W) or the\"\n \"shape of `x` (N, H, W) without their channel dimensions.\"\n )\n\n if mask is not None and mask.shape[0] == 1:\n mask = np.repeat(mask, repeats=x.shape[0], axis=0)\n\n return mask\n\n def apply_patch(\n self,\n x: np.ndarray,\n scale: float,\n patch_external: np.ndarray | None = None,\n mask: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n A function to apply the learned adversarial patch to images or videos.\n\n :param x: Instances to apply randomly transformed patch.\n :param scale: Scale of the applied patch in relation to the classifier input shape.\n :param patch_external: External patch to apply to images `x`.\n :param mask: A boolean array of shape equal to the shape of a single samples (1, H, W) or the shape of `x`\n (N, H, W) without their channel dimensions. Any features for which the mask is True can be the\n center location of the patch during sampling.\n :return: The patched samples.\n \"\"\"\n if mask is not None:\n mask = mask.copy()\n mask = self._check_mask(mask=mask, x=x)\n patch = patch_external if patch_external is not None else self._patch\n return self._random_overlay(images=x, patch=patch, scale=scale, mask=mask).numpy()\n\n def reset_patch(self, initial_patch_value: float | np.ndarray | None = None) -> None:\n \"\"\"\n Reset the adversarial patch.\n\n :param initial_patch_value: Patch value to use for resetting the patch.\n \"\"\"\n if initial_patch_value is None:\n self._patch.assign(self._initial_value)\n elif isinstance(initial_patch_value, float):\n initial_value = np.ones(self.patch_shape) * initial_patch_value\n self._patch.assign(initial_value)\n elif self._patch.shape == initial_patch_value.shape:\n self._patch.assign(initial_patch_value)\n else: # pragma: no cover\n raise ValueError(\"Unexpected value for initial_patch_value.\")\n\n @staticmethod\n def insert_transformed_patch(x: np.ndarray, patch: np.ndarray, image_coords: np.ndarray):\n \"\"\"\n Insert patch to image based on given or selected coordinates.\n\n :param x: The image to insert the patch.\n :param patch: The patch to be transformed and inserted.\n :param image_coords: The coordinates of the 4 corners of the transformed, inserted patch of shape\n [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] in pixel units going in clockwise direction, starting with upper\n left corner.\n :return: The input `x` with the patch inserted.\n \"\"\"\n return insert_transformed_patch(x, patch, image_coords)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_patch/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements utility functions for adversarial patch attacks.\n\"\"\"\nimport numpy as np\n\n\ndef insert_transformed_patch(x: np.ndarray, patch: np.ndarray, image_coords: np.ndarray):\n \"\"\"\n Insert patch to image based on given or selected coordinates.\n\n :param x: A single image of shape HWC to insert the patch.\n :param patch: The patch to be transformed and inserted.\n :param image_coords: The coordinates of the 4 corners of the transformed, inserted patch of shape\n [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] in pixel units going in clockwise direction, starting with upper\n left corner.\n :return: The input `x` with the patch inserted.\n \"\"\"\n import cv2\n\n scaling = False\n\n if np.max(x) <= 1.0:\n scaling = True\n x = (x * 255).astype(np.uint8)\n patch = (patch * 255).astype(np.uint8)\n\n rows = patch.shape[0]\n cols = patch.shape[1]\n\n if image_coords.shape[0] == 4:\n patch_coords = np.array([[0, 0], [cols - 1, 0], [cols - 1, rows - 1], [0, rows - 1]])\n else:\n patch_coords = np.array(\n [\n [0, 0],\n [cols - 1, 0],\n [cols - 1, (rows - 1) // 2],\n [cols - 1, rows - 1],\n [0, rows - 1],\n [0, (rows - 1) // 2],\n ]\n )\n\n # calculate homography\n height, _ = cv2.findHomography(patch_coords, image_coords)\n\n # warp patch to destination coordinates\n x_out = cv2.warpPerspective(patch, height, (x.shape[1], x.shape[0]), cv2.INTER_CUBIC) # type: ignore\n\n # mask to aid with insertion\n mask = np.ones(patch.shape)\n mask_out = cv2.warpPerspective(mask, height, (x.shape[1], x.shape[0]), cv2.INTER_CUBIC) # type: ignore\n\n # save image before adding shadows\n x_neg_patch = np.copy(x)\n x_neg_patch[mask_out != 0] = 0 # negative of the patch space\n\n if x_neg_patch.shape[2] == 1:\n x_out = np.expand_dims(x_out, axis=2)\n\n x_out = x_neg_patch.astype(\"float32\") + x_out.astype(\"float32\")\n\n if scaling:\n x_out = x_out / 255\n\n return x_out\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/adversarial_texture/adversarial_texture_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nImplementation of the adversarial texture attack on object trackers in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1904.11042\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.object_tracking.object_tracker import ObjectTrackerMixin\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialTexturePyTorch(EvasionAttack):\n \"\"\"\n Implementation of the adversarial texture attack on object trackers in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1904.11042\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"patch_height\",\n \"patch_width\",\n \"xmin\",\n \"ymin\",\n \"step_size\",\n \"max_iter\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (ObjectTrackerMixin, LossGradientsMixin, BaseEstimator)\n\n def __init__(\n self,\n estimator,\n patch_height: int,\n patch_width: int,\n x_min: int = 0,\n y_min: int = 0,\n step_size: float = 1.0 / 255.0,\n max_iter: int = 500,\n batch_size: int = 16,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.AdversarialTexturePyTorch`.\n\n :param estimator: A trained estimator.\n :param patch_height: Height of patch.\n :param patch_width: Width of patch.\n :param x_min: Vertical position of patch, top-left corner.\n :param y_min: Horizontal position of patch, top-left corner.\n :param step_size: The step size.\n :param max_iter: The number of optimization steps.\n :param batch_size: The size of the training batch.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n import torch\n\n super().__init__(estimator=estimator, summary_writer=summary_writer)\n self.patch_height = patch_height\n self.patch_width = patch_width\n self.x_min = x_min\n self.y_min = y_min\n self.step_size = step_size\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n self._batch_id = 0\n self._i_max_iter = 0\n\n self.patch_shape = (self.patch_height, self.patch_width, 3)\n\n if self.estimator.channels_first:\n raise ValueError(\"Input shape has to be either NHWC or NFHWC.\")\n\n self.i_h_patch = 0\n self.i_w_patch = 1\n\n self.i_h = 1\n self.i_w = 2\n\n if not (self.estimator.postprocessing_defences is None or self.estimator.postprocessing_defences == []):\n raise ValueError(\n \"Framework-specific implementation of Adversarial Patch attack does not yet support \"\n + \"postprocessing defences.\"\n )\n\n mean_value = (self.estimator.clip_values[1] - self.estimator.clip_values[0]) / 2.0 + self.estimator.clip_values[\n 0\n ]\n self._initial_value = np.ones(self.patch_shape) * mean_value\n self._patch = torch.tensor(self._initial_value, requires_grad=True, device=self.estimator.device)\n\n def _train_step(\n self,\n videos: \"torch.Tensor\",\n target: list[dict[str, \"torch.Tensor\"]],\n y_init: \"torch.Tensor\",\n foreground: \"torch.Tensor\" | None,\n patch_points: np.ndarray | None,\n ) -> \"torch.Tensor\":\n \"\"\"\n Apply a training step to the batch based on a mini-batch.\n\n :param videos: Video samples.\n :param target: Target labels/boxes.\n :param y_init: Initial labels/boxes.\n :param foreground: Foreground mask.\n :param patch_points: Array of shape (nb_frames, 4, 2) containing four pairs of integers (height, width)\n corresponding to the coordinates of the four corners top-left, top-right, bottom-right,\n bottom-left of the transformed image in the coordinate-system of the original image.\n :return: Loss.\n \"\"\"\n import torch\n\n self.estimator.model.zero_grad()\n loss = self._loss(videos, target, y_init, foreground, patch_points)\n loss.backward(retain_graph=True)\n\n if self._patch.grad is not None:\n gradients = self._patch.grad.sign() * self.step_size\n else:\n raise ValueError(\"Gradient term in PyTorch model is `None`.\")\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n self.summary_writer.update(\n batch_id=self._batch_id,\n global_step=self._i_max_iter,\n grad=np.expand_dims(self._patch.grad.detach().cpu().numpy(), axis=0),\n patch=None,\n estimator=None,\n x=None,\n y=None,\n )\n\n self._patch.grad = torch.zeros(\n self._patch.grad.shape, device=self._patch.grad.device, dtype=self._patch.grad.dtype\n )\n\n with torch.no_grad():\n self._patch[:] = torch.clamp(\n self._patch + gradients, min=self.estimator.clip_values[0], max=self.estimator.clip_values[1]\n )\n\n return loss\n\n def _predictions(\n self,\n videos: \"torch.Tensor\",\n y_init: \"torch.Tensor\",\n foreground: \"torch.Tensor\" | None,\n patch_points: np.ndarray | None,\n ) -> list[dict[str, \"torch.Tensor\"]]:\n \"\"\"\n Predict object tracking estimator on patched videos.\n\n :param videos: Video samples.\n :param y_init: Initial labels/boxes.\n :param foreground: Foreground mask.\n :param patch_points: Array of shape (nb_frames, 4, 2) containing four pairs of integers (height, width)\n corresponding to the coordinates of the four corners top-left, top-right, bottom-right,\n bottom-left of the transformed image in the coordinate-system of the original image.\n :return: Predicted labels/boxes.\n \"\"\"\n import torch\n\n patched_input = self._apply_texture(videos, self._patch, foreground=foreground, patch_points=patch_points)\n patched_input = torch.clamp(\n patched_input,\n min=self.estimator.clip_values[0],\n max=self.estimator.clip_values[1],\n )\n\n predictions = self.estimator.predict(patched_input, y_init=y_init)\n\n return predictions\n\n def _loss(\n self,\n videos: \"torch.Tensor\",\n target: list[dict[str, \"torch.Tensor\"]],\n y_init: \"torch.Tensor\",\n foreground: \"torch.Tensor\" | None,\n patch_points: np.ndarray | None,\n ) -> \"torch.Tensor\":\n \"\"\"\n Calculate L1-loss.\n\n :param videos: Video samples.\n :param target: Target labels/boxes.\n :param y_init: Initial labels/boxes.\n :param foreground: Foreground mask.\n :param patch_points: Array of shape (nb_frames, 4, 2) containing four pairs of integers (height, width)\n corresponding to the coordinates of the four corners top-left, top-right, bottom-right,\n bottom-left of the transformed image in the coordinate-system of the original image.\n :return: Loss.\n \"\"\"\n import torch\n\n y_pred = self._predictions(videos, y_init, foreground, patch_points)\n loss = torch.nn.L1Loss(reduction=\"sum\")(y_pred[0][\"boxes\"].float(), target[0][\"boxes\"].float())\n for i in range(1, len(y_pred)):\n loss = loss + torch.nn.L1Loss(reduction=\"sum\")(y_pred[i][\"boxes\"].float(), target[i][\"boxes\"].float())\n\n return loss\n\n def _get_patch_mask(self, nb_samples: int) -> \"torch.Tensor\":\n \"\"\"\n Create patch mask.\n\n :param nb_samples: Number of samples.\n :return: Patch mask.\n \"\"\"\n import torch\n\n image_mask_np = np.ones((self.patch_height, self.patch_width))\n\n image_mask_np = np.expand_dims(image_mask_np, axis=2)\n image_mask_np = np.broadcast_to(image_mask_np, self.patch_shape)\n image_mask = torch.Tensor(np.array(image_mask_np)).to(self.estimator.device)\n image_mask = torch.stack([image_mask] * nb_samples, dim=0)\n return image_mask\n\n def _apply_texture(\n self,\n videos: \"torch.Tensor\",\n patch: \"torch.Tensor\",\n foreground: \"torch.Tensor\" | None,\n patch_points: np.ndarray | None,\n ) -> \"torch.Tensor\":\n \"\"\"\n Apply texture over background and overlay foreground.\n\n :param videos: Video samples.\n :param patch: Patch to apply.\n :param foreground: Foreground mask.\n :param patch_points: Array of shape (nb_frames, 4, 2) containing four pairs of integers (height, width)\n corresponding to the coordinates of the four corners top-left, top-right, bottom-right,\n bottom-left of the transformed image in the coordinate-system of the original image.\n :return: Patched videos.\n \"\"\"\n import torch\n import torchvision\n\n nb_samples = videos.shape[0]\n nb_frames = videos.shape[1]\n frame_height = videos.shape[2]\n frame_width = videos.shape[3]\n\n image_mask = self._get_patch_mask(nb_samples=nb_samples)\n image_mask = image_mask.float()\n\n patch = patch.float()\n padded_patch = torch.stack([patch] * nb_samples)\n\n if patch_points is None:\n pad_h_before = self.x_min\n pad_h_after = int(videos.shape[self.i_h + 1] - pad_h_before - image_mask.shape[self.i_h_patch + 1])\n\n pad_w_before = self.y_min\n pad_w_after = int(videos.shape[self.i_w + 1] - pad_w_before - image_mask.shape[self.i_w_patch + 1])\n\n image_mask = image_mask.permute(0, 3, 1, 2)\n\n image_mask = torchvision.transforms.functional.pad(\n img=image_mask,\n padding=[pad_w_before, pad_h_before, pad_w_after, pad_h_after],\n fill=0,\n padding_mode=\"constant\",\n )\n\n image_mask = image_mask.permute(0, 2, 3, 1)\n\n image_mask = torch.unsqueeze(image_mask, dim=1)\n image_mask = torch.repeat_interleave(image_mask, dim=1, repeats=nb_frames)\n image_mask = image_mask.float()\n\n padded_patch = padded_patch.permute(0, 3, 1, 2)\n\n padded_patch = torchvision.transforms.functional.pad(\n img=padded_patch,\n padding=[pad_w_before, pad_h_before, pad_w_after, pad_h_after],\n fill=0,\n padding_mode=\"constant\",\n )\n\n padded_patch = padded_patch.permute(0, 2, 3, 1)\n\n padded_patch = torch.unsqueeze(padded_patch, dim=1)\n padded_patch = torch.repeat_interleave(padded_patch, dim=1, repeats=nb_frames)\n\n padded_patch = padded_patch.float()\n\n else:\n\n startpoints = [[0, 0], [frame_width, 0], [frame_width, frame_height], [0, frame_height]]\n endpoints = np.zeros_like(patch_points)\n endpoints[:, :, 0] = patch_points[:, :, 1]\n endpoints[:, :, 1] = patch_points[:, :, 0]\n\n image_mask = image_mask.permute(0, 3, 1, 2)\n\n image_mask = torchvision.transforms.functional.resize(\n img=image_mask,\n size=[int(videos.shape[2]), int(videos.shape[3])],\n interpolation=torchvision.transforms.InterpolationMode.BILINEAR,\n )\n\n image_mask_list = []\n\n for i_frame in range(nb_frames):\n\n image_mask_i = torchvision.transforms.functional.perspective(\n img=image_mask,\n startpoints=startpoints,\n endpoints=endpoints[i_frame],\n interpolation=torchvision.transforms.InterpolationMode.BILINEAR,\n fill=0,\n )\n\n image_mask_i = image_mask_i.permute(0, 2, 3, 1)\n\n image_mask_list.append(image_mask_i)\n\n image_mask = torch.stack(image_mask_list, dim=1)\n image_mask = image_mask.float()\n\n padded_patch = padded_patch.permute(0, 3, 1, 2)\n\n padded_patch = torchvision.transforms.functional.resize(\n img=padded_patch,\n size=[int(videos.shape[2]), int(videos.shape[3])],\n interpolation=torchvision.transforms.InterpolationMode.BILINEAR,\n )\n\n padded_patch_list = []\n\n for i_frame in range(nb_frames):\n padded_patch_i = torchvision.transforms.functional.perspective(\n img=padded_patch,\n startpoints=startpoints,\n endpoints=endpoints[i_frame],\n interpolation=torchvision.transforms.InterpolationMode.BILINEAR,\n fill=0,\n )\n\n padded_patch_i = padded_patch_i.permute(0, 2, 3, 1)\n\n padded_patch_list.append(padded_patch_i)\n\n padded_patch = torch.stack(padded_patch_list, dim=1)\n padded_patch = padded_patch.float()\n\n inverted_mask = (\n torch.from_numpy(np.ones(shape=image_mask.shape, dtype=np.float32)).to(self.estimator.device) - image_mask\n )\n\n if foreground is not None:\n combined = (\n videos * inverted_mask\n + padded_patch * image_mask\n - padded_patch * ~foreground.bool()\n + videos * ~foreground.bool() * image_mask\n )\n else:\n combined = videos * inverted_mask + padded_patch * image_mask\n\n return combined\n\n def generate( # type: ignore # pylint: disable=signature-differs\n self, x: np.ndarray, y: list[dict[str, np.ndarray]], **kwargs\n ) -> np.ndarray:\n \"\"\"\n Generate an adversarial patch and return the patch and its mask in arrays.\n\n :param x: Input videos of shape NFHWC.\n :param y: True labels of format `list[dict[str, np.ndarray]]`, one dictionary for each input image. The keys of\n the dictionary are:\n\n - boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n\n :Keyword Arguments:\n * *shuffle* (``np.ndarray``) --\n Shuffle order of samples, labels, initial boxes, and foregrounds for texture generation.\n * *y_init* (``np.ndarray``) --\n Initial boxes around object to be tracked of shape (nb_samples, 4) with second dimension representing\n [x1, y1, x2, y2] with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n * *foreground* (``np.ndarray``) --\n Foreground masks of shape NFHWC of boolean values with False/0.0 representing foreground, preventing\n updates to the texture, and True/1.0 for background, allowing updates to the texture.\n * *patch_points* (``np.ndarray``) --\n Array of shape (nb_frames, 4, 2) containing four pairs of integers (height, width) corresponding to the\n four corners top-left, top-right, bottom-right, bottom-left of the transformed image in the coordinates\n of the original image.\n\n :return: An array with images patched with adversarial texture.\n \"\"\"\n import torch\n\n shuffle = kwargs.get(\"shuffle\", True)\n y_init = kwargs.get(\"y_init\")\n foreground = kwargs.get(\"foreground\")\n if foreground is None:\n foreground = np.ones_like(x)\n patch_points = kwargs.get(\"patch_points\")\n\n class TrackingDataset(torch.utils.data.Dataset):\n \"\"\"\n Object tracking dataset in PyTorch.\n \"\"\"\n\n def __init__(self, x, y, y_init, foreground):\n self.x = x\n self.y = y\n self.y_init = y_init\n self.foreground = foreground\n\n def __len__(self):\n return self.x.shape[0]\n\n def __getitem__(self, idx):\n img = self.x[idx]\n\n target = {}\n target[\"boxes\"] = torch.from_numpy(y[idx][\"boxes\"])\n\n y_init_i = self.y_init[idx]\n foreground_i = self.foreground[idx]\n\n return img, target, y_init_i, foreground_i\n\n dataset = TrackingDataset(x, y, y_init, foreground)\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=self.batch_size,\n shuffle=shuffle,\n drop_last=False,\n )\n\n for i_max_iter in trange(self.max_iter, desc=\"Adversarial Texture PyTorch\", disable=not self.verbose):\n\n self._i_max_iter = i_max_iter\n self._batch_id = 0\n\n for videos_i, target_i, y_init_i, foreground_i in data_loader:\n self._batch_id += 1\n videos_i = videos_i.to(self.estimator.device)\n y_init_i = y_init_i.to(self.estimator.device)\n foreground_i = foreground_i.to(self.estimator.device)\n target_i_list = []\n for i_t in range(videos_i.shape[0]):\n target_i_list.append({\"boxes\": target_i[\"boxes\"][i_t].to(self.estimator.device)})\n\n _ = self._train_step(\n videos=videos_i,\n target=target_i_list,\n y_init=y_init_i,\n foreground=foreground_i,\n patch_points=patch_points,\n )\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n self.summary_writer.update(\n batch_id=self._batch_id,\n global_step=self._i_max_iter,\n grad=None,\n patch=self._patch.detach().cpu().numpy(),\n estimator=self.estimator,\n x=videos_i.detach().cpu().numpy(),\n y=target_i_list,\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return self.apply_patch(x=x, foreground=foreground, patch_points=patch_points)\n\n def apply_patch(\n self,\n x: np.ndarray,\n patch_external: np.ndarray | None = None,\n foreground: np.ndarray | None = None,\n patch_points: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n A function to apply the learned adversarial texture to videos.\n\n :param x: Videos of shape NFHWC to apply adversarial texture.\n :param patch_external: External patch to apply to videos `x`.\n :param foreground: Foreground masks of shape NFHWC of boolean values with False/0.0 representing foreground,\n preventing updates to the texture, and True/1.0 for background, allowing updates to the\n texture.\n :param patch_points: Array of shape (nb_frames, 4, 2) containing four pairs of integers (height, width)\n corresponding to the coordinates of the four corners top-left, top-right, bottom-right,\n bottom-left of the transformed image in the coordinate-system of the original image.\n :return: The videos with adversarial textures.\n \"\"\"\n import torch\n\n patch_tensor = (\n torch.Tensor(patch_external).to(self.estimator.device) if patch_external is not None else self._patch\n )\n x_tensor = torch.Tensor(x).to(self.estimator.device)\n if foreground is None:\n foreground_tensor = None\n else:\n foreground_tensor = torch.Tensor(foreground).to(self.estimator.device)\n\n return (\n self._apply_texture(\n videos=x_tensor, patch=patch_tensor, foreground=foreground_tensor, patch_points=patch_points\n )\n .detach()\n .cpu()\n .numpy()\n )\n\n def reset_patch(self, initial_patch_value: float | np.ndarray | None = None) -> None:\n \"\"\"\n Reset the adversarial texture.\n\n :param initial_patch_value: Patch value to use for resetting the patch.\n \"\"\"\n import torch\n\n if initial_patch_value is None:\n self._patch.data = torch.Tensor(self._initial_value).double()\n elif isinstance(initial_patch_value, float):\n initial_value = np.ones(self.patch_shape) * initial_patch_value\n self._patch.data = torch.Tensor(initial_value).double()\n elif self._patch.shape == initial_patch_value.shape:\n self._patch.data = torch.Tensor(initial_patch_value).double()\n else:\n raise ValueError(\"Unexpected value for initial_patch_value.\")\n\n def _check_params(self) -> None:\n\n if not isinstance(self.patch_height, int) or self.patch_height <= 0:\n raise ValueError(\"The patch height `patch_height` has to be of type int and larger than zero.\")\n\n if not isinstance(self.patch_width, int) or self.patch_width <= 0:\n raise ValueError(\"The patch width `patch_width` has to be of type int and larger than zero.\")\n\n if not isinstance(self.x_min, int) or self.x_min < 0:\n raise ValueError(\"The vertical position `x_min` has to be of type int and larger than zero.\")\n\n if not isinstance(self.y_min, int) or self.y_min < 0:\n raise ValueError(\"The horizontal position `y_min` has to be of type int and larger than zero.\")\n\n if not isinstance(self.step_size, float) or self.step_size <= 0:\n raise ValueError(\"The step size `step_size` has to be of type float and larger than zero.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The number of iterations `max_iter` has to be of type int and larger than zero.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be of type int and larger than zero.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/feature_adversaries/feature_adversaries_numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Feature Adversaries attack.\n\n| Paper link: https://arxiv.org/abs/1511.05122\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass FeatureAdversariesNumpy(EvasionAttack):\n \"\"\"\n This class represent a Feature Adversaries evasion attack.\n\n | Paper link: https://arxiv.org/abs/1511.05122\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"delta\",\n \"layer\",\n \"batch_size\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n delta: float | None = None,\n layer: int | None = None,\n batch_size: int = 32,\n ):\n \"\"\"\n Create a :class:`.FeatureAdversaries` instance.\n\n :param classifier: A trained classifier.\n :param delta: The maximum deviation between source and guide images.\n :param layer: Index of the representation layer.\n :param batch_size: Batch size.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.delta = delta\n self.layer = layer\n self.batch_size = batch_size\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: Source samples.\n :param y: Guide samples.\n :param kwargs: The kwargs are used as `options` for the minimisation with `scipy.optimize.minimize` using\n `method=\"L-BFGS-B\"`. Valid options are based on the output of\n `scipy.optimize.show_options(solver='minimize', method='L-BFGS-B')`:\n Minimize a scalar function of one or more variables using the L-BFGS-B algorithm.\n\n disp : None or int\n If `disp is None` (the default), then the supplied version of `iprint`\n is used. If `disp is not None`, then it overrides the supplied version\n of `iprint` with the behaviour you outlined.\n maxcor : int\n The maximum number of variable metric corrections used to\n define the limited memory matrix. (The limited memory BFGS\n method does not store the full hessian but uses this many terms\n in an approximation to it.)\n ftol : float\n The iteration stops when ``(f^k -\n f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.\n gtol : float\n The iteration will stop when ``max{|proj g_i | i = 1, ..., n}\n <= gtol`` where ``pg_i`` is the i-th component of the\n projected gradient.\n eps : float\n Step size used for numerical approximation of the Jacobian.\n maxfun : int\n Maximum number of function evaluations.\n maxiter : int\n Maximum number of iterations.\n iprint : int, optional\n Controls the frequency of output. ``iprint < 0`` means no output;\n ``iprint = 0`` print only one line at the last iteration;\n ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;\n ``iprint = 99`` print details of every iteration except n-vectors;\n ``iprint = 100`` print also the changes of active set and final x;\n ``iprint > 100`` print details of every iteration including x and g.\n callback : callable, optional\n Called after each iteration, as ``callback(xk)``, where ``xk`` is the\n current parameter vector.\n maxls : int, optional\n Maximum number of line search steps (per iteration). Default is 20.\n\n The option `ftol` is exposed via the `scipy.optimize.minimize` interface,\n but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The\n relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.\n I.e., `factr` multiplies the default machine floating-point precision to\n arrive at `ftol`.\n :return: Adversarial examples.\n :raises KeyError: The argument {} in kwargs is not allowed as option for `scipy.optimize.minimize` using\n `method=\"L-BFGS-B\".`\n \"\"\"\n from scipy.linalg import norm\n from scipy.optimize import Bounds, minimize\n\n if y is None:\n raise ValueError(\"The value of guide `y` cannot be None. Please provide a `np.ndarray` of guide inputs.\")\n if x.shape != y.shape:\n raise ValueError(\"The shape of source `x` and guide `y` must be of same shape.\")\n if x.shape[1:] != self.estimator.input_shape: # pragma: no cover\n raise ValueError(\"Source and guide inputs must match `input_shape` of estimator.\")\n\n l_b = x.flatten() - self.delta\n l_b[l_b < self.estimator.clip_values[0]] = self.estimator.clip_values[0]\n\n u_b = x.flatten() + self.delta\n u_b[u_b > self.estimator.clip_values[1]] = self.estimator.clip_values[1]\n\n bound = Bounds(lb=l_b, ub=u_b, keep_feasible=False)\n\n guide_representation = self.estimator.get_activations(\n x=y.reshape(-1, *self.estimator.input_shape), # type: ignore\n layer=self.layer,\n batch_size=self.batch_size,\n )\n\n def func(x_i):\n x_i = x_i.astype(x.dtype)\n source_representation = self.estimator.get_activations(\n x=x_i.reshape(-1, *self.estimator.input_shape),\n layer=self.layer,\n batch_size=self.batch_size,\n )\n\n n = (\n norm(\n source_representation.flatten() - guide_representation.flatten(),\n ord=2,\n )\n ** 2\n )\n\n return n\n\n x_0 = x.copy().flatten()\n\n options = {\"eps\": 1e-3, \"ftol\": 1e-3}\n options_allowed_keys = [\n \"disp\",\n \"maxcor\",\n \"ftol\",\n \"gtol\",\n \"eps\",\n \"maxfun\",\n \"maxiter\",\n \"iprint\",\n \"callback\",\n \"maxls\",\n ]\n\n for key in kwargs:\n if key not in options_allowed_keys:\n raise KeyError(\n f\"The argument `{key}` in kwargs is not allowed as option for `scipy.optimize.minimize` using \"\n '`method=\"L-BFGS-B\".`'\n )\n options.update(kwargs)\n\n res = minimize(func, x_0, method=\"L-BFGS-B\", bounds=bound, options=options)\n x_adv = res.x\n logger.info(res)\n\n return x_adv.reshape(-1, *self.estimator.input_shape).astype(x.dtype)\n\n def _check_params(self) -> None:\n \"\"\"\n Apply attack-specific checks.\n \"\"\"\n if self.delta is None:\n raise ValueError(\"The delta cannot be None.\")\n if self.delta is not None and self.delta <= 0:\n raise ValueError(\"The maximum deviation `delta` has to be positive.\")\n\n if not isinstance(self.layer, int):\n raise ValueError(\"The index of the representation layer `layer` has to be integer.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/feature_adversaries/feature_adversaries_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Feature Adversaries attack in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1511.05122\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nif TYPE_CHECKING:\n\n import torch\n from torch.optim import Optimizer\n\n from art.utils import PYTORCH_ESTIMATOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass FeatureAdversariesPyTorch(EvasionAttack):\n \"\"\"\n This class represent a Feature Adversaries evasion attack in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1511.05122\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"delta\",\n \"optimizer\",\n \"optimizer_kwargs\",\n \"lambda_\",\n \"layer\",\n \"max_iter\",\n \"batch_size\",\n \"step_size\",\n \"random_start\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin)\n\n def __init__(\n self,\n estimator: \"PYTORCH_ESTIMATOR_TYPE\",\n delta: float,\n optimizer: \"Optimizer\" | None = None,\n optimizer_kwargs: dict | None = None,\n lambda_: float = 0.0,\n layer: int | str | tuple[int, ...] | tuple[str, ...] = -1,\n max_iter: int = 100,\n batch_size: int = 32,\n step_size: int | float | None = None,\n random_start: bool = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.FeatureAdversariesPyTorch` instance.\n\n :param estimator: A trained estimator.\n :param delta: The maximum deviation between source and guide images.\n :param optimizer: Optimizer applied to problem constrained only by clip values if defined, if None the\n Projected Gradient Descent (PGD) optimizer is used.\n :param optimizer_kwargs: Additional optimizer arguments.\n :param lambda_: Regularization parameter of the L-inf soft constraint.\n :param layer: Index or tuple of indices of the representation layer(s).\n :param max_iter: The maximum number of iterations.\n :param batch_size: Batch size.\n :param step_size: Step size for PGD optimizer.\n :param random_start: Randomly initialize perturbations, when using Projected Gradient Descent variant.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.delta = delta\n self.optimizer = optimizer\n self._optimizer_kwargs = {} if optimizer_kwargs is None else optimizer_kwargs\n self.lambda_ = lambda_\n self.layer = layer if isinstance(layer, tuple) else (layer,)\n self.batch_size = batch_size\n self.max_iter = max_iter\n self.step_size = step_size\n self.random_start = random_start\n self.verbose = verbose\n self._check_params()\n\n def _generate_batch(self, x: \"torch.Tensor\", y: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Generate adversarial batch.\n\n :param x: Source samples.\n :param y: Guide samples.\n :return: Batch of adversarial examples.\n \"\"\"\n import torch\n\n def loss_fn(source_orig, source_adv, guide):\n representation_loss = torch.zeros(size=(source_orig.shape[0],)).to(self.estimator.device)\n for layer_i in self.layer:\n adv_representation = self.estimator.get_activations(source_adv, layer_i, self.batch_size, True)\n guide_representation = self.estimator.get_activations(guide, layer_i, self.batch_size, True)\n\n dim = tuple(range(1, len(source_adv.shape)))\n soft_constraint = torch.amax(torch.abs(source_adv - source_orig), dim=dim)\n\n dim = tuple(range(1, len(adv_representation.shape)))\n representation_loss += torch.sum(torch.square(adv_representation - guide_representation), dim=dim)\n\n loss = torch.mean(representation_loss + self.lambda_ * soft_constraint)\n return loss\n\n self.estimator.model.eval()\n\n adv = x.clone().detach().to(self.estimator.device)\n if self.random_start:\n # Starting at a uniformly random point\n adv = adv + torch.empty_like(adv).uniform_(-self.delta, self.delta)\n if self.estimator.clip_values is not None:\n adv = torch.clamp(adv, *self.estimator.clip_values)\n\n if self.optimizer is None:\n # run a plain-vanilla PGD\n adv.requires_grad = True\n\n for _ in trange(self.max_iter, desc=\"Feature Adversaries PyTorch\", disable=not self.verbose):\n loss = loss_fn(x, adv, y)\n loss.backward()\n\n # pgd step\n if adv.grad is not None and self.step_size is not None:\n adv.data = adv - adv.grad.detach().sign() * self.step_size\n else:\n raise ValueError(\"Gradient tensor in PyTorch model or step_size is `None`.\")\n perturbation = torch.clamp(adv.detach() - x.detach(), -self.delta, self.delta)\n adv.data = x.detach() + perturbation\n if self.estimator.clip_values is not None:\n adv.data = torch.clamp(adv.detach(), *self.estimator.clip_values)\n adv.grad.zero_()\n else:\n # optimize soft constraint problem with chosen optimizer\n opt = self.optimizer(params=[adv], **self._optimizer_kwargs) # type: ignore\n\n for _ in trange(self.max_iter, desc=\"Feature Adversaries PyTorch\", disable=not self.verbose):\n adv.requires_grad = True\n # clip adversarial within L-Inf delta-ball\n adv.data = x.detach() + torch.clamp(adv.detach() - x.detach(), -self.delta, self.delta)\n\n def closure():\n if torch.is_grad_enabled():\n opt.zero_grad()\n loss = loss_fn(x, adv, y)\n if loss.requires_grad:\n loss.backward()\n return loss\n\n opt.step(closure)\n\n if self.estimator.clip_values is not None:\n adv.data = torch.clamp(adv.detach(), *self.estimator.clip_values)\n return adv.detach().cpu()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: Source samples.\n :param y: Guide samples.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n if y is None:\n raise ValueError(\"The value of guide `y` cannot be None. Please provide a `np.ndarray` of guide inputs.\")\n if x.shape != y.shape:\n raise ValueError(\"The shape of source `x` and guide `y` must be of same shape.\")\n if x.shape[1:] != self.estimator.input_shape: # pragma: no cover\n raise ValueError(\"Source and guide inputs must match `input_shape` of estimator.\")\n\n nb_samples = x.shape[0]\n\n x_adversarial = [None] * nb_samples\n\n nb_batches = int(np.ceil(nb_samples / float(self.batch_size)))\n for m in range(nb_batches):\n # batch indices\n begin, end = m * self.batch_size, min((m + 1) * self.batch_size, nb_samples)\n\n # create batch of adversarial examples\n source_batch = torch.tensor(x[begin:end]).to(self.estimator.device)\n guide_batch = torch.tensor(y[begin:end]).to(self.estimator.device)\n x_adversarial[begin:end] = self._generate_batch(source_batch, guide_batch).numpy()\n return np.array(x_adversarial, dtype=x.dtype)\n\n def _check_params(self) -> None:\n \"\"\"\n Apply attack-specific checks.\n \"\"\"\n if not isinstance(self.delta, float):\n raise ValueError(\"The value of delta must be of type float.\")\n if self.delta <= 0:\n raise ValueError(\"The maximum deviation value delta has to be positive.\")\n\n if not isinstance(self.lambda_, float):\n raise ValueError(\"The value of lambda_ must be of type float.\")\n if self.lambda_ < 0.0:\n raise ValueError(\"The regularization parameter `lambda_` has to be non-negative.\")\n\n if not isinstance(self.layer[0], (int, str)):\n raise ValueError(\"The value of the representation layer must be integer or string.\")\n\n if not isinstance(self.max_iter, int):\n raise ValueError(\"The value of max_iter must be of type int.\")\n if self.max_iter <= 0:\n raise ValueError(\"The maximum number of iterations has to be a positive.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size has to be positive.\")\n\n if self.optimizer is None and self.step_size is None:\n raise ValueError(\"The step size cannot be None if optimizer is None.\")\n if self.step_size is not None and not isinstance(self.step_size, (int, float)):\n raise ValueError(\"The value of step_size must be of type int or float.\")\n if self.step_size is not None and self.step_size <= 0:\n raise ValueError(\"The step size has to be a positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/feature_adversaries/feature_adversaries_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Feature Adversaries attack in TensorFlow v2.\n\n| Paper link: https://arxiv.org/abs/1511.05122\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from tensorflow.keras.optimizers import Optimizer\n\n from art.utils import TENSORFLOWV2_ESTIMATOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass FeatureAdversariesTensorFlowV2(EvasionAttack):\n \"\"\"\n This class represent a Feature Adversaries evasion attack in TensorFlow v2.\n\n | Paper link: https://arxiv.org/abs/1511.05122\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"delta\",\n \"optimizer\",\n \"optimizer_kwargs\",\n \"lambda_\",\n \"layer\",\n \"max_iter\",\n \"batch_size\",\n \"step_size\",\n \"random_start\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin)\n\n def __init__(\n self,\n estimator: \"TENSORFLOWV2_ESTIMATOR_TYPE\",\n delta: float,\n optimizer: \"Optimizer\" | None = None,\n optimizer_kwargs: dict | None = None,\n lambda_: float = 0.0,\n layer: int | str | tuple[int, ...] | tuple[str, ...] = -1,\n max_iter: int = 100,\n batch_size: int = 32,\n step_size: int | float | None = None,\n random_start: bool = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.FeatureAdversariesTensorFlowV2` instance.\n\n :param estimator: A trained estimator.\n :param delta: The maximum deviation between source and guide images.\n :param optimizer: Optimizer applied to problem constrained only by clip values if defined, if None the\n Projected Gradient Descent (PGD) optimizer is used.\n :param optimizer_kwargs: Additional optimizer arguments.\n :param lambda_: Regularization parameter of the L-inf soft constraint.\n :param layer: Index or tuple of indices of the representation layer(s).\n :param max_iter: The maximum number of iterations.\n :param batch_size: Batch size.\n :param step_size: Step size for PGD optimizer.\n :param random_start: Randomly initialize perturbations, when using Projected Gradient Descent variant.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.delta = delta\n self.optimizer = optimizer\n self._optimizer_kwargs = {} if optimizer_kwargs is None else optimizer_kwargs\n self.lambda_ = lambda_\n self.layer = layer if isinstance(layer, tuple) else (layer,)\n self.batch_size = batch_size\n self.max_iter = max_iter\n self.step_size = step_size\n self.random_start = random_start\n self.verbose = verbose\n self._check_params()\n\n def _generate_batch(self, x: \"tf.Tensor\", y: \"tf.Tensor\") -> \"tf.Tensor\":\n \"\"\"\n Generate adversarial batch.\n\n :param x: Source samples.\n :param y: Guide samples.\n :return: Batch of adversarial examples.\n \"\"\"\n import tensorflow as tf\n\n def loss_fn(source_orig, source_adv, guide):\n representation_loss = tf.zeros(shape=(source_orig.shape[0],), dtype=tf.float32)\n for layer_i in self.layer:\n adv_representation = self.estimator.get_activations(source_adv, layer_i, self.batch_size, True)\n guide_representation = self.estimator.get_activations(guide, layer_i, self.batch_size, True)\n\n axis = tuple(range(1, len(source_adv.shape)))\n soft_constraint = tf.cast(tf.math.reduce_max(tf.abs(source_adv - source_orig), axis=axis), tf.float32)\n\n axis = tuple(range(1, len(adv_representation.shape)))\n representation_loss += tf.reduce_sum(tf.square(adv_representation - guide_representation), axis=axis)\n\n loss = tf.math.reduce_mean(representation_loss + self.lambda_ * soft_constraint)\n return loss\n\n adv = tf.identity(x)\n if self.random_start:\n # Starting at a uniformly random point\n adv = adv + tf.random.uniform(x.shape, -self.delta, self.delta)\n if self.estimator.clip_values is not None:\n adv = tf.clip_by_value(adv, *self.estimator.clip_values)\n\n if self.optimizer is None:\n # run a plain-vanilla PGD\n for _ in trange(self.max_iter, desc=\"Feature Adversaries TensorFlow v2\", disable=not self.verbose):\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n tape.watch(adv)\n loss = loss_fn(x, adv, y)\n gradient = tape.gradient(loss, adv)\n\n # pgd step\n adv = adv - tf.math.sign(gradient) * self.step_size\n perturbation = tf.clip_by_value(adv - x, -self.delta, self.delta)\n adv = x + perturbation\n if self.estimator.clip_values is not None:\n adv = tf.clip_by_value(x + perturbation, *self.estimator.clip_values)\n else:\n # optimize soft constraint problem with chosen optimizer\n opt = self.optimizer(**self._optimizer_kwargs) # type: ignore\n perturbation = tf.Variable(\n tf.zeros_like(adv),\n trainable=True,\n constraint=lambda x: tf.clip_by_value(x, -self.delta, self.delta),\n )\n\n for _ in trange(self.max_iter, desc=\"Feature Adversaries TensorFlow v2\", disable=not self.verbose):\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n tape.watch(perturbation)\n adv = x + perturbation\n loss = loss_fn(x, adv, y)\n gradient = tape.gradient(loss, perturbation)\n\n opt.apply_gradients([(gradient, perturbation)])\n\n if self.estimator.clip_values is not None:\n adv = tf.clip_by_value(x + perturbation, *self.estimator.clip_values)\n perturbation.assign(adv - x)\n return adv\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: Source samples.\n :param y: Guide samples.\n :return: Adversarial examples.\n \"\"\"\n import tensorflow as tf\n\n if y is None:\n raise ValueError(\"The value of guide `y` cannot be None. Please provide a `np.ndarray` of guide inputs.\")\n if x.shape != y.shape:\n raise ValueError(\"The shape of source `x` and guide `y` must be of same shape.\")\n if x.shape[1:] != self.estimator.input_shape: # pragma: no cover\n raise ValueError(\"Source and guide inputs must match `input_shape` of estimator.\")\n\n nb_samples = x.shape[0]\n\n x_adversarial = [None] * nb_samples\n\n nb_batches = int(np.ceil(nb_samples / float(self.batch_size)))\n for m in range(nb_batches):\n # batch indices\n begin, end = m * self.batch_size, min((m + 1) * self.batch_size, nb_samples)\n\n # create batch of adversarial examples\n source_batch = tf.convert_to_tensor(x[begin:end])\n guide_batch = tf.convert_to_tensor(y[begin:end])\n x_adversarial[begin:end] = self._generate_batch(source_batch, guide_batch).numpy()\n return np.array(x_adversarial, dtype=x.dtype)\n\n def _check_params(self) -> None:\n \"\"\"\n Apply attack-specific checks.\n \"\"\"\n if not isinstance(self.delta, float):\n raise ValueError(\"The value of delta must be of type float.\")\n if self.delta <= 0:\n raise ValueError(\"The maximum deviation value delta has to be positive.\")\n\n if not isinstance(self.lambda_, float):\n raise ValueError(\"The value of lambda_ must be of type float.\")\n if self.lambda_ < 0.0:\n raise ValueError(\"The regularization parameter `lambda_` has to be non-negative.\")\n\n if not isinstance(self.layer[0], (int, str)):\n raise ValueError(\"The value of the representation layer must be integer or string.\")\n\n if not isinstance(self.max_iter, int):\n raise ValueError(\"The value of max_iter must be of type int.\")\n if self.max_iter <= 0:\n raise ValueError(\"The maximum number of iterations has to be a positive.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size has to be positive.\")\n\n if self.optimizer is None and self.step_size is None:\n raise ValueError(\"The step size cannot be None if optimizer is None.\")\n if self.step_size is not None and not isinstance(self.step_size, (int, float)):\n raise ValueError(\"The value of step_size must be of type int or float.\")\n if self.step_size is not None and self.step_size <= 0:\n raise ValueError(\"The step size has to be a positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/graphite/graphite_blackbox.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2022 University of Michigan and University of Wisconsin-Madison\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the black-box (hard-label) GRAPHITE attack `GRAPHITEBlackbox`. This is a physical black-box\nattack that only requires class predictions.\n\n| Paper link: https://arxiv.org/abs/2002.07088\n| Original GitHub link: https://github.com/ryan-feng/GRAPHITE\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport random\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\nfrom art.utils import compute_success, to_categorical, check_and_transform_label_format\nfrom art.attacks.evasion.graphite.utils import (\n convert_to_network,\n get_transform_params,\n add_noise,\n get_transformed_images,\n run_predictions,\n score_fn,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass GRAPHITEBlackbox(EvasionAttack):\n \"\"\"\n Implementation of the hard-label GRAPHITE attack from Feng et al. (2022). This is a physical, black-box attack\n that only requires final class prediction and generates robust physical perturbations that can be applied as\n stickers.\n\n | Paper link: https://arxiv.org/abs/2002.07088\n | Original GitHub link: https://github.com/ryan-feng/GRAPHITE\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"noise_size\",\n \"net_size\",\n \"heat_patch_size\",\n \"heat_patch_stride\",\n \"heatmap_mode\",\n \"tr_lo\",\n \"tr_hi\",\n \"num_xforms_mask\",\n \"max_mask_size\",\n \"rotation_range\",\n \"beta\",\n \"eta\",\n \"num_xforms_boost\",\n \"num_boost_queries\",\n \"dist_range\",\n \"gamma_range\",\n \"crop_percent_range\",\n \"off_x_range\",\n \"off_y_range\",\n \"blur_kernels\",\n \"batch_size\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n noise_size: tuple[int, int],\n net_size: tuple[int, int],\n heat_patch_size: tuple[int, int] = (4, 4),\n heat_patch_stride: tuple[int, int] = (1, 1),\n heatmap_mode: str = \"Target\",\n tr_lo: float = 0.65,\n tr_hi: float = 0.85,\n num_xforms_mask: int = 100,\n max_mask_size: int = -1,\n beta: float = 1.0,\n eta: float = 500,\n num_xforms_boost: int = 100,\n num_boost_queries: int = 20000,\n rotation_range: tuple[float, float] = (-30.0, 30.0),\n dist_range: tuple[float, float] = (0.0, 0.0),\n gamma_range: tuple[float, float] = (1.0, 2.0),\n crop_percent_range: tuple[float, float] = (-0.03125, 0.03125),\n off_x_range: tuple[float, float] = (-0.03125, 0.03125),\n off_y_range: tuple[float, float] = (-0.03125, 0.03125),\n blur_kernels: tuple[int, int] | list[int] = (0, 3),\n batch_size: int = 64,\n ) -> None:\n \"\"\"\n Create a GRAPHITEBlackbox attack instance.\n\n :param classifier: A trained classifier.\n :param noise_size: The resolution to generate perturbations in (w, h).\n :param net_size: The resolution to resize images to before feeding to the model in (w, h).\n :param heat_patch_size: The size of the heatmap patches in (w, h).\n :param heat_patch_stride: The stride of the heatmap patching in (w, h).\n :param heatmap_mode: The mode of heatmap in ['Target', 'Random'].\n :param tr_lo: tr_lo, threshold for fine-grained reduction.\n :param tr_hi: tr_hi, threshold for coarse-grained reduction.\n :param num_xforms_mask: The number of transforms to use in mask generation.\n :param max_mask_size: Optionally specify that you just want to optimize until a mask size of <= max_mask_size.\n :param beta: The parameter beta for RGF optimization in boosting.\n :param eta: The step size for RGF optimization in boosting.\n :param num_xforms_boost: The number of transforms to use in boosting.\n :param num_boost_queries: The number of queries to use in boosting.\n :param rotation_range: The range of the rotation in the perspective transform.\n :param dist_range: The range of the distance (in ft) to be added to the focal length in perspective transform.\n :param gamma_range: The range of the gamma in the gamma transform.\n :param crop_percent_range: The range of the crop percent in the perspective transform.\n :param off_x_range: The range of the x offset (percent) in the perspective transform.\n :param off_y_range: The range of the y offset (percent) in the perspective transform.\n :param blur_kernels: The kernels to blur with.\n :param batch_size: The size of the batch used by the estimator during inference.\n \"\"\"\n super().__init__(estimator=classifier)\n self.noise_size = noise_size\n self.net_size = net_size\n self.heat_patch_size = heat_patch_size\n self.heat_patch_stride = heat_patch_stride\n self.heatmap_mode = heatmap_mode\n self.batch_size = batch_size\n self.tr_lo = tr_lo\n self.tr_hi = tr_hi\n self.num_xforms_mask = num_xforms_mask\n self.max_mask_size = max_mask_size\n self.beta = beta\n self.eta = eta\n self.num_xforms_boost = num_xforms_boost\n self.num_boost_queries = num_boost_queries\n self.rotation_range = rotation_range\n self.dist_range = dist_range\n self.gamma_range = gamma_range\n self.crop_percent_range = crop_percent_range\n self.off_x_range = off_x_range\n self.off_y_range = off_y_range\n self.blur_kernels = blur_kernels\n\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,).\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :param x_tar: Initial array to act as the example target image.\n :param pts: Optional points to consider when cropping the perspective transform. An array of points in\n [x, y, scale] with shape [num points, 3, 1].\n :param obj_width: The estimated object width (inches) for perspective transform. 30 by default.\n :param focal: The estimated focal length (ft) for perspective transform. 3 by default.\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = kwargs.get(\"mask\")\n x_tar = kwargs.get(\"x_tar\")\n obj_width = kwargs.get(\"obj_width\") if \"obj_width\" in kwargs else 30\n focal = kwargs.get(\"focal\") if \"focal\" in kwargs else 3\n pts = kwargs.get(\"pts\") if \"pts\" in kwargs else None\n\n if y is None:\n raise ValueError(\"Target labels `y` need to be provided.\")\n\n if x_tar is None:\n raise ValueError(\"Target image example `x_tar` needs to be provided.\")\n\n y = check_and_transform_label_format(y, self.estimator.nb_classes)\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if not isinstance(obj_width, int) and not isinstance(obj_width, float):\n raise ValueError(\"obj_width must be int or float\")\n obj_width = float(obj_width)\n\n if not isinstance(focal, int) and not isinstance(focal, float):\n raise ValueError(\"focal must be int or float\")\n focal = float(focal)\n\n # Check the mask\n if mask is not None:\n if len(mask.shape) == len(x.shape):\n mask = mask.astype(ART_NUMPY_DTYPE)\n else:\n mask = np.array([mask.astype(ART_NUMPY_DTYPE)] * x.shape[0])\n else:\n mask = np.array([None] * x.shape[0])\n\n # Get clip_min and clip_max from the classifier or infer them from data\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.min(x), np.max(x)\n\n # target initialization image\n x_tar = kwargs.get(\"x_tar\")\n\n if x_tar is None:\n raise ValueError(\"x_tar is None. Please provide x_tar as initial array to act as the example target image.\")\n\n # Some initial setups\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n if self.estimator.channels_first:\n x = np.transpose(x, (0, 2, 3, 1))\n x_adv = np.transpose(x_adv, (0, 2, 3, 1))\n x_tar = np.transpose(x_tar, (0, 2, 3, 1))\n if len(mask.shape) == 4:\n mask = np.transpose(mask, (0, 2, 3, 1))\n\n y = np.argmax(y, axis=1)\n\n # Generate the adversarial samples\n for i in range(x_adv.shape[0]):\n x_adv[i] = self._perturb(\n x=x_adv[i],\n y=y[i], # type: ignore\n x_tar=x_tar[i],\n obj_width=obj_width,\n focal=focal,\n clip_min=clip_min,\n clip_max=clip_max,\n mask=mask[i],\n pts=pts,\n )\n\n y = to_categorical(y, self.estimator.nb_classes) # type: ignore\n\n # COMPUTE SUCCESS RATE\n x_copy = np.zeros((x.shape[0], self.noise_size[1], self.noise_size[0], x.shape[3]))\n x_adv_copy = np.zeros((x_adv.shape[0], self.noise_size[1], self.noise_size[0], x_adv.shape[3]))\n for i in range(x_copy.shape[0]):\n x_copy[i] = convert_to_network(x[i], self.net_size, clip_min, clip_max)\n x_adv_copy[i] = convert_to_network(x_adv[i], self.net_size, clip_min, clip_max)\n\n if self.estimator.channels_first:\n x_copy = np.transpose(x_copy, (0, 3, 1, 2))\n x_adv_copy = np.transpose(x_adv_copy, (0, 3, 1, 2))\n\n logger.info(\n \"Success rate of GRAPHITE hard-label attack: %.2f%%\",\n 100\n * compute_success(\n self.estimator,\n x_copy.astype(np.float32),\n y,\n x_adv_copy.astype(np.float32),\n self.targeted,\n batch_size=self.batch_size,\n ),\n )\n\n if self.estimator.channels_first:\n x_adv = np.transpose(x_adv, (0, 3, 1, 2))\n\n return x_adv\n\n def _perturb(\n self,\n x: np.ndarray,\n y: int,\n x_tar: np.ndarray,\n obj_width: float,\n focal: float,\n clip_min: float,\n clip_max: float,\n mask: np.ndarray | None = None,\n pts: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n Internal attack function for one example.\n\n :param x: An array with one original input to be attacked.\n :param y: The target label.\n :param x_tar: Initial array to act as an example target image.\n :param obj_width: Estimated width of object in inches for perspective transform.\n :param focal: Estimated focal length in ft for perspective transform.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: An adversarial example.\n \"\"\"\n import cv2\n\n x = (x.copy() - clip_min) / (clip_max - clip_min)\n x_tar = (x_tar.copy() - clip_min) / (clip_max - clip_min)\n\n if mask is None:\n mask_array = np.ones((self.noise_size[1], self.noise_size[0], x.shape[2]))\n else:\n mask_array = mask\n mask_array = mask_array / np.max(mask_array)\n\n x_copy = x.copy()\n x_tar_copy = x_tar.copy()\n mask_copy = mask_array.copy()\n x_noise = cv2.resize(x_copy, self.noise_size)\n x_tar_noise = cv2.resize(x_tar_copy, self.noise_size)\n mask_noise = cv2.resize(mask_copy, self.noise_size).astype(float)\n mask_noise = np.where(mask_noise > 0.5, 1.0, 0.0)\n\n if len(x_noise.shape) < 3:\n x_noise = x_noise[:, :, np.newaxis]\n if len(x_tar_noise.shape) < 3:\n x_tar_noise = x_tar_noise[:, :, np.newaxis]\n if len(mask_noise.shape) < 3:\n mask_noise = mask_noise[:, :, np.newaxis]\n\n mask_out = self._generate_mask(\n x_copy, x_noise, x_tar_noise, mask_noise, y, obj_width, focal, clip_min, clip_max, pts\n )\n\n adversarial = self._boost(x_copy, x_noise, x_tar_noise, mask_out, y, obj_width, focal, clip_min, clip_max, pts)\n\n adversarial = np.clip(adversarial.copy() * (clip_max - clip_min) + clip_min, clip_min, clip_max)\n return adversarial\n\n def _generate_mask(\n self,\n x: np.ndarray,\n x_noise: np.ndarray,\n x_tar_noise: np.ndarray,\n mask: np.ndarray,\n y: int,\n obj_width: float,\n focal: float,\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n Function to generate a mask.\n\n :param x: An array with one original input to be attacked.\n :param x_noise: x in the resolution of the noise size.\n :param x_tar_noise: x_tar in the resolution of the noise size.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param y: The target label.\n :param obj_width: Estimated width of object in inches for perspective transform.\n :param focal: Estimated focal length in ft for perspective transform.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: A mask.\n \"\"\"\n\n # Stage 1: HEATMAP: Collect all the valid patches and order by computed heatmap\n xforms = get_transform_params(\n self.num_xforms_mask,\n self.rotation_range,\n self.dist_range,\n self.gamma_range,\n self.crop_percent_range,\n self.off_x_range,\n self.off_y_range,\n self.blur_kernels,\n obj_width,\n focal,\n )\n\n object_size = mask.sum() / mask.shape[-1]\n\n patch = np.ones((self.heat_patch_size[1], self.heat_patch_size[0], x.shape[-1]))\n patches = []\n indices = []\n\n # collect all valid patches\n for i in range(0, mask.shape[0] - self.heat_patch_size[1] + 1, self.heat_patch_stride[1]):\n for j in range(0, mask.shape[1] - self.heat_patch_size[0] + 1, self.heat_patch_stride[0]):\n new_mask = np.zeros(mask.shape)\n new_mask[\n i : min(i + self.heat_patch_size[1], mask.shape[0]),\n j : min(j + self.heat_patch_size[0], mask.shape[1]),\n ] = patch\n new_mask = new_mask * mask\n if np.sum(new_mask) > 0:\n patches.append(new_mask)\n indices.append((i, j))\n\n # compute heatmap and order\n if self.heatmap_mode == \"Random\":\n tr_scores = [random.random() for i in range(len(patches))]\n else: # Target mode\n\n tr_scores = self._get_heatmap(\n x,\n x_noise,\n x_tar_noise,\n mask,\n y,\n patches,\n xforms,\n clip_min,\n clip_max,\n pts,\n )\n\n tr_scores_np = np.asarray(tr_scores)\n order = tr_scores_np.argsort()\n patches = [patches[ind] for ind in order]\n indices = [indices[ind] for ind in order]\n\n # STAGE 2: Coarse Reduction\n best_mask, patches, indices = self._get_coarse_reduced_mask(\n x, x_noise, x_tar_noise, y, mask, patches, indices, xforms, clip_min, clip_max, pts\n )\n\n # STAGE 3: Fine Reduction\n if self.max_mask_size > 0:\n lbd = 5\n while best_mask.sum() / mask.shape[-1] > self.max_mask_size:\n patches_copy = list(patches)\n best_mask = self._get_fine_reduced_mask(\n x,\n x_noise,\n x_tar_noise,\n y,\n best_mask,\n patches_copy,\n xforms,\n object_size,\n clip_min,\n clip_max,\n lbd,\n pts,\n )\n lbd += 5\n else:\n best_mask = self._get_fine_reduced_mask(\n x,\n x_noise,\n x_tar_noise,\n y,\n best_mask,\n patches,\n xforms,\n object_size,\n clip_min,\n clip_max,\n pts=pts,\n )\n\n return best_mask\n\n def _get_heatmap(\n self,\n x: np.ndarray,\n x_noise: np.ndarray,\n x_tar_noise: np.ndarray,\n mask: np.ndarray,\n y: int,\n patches: list[np.ndarray],\n xforms: list,\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None = None,\n ) -> list[float]:\n \"\"\"\n Function to generate a heatmap.\n\n :param x: An array with one original input to be attacked.\n :param x_noise: x in the resolution of the noise size.\n :param x_tar_noise: x_tar in the resolution of the noise size.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param y: The target label.\n :param patches: List of patches from heatmap.\n :param xforms: List of transform params.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: List of transform-robustness scores for the list of patches.\n \"\"\"\n tr_scores = []\n\n # iterate over patches and compute transform_robustness without each individual patch\n for patch in patches:\n next_mask = mask * (np.ones(mask.shape) - patch)\n theta = (x_tar_noise - x_noise) * next_mask\n xform_imgs = get_transformed_images(\n x, next_mask, xforms, 1.0, theta, self.net_size, clip_min, clip_max, pts\n )\n success_rate = run_predictions(self.estimator, xform_imgs, y, self.batch_size, False)\n tr_scores.append(success_rate)\n\n return tr_scores\n\n def _evaluate_transform_robustness_at_pivot(\n self,\n x: np.ndarray,\n x_noise: np.ndarray,\n x_tar_noise: np.ndarray,\n y: int,\n mask: np.ndarray,\n patches: list[np.ndarray],\n xforms: list,\n clip_min: float,\n clip_max: float,\n pivot: int,\n pts: np.ndarray | None = None,\n ) -> tuple[float, np.ndarray]:\n \"\"\"\n Function as a binary search plug-in that evaluates the transform-robustness at the specified pivot.\n\n :param x: An array with one original input to be attacked.\n :param x_noise: x in the resolution of the noise size.\n :param x_tar_noise: x_tar in the resolution of the noise size.\n :param y: The target label.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param patches: List of patches from heatmap.\n :param xforms: List of transform params.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pivot: Pivot point to evaluate transform-robustness at.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: transform-robustness and mask.\n \"\"\"\n\n best_mask = np.zeros(mask.shape)\n ordering = patches[:pivot]\n for next_patch in ordering:\n next_mask = best_mask + (np.zeros(best_mask.shape) + next_patch)\n next_mask = np.where(next_mask > 0, 1.0, 0.0)\n best_mask = next_mask\n\n theta = (x_tar_noise - x_noise) * best_mask\n xform_imgs = get_transformed_images(x, best_mask, xforms, 1.0, theta, self.net_size, clip_min, clip_max, pts)\n success_rate = run_predictions(self.estimator, xform_imgs, y, self.batch_size, False)\n\n return (success_rate, best_mask)\n\n def _get_coarse_reduced_mask(\n self,\n x: np.ndarray,\n x_noise: np.ndarray,\n x_tar_noise: np.ndarray,\n y: int,\n mask: np.ndarray,\n patches: list[np.ndarray],\n indices: list[tuple[int, int]],\n xforms: list,\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None = None,\n ) -> tuple[np.ndarray, list[np.ndarray], list[tuple[int, int]]]:\n \"\"\"\n Function to coarsely reduce mask.\n\n :param x: An array with one original input to be attacked.\n :param x_noise: x in the resolution of the noise size.\n :param x_tar_noise: x_tar in the resolution of the noise size.\n :param y: The target label.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param patches: List of patches from heatmap.\n :param indices: List of indices for the heatmap patches.\n :param xforms: List of transform params.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: mask, adjusted list of patches, adjusted list of indices\n \"\"\"\n # binary search leftmost pivot value for which `tr` exceeds specified threshold if one exists\n num_patches = len(patches)\n if num_patches == 1:\n pivot = 0\n\n else:\n low = 0\n high = num_patches - 1\n while low <= high:\n mid = low + (high - low) // 2\n score, _ = self._evaluate_transform_robustness_at_pivot(\n x, x_noise, x_tar_noise, y, mask, patches, xforms, clip_min, clip_max, mid, pts\n )\n if score >= self.tr_hi:\n if mid > 0:\n high = mid - 1\n continue\n break\n\n # score < threshold:\n low = mid + 1\n\n pivot = mid\n\n _, best_mask = self._evaluate_transform_robustness_at_pivot(\n x, x_noise, x_tar_noise, y, mask, patches, xforms, clip_min, clip_max, pivot, pts\n )\n\n patches = patches[:] # reduce will examine all patches\n indices = indices[:]\n\n return best_mask, patches, indices\n\n def _get_fine_reduced_mask(\n self,\n x: np.ndarray,\n x_noise: np.ndarray,\n x_tar_noise: np.ndarray,\n y: int,\n mask: np.ndarray,\n patches: list[np.ndarray],\n xforms: list,\n object_size: float,\n clip_min: float,\n clip_max: float,\n lbd: float = 5,\n pts: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n Function to finely reduce mask.\n\n :param x: An array with one original input to be attacked.\n :param x_noise: x in the resolution of the noise size.\n :param x_tar_noise: x_tar in the resolution of the noise size.\n :param y: The target label.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param patches: List of patches from heatmap.\n :param xforms: List of transform params.\n :param obj_size: Estimated width of object in inches for perspective transform.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param lbd: Weight for mask scoring function.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: mask\n \"\"\"\n # STAGE 3: Fine reduction\n theta = (x_tar_noise - x_noise) * mask\n\n # get initial transform_robustness\n xform_imgs = get_transformed_images(x, mask, xforms, 1.0, theta, self.net_size, clip_min, clip_max, pts)\n\n success_rate = run_predictions(self.estimator, xform_imgs, y, self.batch_size, False)\n\n init_tr_err = 1 - success_rate\n\n best_score = score_fn(mask, init_tr_err, object_size, threshold=(1 - self.tr_lo), lbd=lbd)\n best_mask = mask\n\n new_patches = []\n j = 0\n # iterate over patches, greedily remove if the score improves\n while patches:\n j = j + 1\n\n # highest transform_robustness is now always at end, for pop()\n next_patch = patches.pop()\n if np.max(next_patch * best_mask) == 0:\n continue\n next_mask = best_mask * (np.ones(best_mask.shape) - next_patch)\n theta = (x_tar_noise - x_noise) * next_mask\n\n xform_imgs = get_transformed_images(\n x, next_mask, xforms, 1.0, theta, self.net_size, clip_min, clip_max, pts\n )\n\n success_rate = run_predictions(self.estimator, xform_imgs, y, self.batch_size, False)\n\n score = score_fn(next_mask, 1 - success_rate, object_size, threshold=(1 - self.tr_lo), lbd=lbd)\n if score < best_score:\n best_score = score\n best_mask = next_mask\n nbits = best_mask.sum() / best_mask.shape[-1]\n if self.max_mask_size > 0 and nbits < self.max_mask_size:\n break\n else:\n new_patches.append(next_patch)\n\n return best_mask\n\n def _boost(\n self,\n x: np.ndarray,\n x_noise: np.ndarray,\n x_tar_noise: np.ndarray,\n mask: np.ndarray,\n y: int,\n obj_width: float,\n focal: float,\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n Function to boost transform-robustness.\n\n :param x: An array with one original input to be attacked.\n :param x_noise: x in the resolution of the noise size.\n :param x_tar_noise: x_tar in the resolution of the noise size.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param y: The target label.\n :param obj_width: Estimated width of object in inches for perspective transform.\n :param focal: Estimated focal length in ft for perspective transform.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: attacked image\n \"\"\"\n\n xforms = get_transform_params(\n self.num_xforms_boost,\n self.rotation_range,\n self.dist_range,\n self.gamma_range,\n self.crop_percent_range,\n self.off_x_range,\n self.off_y_range,\n self.blur_kernels,\n obj_width,\n focal,\n )\n\n # Initialize\n theta = (x_tar_noise - x_noise) * mask\n query_count = 0\n\n xform_imgs = get_transformed_images(x, mask, xforms, 1.0, theta, self.net_size, clip_min, clip_max, pts)\n\n err_rate = run_predictions(self.estimator, xform_imgs, y, self.batch_size, True)\n query_count += self.num_xforms_boost\n\n best_theta, best_eps = theta, err_rate\n\n # End Initialize\n\n theta, eps = best_theta.copy(), best_eps\n\n opt_count = 0\n\n # gradient free optimization steps\n while True:\n gradient = np.zeros(theta.shape)\n num_q_samples = 10\n\n # Take q samples of random Gaussian noise to use as new directions, calculate transform_robustness\n # Used for gradient estimate\n for _ in range(num_q_samples):\n unit_dir = np.random.randn(*theta.shape).astype(np.float32) * mask\n unit_dir = unit_dir / np.linalg.norm(unit_dir)\n ttt = theta + self.beta * unit_dir\n\n xform_imgs = get_transformed_images(x, mask, xforms, 1.0, ttt, self.net_size, clip_min, clip_max, pts)\n eps_ttt = run_predictions(self.estimator, xform_imgs, y, self.batch_size, True)\n opt_count += self.num_xforms_boost\n\n gradient += (eps_ttt - eps) / self.beta * unit_dir\n\n gradient = 1.0 / num_q_samples * gradient\n\n # Take gradient step\n new_theta = theta - self.eta * gradient\n xform_imgs = get_transformed_images(x, mask, xforms, 1.0, new_theta, self.net_size, clip_min, clip_max, pts)\n new_eps = run_predictions(self.estimator, xform_imgs, y, self.batch_size, True)\n opt_count += self.num_xforms_boost\n\n if new_eps < best_eps:\n best_theta, best_eps = new_theta.copy(), new_eps\n\n theta, eps = new_theta.copy(), new_eps\n\n if (opt_count + query_count + self.num_xforms_boost * 11) > self.num_boost_queries:\n break\n\n adv_example, _, _ = add_noise(x, mask, 1.0, best_theta)\n\n return adv_example\n\n def _check_params(self) -> None:\n if self.noise_size < self.heat_patch_size:\n raise ValueError(\"Heatmap patch size must be smaller than the noise size.\")\n\n if min(self.heat_patch_size) <= 0:\n raise ValueError(\"Heatmap patch size must be positive.\")\n\n if not isinstance(self.heat_patch_size[0], int) or not isinstance(self.heat_patch_size[1], int):\n raise ValueError(\"Heatmap patch size must be a tuple of two integers.\")\n\n if (\n min(self.heat_patch_stride) <= 0\n or not isinstance(self.heat_patch_stride[0], int)\n or not isinstance(self.heat_patch_stride[1], int)\n ):\n raise ValueError(\"Heatmap patch stride must be a tuple of two positive integers.\")\n\n if self.heatmap_mode not in [\"Target\", \"Random\"]:\n raise ValueError(\"Heatmap mode must be 'Target' or 'Random'.\")\n\n if self.tr_lo < 0 or self.tr_lo > 1:\n raise ValueError(\"tr_lo must be between 0 and 1.\")\n\n if self.tr_hi < 0 or self.tr_hi > 1:\n raise ValueError(\"tr_hi must be between 0 and 1.\")\n\n if self.tr_hi < self.tr_lo:\n raise ValueError(\"tr_hi must be at least as high as tr_lo.\")\n\n if self.num_xforms_mask < 0 or not isinstance(self.num_xforms_mask, int):\n raise ValueError(\"num_xforms_mask must be non-negative integer.\")\n\n if self.beta <= 0:\n raise ValueError(\"beta must be positive.\")\n\n if self.eta <= 0:\n raise ValueError(\"eta must be positive.\")\n\n if self.num_xforms_boost < 0 or not isinstance(self.num_xforms_boost, int):\n raise ValueError(\"num_xforms_boost must be positive integer.\")\n\n if self.num_boost_queries <= 0 or not isinstance(self.num_boost_queries, int):\n raise ValueError(\"num_boost_queries must be positive.\")\n\n if (\n self.rotation_range[0] <= -90\n or self.rotation_range[1] >= 90\n or self.rotation_range[1] < self.rotation_range[0]\n ):\n raise ValueError(\"rotation range must be within (-90, 90).\")\n\n if self.dist_range[1] < self.dist_range[0] or self.dist_range[0] < 0:\n raise ValueError(\"distance range invalid. max must be greater than min, and must be nonnegative.\")\n\n if self.gamma_range[1] < self.gamma_range[0] or self.gamma_range[0] < 1:\n raise ValueError(\"gamma range max must be greater than min and the range must be at 1.0 or greater.\")\n\n if self.crop_percent_range[1] < self.crop_percent_range[0]:\n raise ValueError(\"max of crop percent range must be greater or equal to the min.\")\n\n if self.off_x_range[1] < self.off_x_range[0]:\n raise ValueError(\"max of off x range must be greater or equal to the min.\")\n\n if self.off_y_range[1] < self.off_y_range[0]:\n raise ValueError(\"max of off y range must be greater or equal to the min.\")\n\n if min(self.blur_kernels) < 0:\n raise ValueError(\"blur kernels must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/graphite/graphite_whitebox_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2022 University of Michigan and University of Wisconsin-Madison\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the white-box PyTorch version of the GRAPHITE attack `GRAPHITEWhiteboxPyTorch`.\nThis is a robust physical perturbation attack.\n\n| Paper link: https://arxiv.org/abs/2002.07088\n| Original GitHub link: https://github.com/ryan-feng/GRAPHITE\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\nfrom art.utils import compute_success, to_categorical, check_and_transform_label_format, is_probability\nfrom art.attacks.evasion.graphite.utils import convert_to_network, get_transform_params, transform_wb\n\nif TYPE_CHECKING:\n from art.estimators.classification.pytorch import PyTorchClassifier\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass GRAPHITEWhiteboxPyTorch(EvasionAttack):\n \"\"\"\n Implementation of the white-box PyTorch GRAPHITE attack from Feng et al. (2022). This is a physical attack\n that generates robust physical perturbations that can be applied as stickers.\n\n | Paper link: https://arxiv.org/abs/2002.07088\n | Original GitHub link: https://github.com/ryan-feng/GRAPHITE\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"net_size\",\n \"min_tr\",\n \"num_xforms\",\n \"step_size\",\n \"steps\",\n \"first_steps\",\n \"patch_removal_size\",\n \"patch_removal_interval\",\n \"num_patches_to_remove\",\n \"rand_start_epsilon_range\",\n \"rotation_range\",\n \"dist_range\",\n \"gamma_range\",\n \"crop_percent_range\",\n \"off_x_range\",\n \"off_y_range\",\n \"blur_kernels\",\n \"batch_size\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"PyTorchClassifier\",\n net_size: tuple[int, int],\n min_tr: float = 0.8,\n num_xforms: int = 100,\n step_size: float = 0.0157,\n steps: int = 50,\n first_steps: int = 500,\n patch_removal_size: float = 4,\n patch_removal_interval: float = 2,\n num_patches_to_remove: int = 4,\n rand_start_epsilon_range: tuple[float, float] = (-8 / 255, 8 / 255),\n rotation_range: tuple[float, float] = (-30.0, 30.0),\n dist_range: tuple[float, float] = (0.0, 0.0),\n gamma_range: tuple[float, float] = (1.0, 2.0),\n crop_percent_range: tuple[float, float] = (-0.03125, 0.03125),\n off_x_range: tuple[float, float] = (-0.03125, 0.03125),\n off_y_range: tuple[float, float] = (-0.03125, 0.03125),\n blur_kernels: tuple[int, int] | list[int] = (0, 3),\n batch_size: int = 64,\n ) -> None:\n \"\"\"\n Create a GRAPHITEWhiteboxPyTorch attack instance.\n\n :param classifier: A trained classifier.\n :param net_size: The resolution to resize images to before feeding to the model in (w, h).\n :param min_tr: minimum threshold for EoT PGD to reach.\n :param num_xforms: The number of transforms to use.\n :param step_size: The step size.\n :param steps: The number of steps for EoT PGD after the first iteration.\n :param first_steps: The number of steps for EoT PGD for the first iteration.\n :param patch_removal_size: size of patch removal.\n :param patch_removal_interval: stride for patch removal.\n :param num_patches_to_remove: the number of patches to remove per iteration.\n :param rand_start_epsilon_range: the range for random start init.\n :param rotation_range: The range of the rotation in the perspective transform.\n :param dist_range: The range of the dist (in ft) to be added to the focal length in the perspective transform.\n :param gamma_range: The range of the gamma in the gamma transform.\n :param crop_percent_range: The range of the crop percent in the perspective transform.\n :param off_x_range: The range of the x offset (percent) in the perspective transform.\n :param off_y_range: The range of the y offset (percent) in the perspective transform.\n :param blur_kernels: The kernels to blur with.\n :param batch_size: The size of the batch used by the estimator during inference.\n \"\"\"\n super().__init__(estimator=classifier)\n self.net_size = net_size\n self.min_tr = min_tr\n self.num_xforms = num_xforms\n self.step_size = step_size\n self.steps = steps\n self.first_steps = first_steps\n self.patch_removal_size = patch_removal_size\n self.patch_removal_interval = patch_removal_interval\n self.num_patches_to_remove = num_patches_to_remove\n self.rand_start_epsilon_range = rand_start_epsilon_range\n self.rotation_range = rotation_range\n self.dist_range = dist_range\n self.gamma_range = gamma_range\n self.crop_percent_range = crop_percent_range\n self.off_x_range = off_x_range\n self.off_y_range = off_y_range\n self.blur_kernels = blur_kernels\n self.batch_size = batch_size\n\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,).\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :param pts: Optional points to consider when cropping the perspective transform.\n An array of points in [x, y, scale] with shape [num points, 3, 1].\n :param obj_width: The estimated object width (inches) for perspective transform. 30 by default.\n :param focal: The estimated focal length (ft) for perspective transform. 3 by default.\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = kwargs.get(\"mask\")\n obj_width = kwargs.get(\"obj_width\") if \"obj_width\" in kwargs else 30\n focal = kwargs.get(\"focal\") if \"focal\" in kwargs else 3\n pts = kwargs.get(\"pts\") if \"pts\" in kwargs else None\n\n if y is None:\n raise ValueError(\"Target labels `y` need to be provided.\")\n\n y = check_and_transform_label_format(y, self.estimator.nb_classes)\n\n if self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover\n raise ValueError(\n \"This attack has not yet been tested for binary classification with a single output classifier.\"\n )\n\n if not isinstance(obj_width, int) and not isinstance(obj_width, float):\n raise ValueError(\"obj_width must be int or float\")\n obj_width = float(obj_width)\n\n if not isinstance(focal, int) and not isinstance(focal, float):\n raise ValueError(\"focal must be int or float\")\n focal = float(focal)\n\n # Check the mask\n if mask is not None:\n if len(mask.shape) == len(x.shape):\n mask = mask.astype(ART_NUMPY_DTYPE)\n else:\n mask = np.array([mask.astype(ART_NUMPY_DTYPE)] * x.shape[0])\n else:\n mask = np.ones((x.shape))\n\n # Get clip_min and clip_max from the classifier or infer them from data\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n else:\n clip_min, clip_max = np.min(x), np.max(x)\n\n # Some initial setups\n x_adv = x.astype(ART_NUMPY_DTYPE)\n\n if not self.estimator.channels_first:\n x = np.transpose(x, (0, 3, 1, 2))\n x_adv = np.transpose(x_adv, (0, 3, 1, 2))\n mask = np.transpose(mask, (0, 3, 1, 2))\n\n y_pred = self.estimator.predict(\n np.transpose(\n convert_to_network(np.transpose(x_adv[0], (1, 2, 0)), self.net_size, clip_min, clip_max)[\n np.newaxis, :, :, :\n ],\n (0, 3, 1, 2),\n )\n )\n if is_probability(y_pred):\n self.use_logits = False\n else:\n self.use_logits = True\n\n # Generate the adversarial samples\n for i in range(x_adv.shape[0]):\n x_adv[i] = self._perturb(\n x=x_adv[i],\n y=y[i],\n mask=mask[i],\n obj_width=obj_width,\n focal=focal,\n clip_min=clip_min,\n clip_max=clip_max,\n pts=pts,\n )\n\n y = np.argmax(y, axis=1)\n y = to_categorical(y, self.estimator.nb_classes) # type: ignore\n\n # COMPUTE SUCCESS RATE\n x_copy = np.zeros((x.shape[0], self.net_size[1], self.net_size[0], x.shape[1]))\n x_adv_copy = np.zeros((x_adv.shape[0], self.net_size[1], self.net_size[0], x_adv.shape[1]))\n x_copy_trans = np.transpose(x, (0, 2, 3, 1))\n x_adv_copy_trans = np.transpose(x_adv, (0, 2, 3, 1))\n for i in range(x_copy.shape[0]):\n x_copy[i] = convert_to_network(x_copy_trans[i], self.net_size, clip_min, clip_max)\n x_adv_copy[i] = convert_to_network(x_adv_copy_trans[i], self.net_size, clip_min, clip_max)\n\n if self.estimator.channels_first:\n x_copy = np.transpose(x_copy, (0, 3, 1, 2))\n x_adv_copy = np.transpose(x_adv_copy, (0, 3, 1, 2))\n\n logger.info(\n \"Success rate of GRAPHITE white-box attack: %.2f%%\",\n 100\n * compute_success(\n self.estimator,\n x_copy.astype(np.float32),\n y,\n x_adv_copy.astype(np.float32),\n self.targeted,\n batch_size=self.batch_size,\n ),\n )\n\n if not self.estimator.channels_first:\n x_adv = np.transpose(x_adv, (0, 2, 3, 1))\n\n return x_adv\n\n def _eval(\n self,\n x: \"torch.Tensor\",\n x_adv: \"torch.Tensor\",\n mask: \"torch.Tensor\",\n target_label: np.ndarray,\n y_onehot: \"torch.Tensor\",\n xforms: list[tuple[float, float, float, int, float, float, float, float, float]],\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None,\n ) -> float:\n \"\"\"\n Compute transform-robustness.\n\n :param x: Original image.\n :param x_adv: Attacked image.\n :param mask: The mask.\n :param target_label: The target label.\n :param y_onehot: The target label in one hot form.\n :param xforms: Ths list of transformation parameters.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: Transform-robustness of the attack.\n \"\"\"\n import torch\n\n successes = 0\n for xform in xforms:\n with torch.no_grad():\n if len(x_adv.shape) == 3:\n x_adv = x_adv.unsqueeze(0)\n transformed_x_adv = transform_wb(x, x_adv, mask, xform, self.net_size, clip_min, clip_max, pts)\n logits, _ = self.estimator._predict_framework(transformed_x_adv.to(self.estimator.device), y_onehot)\n success = int(logits.argmax(dim=1).detach().cpu().numpy()[0] == target_label)\n successes += success\n return successes / len(xforms)\n\n def _perturb(\n self,\n x: np.ndarray,\n y: np.ndarray,\n mask: np.ndarray,\n obj_width: float,\n focal: float,\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None,\n ) -> np.ndarray:\n \"\"\"\n Internal attack function for one example.\n\n :param x: An array with one original input to be attacked.\n :param y: The target label.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param obj_width: Estimated width of object in inches for perspective transform.\n :param focal: Estimated focal length in ft for perspective transform.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: Optional. A set of points that will set the crop size in the perspective transform.\n :return: An adversarial example.\n \"\"\"\n import torch\n\n x = (x.copy() - clip_min) / (clip_max - clip_min)\n\n mask = mask / np.max(mask)\n mask = np.where(mask > 0.5, 1.0, 0.0)\n\n x_copy = x.copy()\n mask_copy = mask.copy()\n y_onehot = y.copy()\n y = np.argmax(y, axis=0)\n\n # Load victim img and starting mask.\n img = torch.tensor(x_copy, requires_grad=True, device=self.estimator.device)\n mask_tensor = torch.tensor(mask_copy, requires_grad=True, device=self.estimator.device).to(img.dtype)\n y_onehot_tensor = torch.tensor(y_onehot, requires_grad=True, device=self.estimator.device)\n\n # Load transforms.\n xforms = get_transform_params(\n self.num_xforms,\n self.rotation_range,\n self.dist_range,\n self.gamma_range,\n self.crop_percent_range,\n self.off_x_range,\n self.off_y_range,\n self.blur_kernels,\n obj_width,\n focal,\n )\n\n target_label = y\n # Attack\n rounds = 0\n transform_robustness = -1.0\n prev_attack = img.detach().clone()\n while True:\n adv_img = img.detach().clone()\n adv_img = torch.where(mask_tensor > 0.5, prev_attack, adv_img)\n rand_start = (\n torch.FloatTensor(*img.size())\n .uniform_(self.rand_start_epsilon_range[0], self.rand_start_epsilon_range[1])\n .to(adv_img.device)\n )\n adv_img = (adv_img + mask_tensor * rand_start).detach()\n adv_img = torch.clamp(adv_img, 0, 1).to(img.dtype)\n adv_img.requires_grad = True\n final_avg_grad = torch.zeros(img.size())\n\n # Do EOT adversarial attack with current mask.\n loop_length = self.steps if rounds > 0 else self.first_steps\n for _ in range(loop_length):\n avg_grad = torch.zeros(adv_img.size()).to(self.estimator.device)\n for xform in xforms:\n xform_img = transform_wb(\n img.clone().unsqueeze(0),\n adv_img.unsqueeze(0),\n mask_tensor,\n xform,\n self.net_size,\n clip_min,\n clip_max,\n pts,\n )\n\n logits, _ = self.estimator._predict_framework(xform_img.to(self.estimator.device), y_onehot_tensor)\n if self.use_logits:\n loss = torch.nn.functional.cross_entropy(\n input=logits,\n target=torch.tensor(target_label).unsqueeze(0).to(logits.device),\n reduction=\"mean\",\n )\n else:\n loss = torch.nn.functional.nll_loss(\n input=logits, target=torch.tensor(target_label).unsqueeze(0), reduction=\"mean\"\n )\n\n grad = torch.autograd.grad(loss, adv_img)[0]\n avg_grad += grad\n avg_grad /= len(xforms)\n\n avg_grad_sign = avg_grad.clone()\n avg_grad_sign = torch.sign(avg_grad_sign)\n avg_grad_sign[torch.isnan(avg_grad_sign)] = 0\n adv_img = adv_img - mask_tensor * self.step_size * avg_grad_sign\n\n adv_img = adv_img.clamp(0, 1)\n transform_robustness = self._eval(\n img.detach().clone(),\n adv_img,\n mask_tensor,\n target_label,\n y_onehot_tensor,\n xforms,\n clip_min,\n clip_max,\n pts,\n )\n final_avg_grad = avg_grad\n if transform_robustness >= self.min_tr:\n break\n\n if transform_robustness < self.min_tr:\n break\n\n prev_attack = adv_img.detach().clone()\n\n # Remove low-impact pixel-patches or pixels in mask.\n pert = adv_img - img\n final_avg_grad[torch.isnan(final_avg_grad)] = 0\n final_avg_grad = mask_tensor * final_avg_grad * pert\n pixelwise_avg_grads = torch.sum(torch.abs(final_avg_grad), dim=0)\n\n for _ in range(self.num_patches_to_remove):\n # Find minimum gradient patch and remove it.\n min_patch_grad = None\n min_patch_grad_idx = None\n for i in np.arange(\n 0, pixelwise_avg_grads.shape[0] - self.patch_removal_size + 0.0001, self.patch_removal_interval\n ):\n for j in np.arange(\n 0, pixelwise_avg_grads.shape[1] - self.patch_removal_size + 0.0001, self.patch_removal_interval\n ):\n patch_grad = pixelwise_avg_grads[\n int(round(i)) : int(round(i + self.patch_removal_size)),\n int(round(j)) : int(round(j + self.patch_removal_size)),\n ].sum()\n\n if (\n mask_tensor[\n 0,\n int(round(i)) : int(round(i + self.patch_removal_size)),\n int(round(j)) : int(round(j + self.patch_removal_size)),\n ].sum()\n > 0\n ):\n patch_grad = (\n patch_grad\n / mask_tensor[\n 0,\n int(round(i)) : int(round(i + self.patch_removal_size)),\n int(round(j)) : int(round(j + self.patch_removal_size)),\n ].sum()\n ) # TODO1\n if min_patch_grad is None or patch_grad.item() < min_patch_grad:\n min_patch_grad = patch_grad.item()\n min_patch_grad_idx = (i, j)\n if min_patch_grad_idx is None:\n break\n i, j = min_patch_grad_idx\n mask_tensor[\n 0,\n int(round(i)) : int(round(i + self.patch_removal_size)),\n int(round(j)) : int(round(j + self.patch_removal_size)),\n ] = 0\n if img.size()[0] == 3:\n mask_tensor[\n 1,\n int(round(i)) : int(round(i + self.patch_removal_size)),\n int(round(j)) : int(round(j + self.patch_removal_size)),\n ] = 0\n mask_tensor[\n 2,\n int(round(i)) : int(round(i + self.patch_removal_size)),\n int(round(j)) : int(round(j + self.patch_removal_size)),\n ] = 0\n\n rounds += 1\n\n out = prev_attack.detach().clone().cpu().numpy()\n adversarial = np.clip(out.copy() * (clip_max - clip_min) + clip_min, clip_min, clip_max)\n return adversarial\n\n def _check_params(self) -> None:\n if self.min_tr < 0 or self.min_tr > 1:\n raise ValueError(\"min_tr must be between 0 and 1.\")\n\n if self.num_xforms < 0 or not isinstance(self.num_xforms, int):\n raise ValueError(\"num_xforms must be non-negative integer.\")\n\n if self.step_size <= 0:\n raise ValueError(\"step size must be positive.\")\n\n if self.steps <= 0 or not isinstance(self.steps, int):\n raise ValueError(\"steps must be a positive integer.\")\n\n if self.first_steps <= 0 or not isinstance(self.first_steps, int):\n raise ValueError(\"first_steps must be a positive integer.\")\n\n if self.patch_removal_size <= 0:\n raise ValueError(\"patch_removal_size must be positive.\")\n\n if self.patch_removal_interval <= 0:\n raise ValueError(\"patch_removal_interval must be positive.\")\n\n if self.num_patches_to_remove <= 0 or not isinstance(self.num_patches_to_remove, int):\n raise ValueError(\"num_patches_to_remove must be a positive integer.\")\n\n if (\n self.rotation_range[0] <= -90\n or self.rotation_range[1] >= 90\n or self.rotation_range[1] < self.rotation_range[0]\n ):\n raise ValueError(\"rotation range must be within (-90, 90).\")\n\n if self.dist_range[1] < self.dist_range[0] or self.dist_range[0] < 0:\n raise ValueError(\"distance range invalid. max must be greater than min, and must be nonnegative.\")\n\n if self.gamma_range[1] < self.gamma_range[0] or self.gamma_range[0] < 1:\n raise ValueError(\"gamma range max must be greater than min and the range must be at 1.0 or greater.\")\n\n if self.crop_percent_range[1] < self.crop_percent_range[0]:\n raise ValueError(\"max of crop percent range must be greater or equal to the min.\")\n\n if self.off_x_range[1] < self.off_x_range[0]:\n raise ValueError(\"max of off x range must be greater or equal to the min.\")\n\n if self.off_y_range[1] < self.off_y_range[0]:\n raise ValueError(\"max of off y range must be greater or equal to the min.\")\n\n if min(self.blur_kernels) < 0:\n raise ValueError(\"blur kernels must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/graphite/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2022 University of Michigan and University of Wisconsin-Madison\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements helper functions for GRAPHITE attacks.\n\n| Paper link: https://arxiv.org/abs/2002.07088\n| Original GitHub link: https://github.com/ryan-feng/GRAPHITE\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nimport math\nimport numpy as np\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\nfrom art.utils import get_labels_np_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n import torch\n\n\ndef dist2pixels(dist: float, width: float, obj_width: float = 30) -> float:\n \"\"\"\n Convert distance to pixels.\n\n :param dist: Distance to object.\n :param width: Width of image.\n :param obj_width: Width of object.\n :return: Distance in pixels.\n \"\"\"\n dist_inches = dist * 12\n return 1.0 * dist_inches * width / obj_width\n\n\ndef convert_to_network(x: np.ndarray, net_size: tuple[int, int], clip_min: float, clip_max: float) -> np.ndarray:\n \"\"\"\n Convert image to network format.\n\n :param x: Input image.\n :param net_size: The resolution to resize to in (w, h).\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n \"\"\"\n import cv2\n\n if net_size is not None:\n x = cv2.resize(x, net_size)\n x = np.clip(x, 0, 1)\n x = x * (clip_max - clip_min) + clip_min\n if len(x.shape) < 3:\n x = x[:, :, np.newaxis]\n return x\n\n\ndef apply_transformation(\n x: np.ndarray,\n mask: np.ndarray,\n pert: np.ndarray,\n angle: float,\n dist: float,\n gamma: float,\n blur: int,\n crop_percent: float,\n crop_off_x: float,\n crop_off_y: float,\n net_size: tuple[int, int],\n obj_width: float,\n focal: float,\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None = None,\n) -> np.ndarray:\n \"\"\"\n Apply transformation to input image.\n\n :param x: Input image.\n :param mask: Input mask.\n :param pert: Input perturbation.\n :param angle: Angle to rotate image.\n :param dist: Distance in ft for perspective transform.\n :param gamma: Factor for gamma transform.\n :param blur: Kernel width for blurring.\n :param crop_percent: Percent to crop image at.\n :param crop_off_x: x offset for crop.\n :param crop_off_y: y offset for crop.\n :param net_size: Size of the image for the network.\n :param obj_width: Estimated width of object in inches for perspective transform.\n :param focal: Estimated focal length in ft for perspective transform.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: A set of points that will set the crop size in the perspective transform.\n :return: Transformed image in network form.\n \"\"\"\n import cv2\n\n if blur != 0:\n pert = cv2.GaussianBlur(pert, (blur, blur), 0)\n\n if len(pert.shape) < 3:\n pert = pert[:, :, np.newaxis]\n\n att = np.where(mask > 0.5, pert, x)\n att = np.clip(att, 0.0, 1.0)\n\n dist = dist2pixels(dist, att.shape[1], obj_width)\n focal = dist2pixels(focal, att.shape[1], obj_width)\n att = get_perspective_transform(\n att, angle, att.shape[1], att.shape[0], focal, dist, crop_percent, crop_off_x, crop_off_y, pts\n )\n\n if len(att.shape) < 3:\n att = att[:, :, np.newaxis]\n\n # Gamma\n att_uint = (att * 255.0).astype(np.uint8)\n table = np.empty((256), np.uint8)\n for i in range(256):\n table[i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)\n att_uint = cv2.LUT(att_uint, table) # type: ignore\n att = (att_uint / 255.0).astype(np.float32)\n att = np.clip(att, 0.0, 1.0)\n\n return convert_to_network(att, net_size, clip_min, clip_max)\n\n\ndef get_transform_params(\n num_xforms: int,\n rotation_range: tuple[float, float],\n dist_range: tuple[float, float],\n gamma_range: tuple[float, float],\n crop_percent_range: tuple[float, float],\n off_x_range: tuple[float, float],\n off_y_range: tuple[float, float],\n blur_kernels: tuple[int, int] | list[int],\n obj_width: float,\n focal: float,\n) -> list[tuple[float, float, float, int, float, float, float, float, float]]:\n \"\"\"\n Sample transformation params.\n\n :param num_xforms: The number of transforms to sample.\n :param rotation_range: The range of the rotation in the perspective transform.\n :param dist_range: The range of the distance (in ft) to be added to the focal length in perspective transform.\n :param gamma_range: The range of the gamma in the gamma transform.\n :param crop_percent_range: The range of the crop percent in the perspective transform.\n :param off_x_range: The range of the x offset (percent) in the perspective transform.\n :param off_y_range: The range of the y offset (percent) in the perspective transform.\n :param blur_kernels: The kernels to blur with.\n :param obj_width: The estimated object width (inches) for perspective transform. 30 by default.\n :param focal: The estimated focal length (ft) for perspective transform. 3 by default.\n :return: List of transforms.\n \"\"\"\n transforms = []\n for _ in range(num_xforms):\n angle = np.random.uniform(rotation_range[0], rotation_range[1])\n dist = np.random.uniform(focal + dist_range[0], focal + dist_range[1])\n gamma = np.random.uniform(gamma_range[0], gamma_range[1])\n flip_flag = np.random.uniform(0.0, 1.0)\n if int(round(flip_flag)) == 1:\n gamma = 1.0 / gamma\n\n crop_percent = np.random.uniform(crop_percent_range[0], crop_percent_range[1])\n crop_off_x = np.random.uniform(off_x_range[0], off_x_range[1])\n crop_off_y = np.random.uniform(off_y_range[0], off_y_range[1])\n blur = blur_kernels[int(math.floor(np.random.uniform(0.0, 1.0) * len(blur_kernels)))]\n xform = (angle, dist, gamma, blur, crop_percent, crop_off_x, crop_off_y, obj_width, focal)\n transforms.append(xform)\n\n return transforms\n\n\ndef add_noise(\n x: np.ndarray,\n mask: np.ndarray,\n lbd: float,\n theta: np.ndarray,\n clip: bool = True,\n) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Combines the image and noise to create a perturbed image.\n\n :param x: Input image.\n :param mask: Mask image.\n :param lbd: lambda multiplier for the perturbation.\n :param theta: The perturbation.\n :param clip: Whether to clip the perturbation.\n :return: image with perturbation, perturbation, mask\n \"\"\"\n import cv2\n\n theta_full = cv2.resize(theta, (x.shape[1], x.shape[0])).astype(float)\n if len(theta_full.shape) < 3:\n theta_full = theta_full[:, :, np.newaxis]\n comb = x + lbd * theta_full\n\n mask_full = cv2.resize(mask, (x.shape[1], x.shape[0])).astype(float)\n if len(mask_full.shape) < 3:\n mask_full = mask_full[:, :, np.newaxis]\n mask_full = np.where(mask_full > 0.5, 1.0, 0.0)\n\n if clip:\n comb = np.clip(comb, 0, 1)\n\n pert = np.where(mask_full > 0.5, comb, 0)\n return comb, pert, mask_full\n\n\ndef get_transformed_images(\n x: np.ndarray,\n mask: np.ndarray,\n xforms: list[tuple[float, float, float, int, float, float, float, float, float]],\n lbd: float,\n theta: np.ndarray,\n net_size: tuple[int, int],\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None = None,\n) -> list[np.ndarray]:\n \"\"\"\n Get transformed images.\n\n :param x: Input image.\n :param mask: Mask image.\n :param xforms: Transformation parameters.\n :param lbd: lambda multiplier for the perturbation.\n :param theta: The perturbation.\n :param net_size: Size of the image for the network.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: A set of points that will set the crop size in the perspective transform.\n :return: List of transformed images.\n \"\"\"\n att, pert, mask = add_noise(x, mask, lbd, theta, True)\n\n if len(xforms) == 0:\n return [convert_to_network(att, net_size, clip_min, clip_max)]\n\n images = []\n for xform in xforms:\n angle, dist, gamma, blur, crop_percent, crop_off_x, crop_off_y, obj_width, focal = xform\n images.append(\n apply_transformation(\n x,\n mask,\n pert,\n angle,\n dist,\n gamma,\n blur,\n crop_percent,\n crop_off_x,\n crop_off_y,\n net_size,\n obj_width,\n focal,\n clip_min,\n clip_max,\n pts,\n )\n )\n\n return images\n\n\ndef transform_wb(\n x: \"torch.Tensor\",\n x_adv: \"torch.Tensor\",\n mask: \"torch.Tensor\",\n xform: tuple[float, float, float, int, float, float, float, float, float],\n net_size: tuple[int, int],\n clip_min: float,\n clip_max: float,\n pts: np.ndarray | None,\n) -> \"torch.Tensor\":\n \"\"\"\n Get transformed image, white-box setting.\n\n :param x: Original input image.\n :param x_adv: Input image to transform, possibly attacked.\n :param mask: Mask image.\n :param xform: Transformation parameters.\n :param net_size: Size of the image for the network.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :param pts: A set of points that will set the crop size in the perspective transform.\n :return: Transformed image.\n \"\"\"\n import torch\n import cv2\n from kornia.enhance import adjust_gamma\n\n angle, dist, gamma, blur, crop_percent, crop_off_x, crop_off_y, obj_width, focal = xform\n x_adv = torch.clamp(x_adv, 0.0, 1.0)\n\n if blur != 0:\n kernel = np.zeros((blur * 2 - 1, blur * 2 - 1))\n kernel[blur - 1, blur - 1] = 1\n kernel = cv2.GaussianBlur(kernel, (blur, blur), 0).astype(float)\n kernel = kernel[blur // 2 : blur // 2 + blur, blur // 2 : blur // 2 + blur]\n kernel = kernel[np.newaxis, :, :]\n kernel = np.repeat(kernel[np.newaxis, :, :, :], x_adv.size()[1], axis=0)\n kernel_torch = torch.from_numpy(kernel)\n blur_torch = torch.nn.Conv2d(\n in_channels=x_adv.size()[1],\n out_channels=x_adv.size()[1],\n kernel_size=blur,\n groups=x_adv.size()[1],\n bias=False,\n padding=blur // 2,\n )\n blur_torch.weight.data = kernel_torch.to(x_adv.dtype)\n blur_torch.weight.requires_grad = False\n blur_torch = blur_torch.to(x_adv.device)\n # the below is done this way to match the black box implementation\n pert = torch.where(mask > 0.5, x_adv, torch.zeros(x_adv.size()).to(mask.device))\n x_adv = torch.where(mask > 0.5, blur_torch(pert), x)\n else:\n x_adv = torch.where(mask > 0.5, x_adv, x)\n\n x_adv = torch.clamp(x_adv, 0.0, 1.0)\n dist = dist2pixels(dist, x_adv.size()[2], obj_width)\n focal = dist2pixels(focal, x_adv.size()[2], obj_width)\n x_adv = get_perspective_transform_wb(\n x_adv, angle, x_adv.size()[3], x_adv.size()[2], focal, dist, crop_percent, crop_off_x, crop_off_y, pts\n )\n\n # Gamma\n x_adv = adjust_gamma(x_adv, gamma)\n\n return convert_to_network_wb(x_adv, net_size, clip_min, clip_max)\n\n\ndef convert_to_network_wb(\n x: \"torch.Tensor\", net_size: tuple[int, int], clip_min: float, clip_max: float\n) -> \"torch.Tensor\":\n \"\"\"\n Convert image to network format.\n\n :param x: Input image.\n :param net_size: Size of the image for the network.\n :param clip_min: Minimum value of an example.\n :param clip_max: Maximum value of an example.\n :return: Transformed image.\n \"\"\"\n import torch\n from kornia.geometry.transform import resize\n\n orig_device = x.device\n x = resize(x, (net_size[1], net_size[0]), align_corners=False)\n x = torch.clamp(x, 0.0, 1.0)\n x = x * (clip_max - clip_min) + clip_min\n return x.to(orig_device)\n\n\ndef get_perspective_transform(\n img: np.ndarray,\n angle: float,\n width: int,\n height: int,\n focal: float,\n dist: float,\n crop_percent: float,\n crop_off_x: float,\n crop_off_y: float,\n pts: np.ndarray | None = None,\n) -> np.ndarray:\n \"\"\"\n Computes parameters for perspective transform for blackbox attack.\n\n :param img: Input image.\n :param angle: Angle to rotate.\n :param width: Width of image.\n :param height: Height of image.\n :param focal: Focal length.\n :param dist: Distance for transform.\n :param crop_percent: Percentage for cropping.\n :param crop_off_x: Cropping x offset.\n :param crop_off_y: Cropping y offset.\n :param pts: pts to include in the crop.\n :return: Transformed image.\n \"\"\"\n import cv2\n\n perspective_mat, crop_x, crop_y = _get_perspective_transform(\n angle, width, height, focal, dist, crop_percent, crop_off_x, crop_off_y, pts\n )\n dst = cv2.warpPerspective(img, perspective_mat, (crop_x, crop_y), borderMode=cv2.BORDER_REPLICATE)\n return dst\n\n\ndef get_perspective_transform_wb(\n img: \"torch.Tensor\",\n angle: float,\n width: int,\n height: int,\n focal: float,\n dist: float,\n crop_percent: float,\n crop_off_x: float,\n crop_off_y: float,\n pts: np.ndarray | None = None,\n) -> \"torch.Tensor\":\n \"\"\"\n Computes perspective transform for whitebox attack.\n\n :param img: Input image.\n :param angle: Angle to rotate.\n :param width: Width of image.\n :param height: Height of image.\n :param focal: Focal length.\n :param dist: Distance for transform.\n :param crop_percent: Percentage for cropping.\n :param crop_off_x: Cropping x offset.\n :param crop_off_y: Cropping y offset.\n :param pts: pts to include in the crop.\n :return: Transformed image.\n \"\"\"\n import torch\n from kornia.geometry.transform import warp_perspective\n\n perspective_mat, crop_x, crop_y = _get_perspective_transform(\n angle, width, height, focal, dist, crop_percent, crop_off_x, crop_off_y, pts\n )\n dst = warp_perspective(\n img,\n torch.from_numpy(perspective_mat).float().to(img.device).unsqueeze(0),\n (crop_y, crop_x),\n align_corners=True,\n padding_mode=\"border\",\n )\n return dst\n\n\ndef _get_perspective_transform(\n angle: float,\n width: int,\n height: int,\n focal: float,\n dist: float,\n crop_percent: float,\n crop_off_x: float,\n crop_off_y: float,\n pts: np.ndarray | None = None,\n) -> tuple[np.ndarray, int, int]:\n \"\"\"\n Computes parameters for perspective transform.\n\n :param angle: Angle to rotate.\n :param width: Width of image.\n :param height: Height of image.\n :param focal: Focal length.\n :param dist: Distance for transform.\n :param crop_percent: Percentage for cropping.\n :param crop_off_x: Cropping x offset.\n :param crop_off_y: Cropping y offset.\n :param pts: pts to include in the crop.\n :return: perspective transform matrix, crop width, crop_height\n \"\"\"\n angle = math.radians(angle)\n x_cam_off = width / 2 - math.sin(angle) * dist\n z_cam_off = -math.cos(angle) * dist\n y_cam_off = height / 2\n\n rot_mat = np.array(\n [\n [math.cos(angle), 0, -math.sin(angle), 0],\n [0, 1, 0, 0],\n [math.sin(angle), 0, math.cos(angle), 0],\n [0, 0, 0, 1],\n ]\n )\n c_mat = np.array([[1, 0, 0, -x_cam_off], [0, 1, 0, -y_cam_off], [0, 0, 1, -z_cam_off], [0, 0, 0, 1]])\n\n rt_mat = np.matmul(rot_mat, c_mat)\n\n h_mat = np.array(\n [\n [focal * rt_mat[0, 0], focal * rt_mat[0, 1], focal * rt_mat[0, 3]],\n [focal * rt_mat[1, 0], focal * rt_mat[1, 1], focal * rt_mat[1, 3]],\n [rt_mat[2, 0], rt_mat[2, 1], rt_mat[2, 3]],\n ]\n )\n\n x_off, y_off, crop_size = get_offset_and_crop_size(\n width, height, h_mat, crop_percent, crop_off_x, crop_off_y, focal / dist, pts\n )\n\n affine_mat = np.array([[1, 0, x_off], [0, 1, y_off], [0, 0, 1]])\n perspective_mat = np.matmul(affine_mat, h_mat)\n\n if height > width: # tall and narrow\n crop_x = int(crop_size)\n crop_y = int(round(crop_size / width * height))\n else: # wide and short or square\n crop_y = int(crop_size)\n crop_x = int(round(crop_size / height * width))\n\n return perspective_mat, crop_x, crop_y\n\n\ndef get_offset_and_crop_size(\n width: int,\n height: int,\n h_mat: np.ndarray,\n crop_percent: float,\n crop_off_x: float,\n crop_off_y: float,\n ratio: float,\n pts: np.ndarray | None = None,\n) -> tuple[float, float, float]:\n \"\"\"\n Compute offsets and crop size for perspective transform.\n\n :param w: Width of image.\n :param h: Height of image.\n :param H: Homography matrix.\n :param crop_percent: Percentage for cropping.\n :param crop_off_x: Cropping x offset.\n :param crop_off_y: Cropping y offset.\n :param ratio: Focal length to distance ratio for scaling.\n :param pts: pts to include in the crop.\n :return: x offset, y offset, crop size.\n \"\"\"\n pts_flag = pts is not None\n if pts is not None:\n pts_copy = [point.copy() for point in pts]\n for i in range(len(pts)):\n pts_copy[i][0, 0] = pts_copy[i][0, 0] * width / pts_copy[i][2, 0]\n pts_copy[i][1, 0] = pts_copy[i][1, 0] * height / pts_copy[i][2, 0]\n pts_copy[i][2, 0] = pts_copy[i][2, 0] * 1.0 / pts_copy[i][2, 0]\n\n else:\n pts_copy = [\n np.array([[0], [0], [1.0]]),\n np.array([[0], [height], [1.0]]),\n np.array([[width], [0], [1.0]]),\n np.array([[width], [height], [1.0]]),\n ]\n\n min_x = width\n min_y = height\n max_x = 0\n max_y = 0\n\n for point in pts_copy:\n new_pt = np.matmul(h_mat, point)\n new_pt /= new_pt[2, 0]\n\n if new_pt[0, 0] < min_x:\n min_x = new_pt[0, 0]\n if new_pt[0, 0] > max_x:\n max_x = new_pt[0, 0]\n if new_pt[1, 0] < min_y:\n min_y = new_pt[1, 0]\n if new_pt[1, 0] > max_y:\n max_y = new_pt[1, 0]\n\n if pts_flag:\n if (max_x - min_x) / (max_y - min_y) < width / height: # result is tall and narrow\n diff_in_size = (max_y - min_y) / height * width - (max_x - min_x)\n orig_size = max_y - min_y if width > height else (max_y - min_y) / height * width\n crop_size = int(round(orig_size * (1.0 - crop_percent)))\n y_off = -min_y - int(round(crop_percent / 2 * orig_size))\n x_off = -min_x + int(round(diff_in_size / 2 - crop_percent / 2 * orig_size))\n\n else: # result is wide and short\n diff_in_size = (max_x - min_x) / width * height - (max_y - min_y)\n orig_size = max_x - min_x if height > width else (max_x - min_x) / width * height\n crop_size = int(round(orig_size * (1.0 - crop_percent)))\n x_off = -min_x - int(round(crop_percent / 2 * orig_size))\n y_off = -min_y + int(round(diff_in_size / 2 - crop_percent / 2 * orig_size))\n\n return x_off + crop_off_x * crop_size, y_off + crop_off_y * crop_size, crop_size\n\n min_x -= int((width * ratio - (max_x - min_x)) // 2)\n min_y -= int((height * ratio - (max_y - min_y)) // 2)\n\n crop_size = int(round((1.0 - crop_percent) * min(width, height) * ratio))\n\n return (\n -min_x - int(round(crop_percent / 2 * width * ratio)),\n -min_y - int(round(crop_percent / 2 * height * ratio)),\n crop_size,\n )\n\n\ndef run_predictions(\n estimator: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n imgs: list[np.ndarray],\n target: int,\n batch_size: int,\n err_rate: bool = True,\n) -> float:\n \"\"\"\n Run model predictions over batch of input.\n\n :param estimator: The model.\n :param imgs: Batch of images with different transforms.\n :param target: Target label.\n :param batch_size: Size of batches to process.\n :param err_rate: Whether to return a measure of error or a measure of transform-robutness.\n :return: Either the error rate or transform-robustness depending on err_rate.\n \"\"\"\n img_tensor = np.zeros((batch_size, imgs[0].shape[0], imgs[0].shape[1], imgs[0].shape[2]), dtype=np.float32)\n num_successes = 0\n tar_tensor = np.ones((batch_size)) * target\n\n count = 0\n for i, img in enumerate(imgs):\n max_y = min(img.shape[0], img_tensor.shape[1])\n max_x = min(img.shape[1], img_tensor.shape[2])\n img_tensor[count, :max_y, :max_x, :] = img[:max_y, :max_x, :]\n count += 1\n if count == batch_size or i == len(imgs) - 1:\n if count < batch_size:\n img_tensor = img_tensor[:count, :, :, :]\n tar_tensor = tar_tensor[:count]\n\n if estimator.channels_first:\n transposed = np.transpose(img_tensor, (0, 3, 1, 2))\n preds = get_labels_np_array(estimator.predict(transposed, batch_size=batch_size))\n else:\n preds = get_labels_np_array(estimator.predict(img_tensor, batch_size=batch_size))\n np_preds = np.argmax(preds)\n num_successes += (np_preds == tar_tensor).sum().item()\n count = 0\n\n return_val = (1.0 - num_successes * 1.0 / len(imgs)) if err_rate else num_successes * 1.0 / len(imgs)\n return return_val\n\n\ndef score_fn(mask: np.ndarray, tr_err: float, object_size: float, threshold: float = 0.75, lbd: float = 5):\n \"\"\"\n Mask scoring function.\n\n :param mask: The mask.\n :param tr_err: The error in transform-robustness.\n :param object_size: The size of the object.\n :param threshold: The threshold at which to heavily penalize.\n :param lbd: lambda weight multiplier.\n :return: Score of the mask.\n \"\"\"\n if tr_err > threshold:\n return 10000000\n\n return lbd * mask.sum() / 3 / (object_size) + tr_err\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/imperceptible_asr/imperceptible_asr.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the adversarial and imperceptible attack on automatic speech recognition systems of Qin et al.\n(2019). It generates an adversarial audio example.\n\n| Paper link: http://proceedings.mlr.press/v97/qin19a.html\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport scipy.signal as ss\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin, NeuralNetworkMixin\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\nfrom art.utils import pad_sequence_input\n\nif TYPE_CHECKING:\n\n from tensorflow.compat.v1 import Tensor\n from torch import Tensor as PTensor\n\n from art.utils import SPEECH_RECOGNIZER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImperceptibleASR(EvasionAttack):\n \"\"\"\n Implementation of the imperceptible attack against a speech recognition model.\n\n | Paper link: http://proceedings.mlr.press/v97/qin19a.html\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"masker\",\n \"eps\",\n \"learning_rate_1\",\n \"max_iter_1\",\n \"alpha\",\n \"learning_rate_2\",\n \"max_iter_2\",\n \"batch_size\",\n \"loss_theta_min\",\n \"decrease_factor_eps\",\n \"num_iter_decrease_eps\",\n \"increase_factor_alpha\",\n \"num_iter_increase_alpha\",\n \"decrease_factor_alpha\",\n \"num_iter_decrease_alpha\",\n ]\n\n _estimator_requirements = (NeuralNetworkMixin, LossGradientsMixin, BaseEstimator, SpeechRecognizerMixin)\n\n def __init__(\n self,\n estimator: \"SPEECH_RECOGNIZER_TYPE\",\n masker: \"PsychoacousticMasker\",\n eps: float = 2000.0,\n learning_rate_1: float = 100.0,\n max_iter_1: int = 1000,\n alpha: float = 0.05,\n learning_rate_2: float = 1.0,\n max_iter_2: int = 4000,\n loss_theta_min: float = 0.05,\n decrease_factor_eps: float = 0.8,\n num_iter_decrease_eps: int = 10,\n increase_factor_alpha: float = 1.2,\n num_iter_increase_alpha: int = 20,\n decrease_factor_alpha: float = 0.8,\n num_iter_decrease_alpha: int = 50,\n batch_size: int = 1,\n ) -> None:\n \"\"\"\n Create an instance of the :class:`.ImperceptibleASR`.\n\n The default parameters assume that audio input is in `int16` range. If using normalized audio input, parameters\n `eps` and `learning_rate_{1,2}` need to be scaled with a factor `2^-15`\n\n :param estimator: A trained speech recognition estimator.\n :param masker: A Psychoacoustic masker.\n :param eps: Initial max norm bound for adversarial perturbation.\n :param learning_rate_1: Learning rate for stage 1 of attack.\n :param max_iter_1: Number of iterations for stage 1 of attack.\n :param alpha: Initial alpha value for balancing stage 2 loss.\n :param learning_rate_2: Learning rate for stage 2 of attack.\n :param max_iter_2: Number of iterations for stage 2 of attack.\n :param loss_theta_min: If imperceptible loss reaches minimum, stop early. Works best with `batch_size=1`.\n :param decrease_factor_eps: Decrease factor for epsilon (Paper default: 0.8).\n :param num_iter_decrease_eps: Iterations after which to decrease epsilon if attack succeeds (Paper default: 10).\n :param increase_factor_alpha: Increase factor for alpha (Paper default: 1.2).\n :param num_iter_increase_alpha: Iterations after which to increase alpha if attack succeeds (Paper default: 20).\n :param decrease_factor_alpha: Decrease factor for alpha (Paper default: 0.8).\n :param num_iter_decrease_alpha: Iterations after which to decrease alpha if attack fails (Paper default: 50).\n :param batch_size: Batch size.\n \"\"\"\n\n # Super initialization\n super().__init__(estimator=estimator)\n self.masker = masker\n self.eps = eps\n self.learning_rate_1 = learning_rate_1\n self.max_iter_1 = max_iter_1\n self.alpha = alpha\n self.learning_rate_2 = learning_rate_2\n self.max_iter_2 = max_iter_2\n self._targeted = True\n self.batch_size = batch_size\n self.loss_theta_min = loss_theta_min\n self.decrease_factor_eps = decrease_factor_eps\n self.num_iter_decrease_eps = num_iter_decrease_eps\n self.increase_factor_alpha = increase_factor_alpha\n self.num_iter_increase_alpha = num_iter_increase_alpha\n self.decrease_factor_alpha = decrease_factor_alpha\n self.num_iter_decrease_alpha = num_iter_decrease_alpha\n self._check_params()\n\n # init some aliases\n self._window_size = masker.window_size\n self._hop_size = masker.hop_size\n self._sample_rate = masker.sample_rate\n\n self._framework: str | None = None\n\n if isinstance(self.estimator, TensorFlowV2Estimator):\n import tensorflow.compat.v1 as tf1\n\n # set framework attribute\n self._framework = \"tensorflow\"\n\n # disable eager execution and use tensorflow.compat.v1 API, e.g. Lingvo uses TF2v1 AP\n tf1.disable_eager_execution()\n\n # TensorFlow placeholders\n self._delta = tf1.placeholder(tf1.float32, shape=[None, None], name=\"art_delta\")\n self._power_spectral_density_maximum_tf = tf1.placeholder(tf1.float32, shape=[None], name=\"art_psd_max\")\n self._masking_threshold_tf = tf1.placeholder(\n tf1.float32, shape=[None, None, None], name=\"art_masking_threshold\"\n )\n # TensorFlow - loss gradient operations\n self._loss_gradient_masking_threshold_op_tf = self._loss_gradient_masking_threshold_tf(\n self._delta, self._power_spectral_density_maximum_tf, self._masking_threshold_tf\n )\n\n elif isinstance(self.estimator, PyTorchEstimator):\n # set framework attribute\n self._framework = \"pytorch\"\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate imperceptible, adversarial examples.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values of shape (batch_size,). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: An array holding the adversarial examples.\n \"\"\"\n if y is None:\n raise ValueError(\"The target values `y` cannot be None. Please provide a `np.ndarray` of target labels.\")\n\n nb_samples = x.shape[0]\n\n x_imperceptible = [None] * nb_samples\n\n nb_batches = int(np.ceil(nb_samples / float(self.batch_size)))\n for m in range(nb_batches):\n # batch indices\n begin, end = m * self.batch_size, min((m + 1) * self.batch_size, nb_samples)\n\n # create batch of adversarial examples\n x_imperceptible[begin:end] = self._generate_batch(x[begin:end], y[begin:end])\n\n # for ragged input, use object dtype\n dtype = np.float32 if x.ndim != 1 else object\n return np.array(x_imperceptible, dtype=dtype)\n\n def _generate_batch(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Create imperceptible, adversarial sample.\n\n This is a helper method that calls the methods to create an adversarial (`ImperceptibleASR._create_adversarial`)\n and imperceptible (`ImperceptibleASR._create_imperceptible`) example subsequently.\n \"\"\"\n # create adversarial example\n x_adversarial = self._create_adversarial(x, y)\n if self.max_iter_2 == 0:\n return x_adversarial\n\n # make adversarial example imperceptible\n x_imperceptible = self._create_imperceptible(x, x_adversarial, y)\n return x_imperceptible\n\n def _create_adversarial(self, x, y) -> np.ndarray:\n \"\"\"\n Create adversarial example with small perturbation that successfully deceives the estimator.\n\n The method implements the part of the paper by Qin et al. (2019) that is referred to as the first stage of the\n attack. The authors basically follow Carlini and Wagner (2018).\n\n | Paper link: https://arxiv.org/abs/1801.01944.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Target values of shape (batch_size,). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: An array with the adversarial outputs.\n \"\"\"\n batch_size = x.shape[0]\n\n # for ragged input, use object dtype\n dtype = np.float32 if x.ndim != 1 else object\n\n epsilon = [self.eps] * batch_size\n x_adversarial = [None] * batch_size\n\n x_perturbed = x.copy()\n\n for i in range(1, self.max_iter_1 + 1):\n # perform FGSM step for x\n gradients = self.estimator.loss_gradient(x_perturbed, y, batch_mode=True)\n x_perturbed = x_perturbed - self.learning_rate_1 * np.array([np.sign(g) for g in gradients], dtype=dtype)\n\n # clip perturbation\n perturbation = x_perturbed - x\n perturbation = np.array([np.clip(p, -e, e) for p, e in zip(perturbation, epsilon)], dtype=dtype)\n\n # re-apply clipped perturbation to x\n x_perturbed = x + perturbation\n\n if i % self.num_iter_decrease_eps == 0:\n prediction = self.estimator.predict(x_perturbed, batch_size=batch_size)\n for j in range(batch_size):\n # validate adversarial target, i.e. f(x_perturbed)=y\n if prediction[j] == y[j].upper():\n # decrease max norm bound epsilon\n perturbation_norm = np.max(np.abs(perturbation[j]))\n if epsilon[j] > perturbation_norm:\n epsilon[j] = perturbation_norm\n epsilon[j] *= self.decrease_factor_eps\n # save current best adversarial example\n x_adversarial[j] = x_perturbed[j]\n logger.info(\"Current iteration %s, epsilon %s\", i, epsilon)\n\n # return perturbed x if no adversarial example found\n for j in range(batch_size):\n if x_adversarial[j] is None:\n logger.critical(\"Adversarial attack stage 1 for x_%s was not successful\", j)\n x_adversarial[j] = x_perturbed[j]\n\n return np.array(x_adversarial, dtype=dtype)\n\n def _create_imperceptible(self, x: np.ndarray, x_adversarial: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Create imperceptible, adversarial example with small perturbation.\n\n This method implements the part of the paper by Qin et al. (2019) that is described as the second stage of the\n attack. The resulting adversarial audio samples are able to successfully deceive the ASR estimator and are\n imperceptible to the human ear.\n\n :param x: An array with the original inputs to be attacked.\n :param x_adversarial: An array with the adversarial examples.\n :param y: Target values of shape (batch_size,). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: An array with the imperceptible, adversarial outputs.\n \"\"\"\n batch_size = x.shape[0]\n alpha_min = 0.0005\n\n # for ragged input, use object dtype\n dtype = np.float32 if x.ndim != 1 else object\n\n early_stop = [False] * batch_size\n\n alpha = np.array([self.alpha] * batch_size, dtype=np.float32)\n loss_theta_previous = [np.inf] * batch_size\n x_imperceptible = [None] * batch_size\n # if inputs are *not* ragged, we can't multiply alpha * gradients_theta\n if x.ndim != 1:\n alpha = np.expand_dims(alpha, axis=-1)\n\n masking_threshold, psd_maximum = self._stabilized_threshold_and_psd_maximum(x)\n\n x_perturbed = x_adversarial.copy()\n\n for i in range(1, self.max_iter_2 + 1):\n # get perturbation\n perturbation = x_perturbed - x\n\n # get loss gradients of both losses\n gradients_net = self.estimator.loss_gradient(x_perturbed, y, batch_mode=True)\n gradients_theta, loss_theta = self._loss_gradient_masking_threshold(\n perturbation, x, masking_threshold, psd_maximum\n )\n\n # check shapes match, otherwise unexpected errors can occur\n assert gradients_net.shape == gradients_theta.shape\n\n # perform gradient descent steps\n x_perturbed = x_perturbed - self.learning_rate_2 * (gradients_net + alpha * gradients_theta)\n\n if i % self.num_iter_increase_alpha == 0 or i % self.num_iter_decrease_alpha == 0:\n prediction = self.estimator.predict(x_perturbed, batch_size=batch_size)\n for j in range(batch_size):\n # validate if adversarial target succeeds, i.e. f(x_perturbed)=y\n if i % self.num_iter_increase_alpha == 0 and prediction[j] == y[j].upper():\n # increase alpha\n alpha[j] *= self.increase_factor_alpha\n # save current best imperceptible, adversarial example\n if loss_theta[j] < loss_theta_previous[j]:\n x_imperceptible[j] = x_perturbed[j]\n loss_theta_previous[j] = loss_theta[j]\n\n # validate if adversarial target fails, i.e. f(x_perturbed)!=y\n if i % self.num_iter_decrease_alpha == 0 and prediction[j] != y[j].upper():\n # decrease alpha\n alpha[j] = max(alpha[j] * self.decrease_factor_alpha, alpha_min)\n logger.info(\"Current iteration %s, alpha %s, loss theta %s\", i, alpha, loss_theta)\n\n # note: avoids nan values in loss theta, which can occur when loss converges to zero.\n for j in range(batch_size):\n if loss_theta[j] < self.loss_theta_min and not early_stop[j]:\n logger.warning(\n \"Batch sample %s reached minimum threshold of %s for theta loss.\", j, self.loss_theta_min\n )\n early_stop[j] = True\n if all(early_stop):\n logger.warning(\n \"All batch samples reached minimum threshold for theta loss. Stopping early at iteration %s.\", i\n )\n break\n\n # return perturbed x if no adversarial example found\n for j in range(batch_size):\n if x_imperceptible[j] is None:\n logger.critical(\"Adversarial attack stage 2 for x_%s was not successful\", j)\n x_imperceptible[j] = x_perturbed[j]\n\n return np.array(x_imperceptible, dtype=dtype)\n\n def _stabilized_threshold_and_psd_maximum(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Return batch of stabilized masking thresholds and PSD maxima.\n\n :param x: An array with the original inputs to be attacked.\n :return: Tuple consisting of stabilized masking thresholds and PSD maxima.\n \"\"\"\n masking_threshold = []\n psd_maximum = []\n x_padded, _ = pad_sequence_input(x)\n\n for x_i in x_padded:\n m_t, p_m = self.masker.calculate_threshold_and_psd_maximum(x_i)\n masking_threshold.append(m_t)\n psd_maximum.append(p_m)\n # stabilize imperceptible loss by canceling out the \"10*log\" term in power spectral density maximum and\n # masking threshold\n masking_threshold_stabilized = 10 ** (np.array(masking_threshold) * 0.1)\n psd_maximum_stabilized = 10 ** (np.array(psd_maximum) * 0.1)\n return masking_threshold_stabilized, psd_maximum_stabilized\n\n def _loss_gradient_masking_threshold(\n self,\n perturbation: np.ndarray,\n x: np.ndarray,\n masking_threshold_stabilized: np.ndarray,\n psd_maximum_stabilized: np.ndarray,\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Compute loss gradient of the global masking threshold w.r.t. the PSD approximate of the perturbation.\n\n The loss is defined as the hinge loss w.r.t. to the frequency masking threshold of the original audio input `x`\n and the normalized power spectral density estimate of the perturbation. In order to stabilize the optimization\n problem during back-propagation, the `10*log`-terms are canceled out.\n\n :param perturbation: Adversarial perturbation.\n :param x: An array with the original inputs to be attacked.\n :param masking_threshold_stabilized: Stabilized masking threshold for the original input `x`.\n :param psd_maximum_stabilized: Stabilized maximum across frames, i.e. shape is `(batch_size, frame_length)`, of\n the original unnormalized PSD of `x`.\n :return: Tuple consisting of the loss gradient, which has same shape as `perturbation`, and loss value.\n \"\"\"\n # pad input\n perturbation_padded, delta_mask = pad_sequence_input(perturbation)\n\n if self._framework == \"tensorflow\":\n # get loss gradients (TensorFlow)\n feed_dict = {\n self._delta: perturbation_padded,\n self._power_spectral_density_maximum_tf: psd_maximum_stabilized,\n self._masking_threshold_tf: masking_threshold_stabilized,\n }\n\n gradients_padded, loss = self.estimator._sess.run(self._loss_gradient_masking_threshold_op_tf, feed_dict)\n elif self._framework == \"pytorch\":\n # get loss gradients (TensorFlow)\n gradients_padded, loss = self._loss_gradient_masking_threshold_torch(\n perturbation_padded, psd_maximum_stabilized, masking_threshold_stabilized\n )\n else:\n raise NotImplementedError\n\n # undo padding, i.e. change gradients shape from (nb_samples, max_length) to (nb_samples)\n lengths = delta_mask.sum(axis=1)\n gradients = []\n for gradient_padded, length in zip(gradients_padded, lengths):\n gradient = gradient_padded[:length]\n gradients.append(gradient)\n\n # for ragged input, use object dtype\n dtype = np.float32 if x.ndim != 1 else object\n return np.array(gradients, dtype=dtype), loss\n\n def _loss_gradient_masking_threshold_tf(\n self, perturbation: \"Tensor\", psd_maximum_stabilized: \"Tensor\", masking_threshold_stabilized: \"Tensor\"\n ) -> \"Tensor\" | \"Tensor\":\n \"\"\"\n Compute loss gradient of the masking threshold loss in TensorFlow.\n\n Note that the PSD maximum and masking threshold are required to be stabilized, i.e. have the `10*log10`-term\n canceled out. Following Qin et al. (2019) this mitigates optimization instabilities.\n\n :param perturbation: Adversarial perturbation.\n :param psd_maximum_stabilized: Stabilized maximum across frames, i.e. shape is `(batch_size, frame_length)`, of\n the original unnormalized PSD of `x`.\n :param masking_threshold_stabilized: Stabilized masking threshold for the original input `x`.\n :return: Approximate PSD tensor of shape `(batch_size, window_size // 2 + 1, frame_length)`.\n \"\"\"\n import tensorflow.compat.v1 as tf1\n\n # calculate approximate power spectral density\n psd_perturbation = self._approximate_power_spectral_density_tf(perturbation, psd_maximum_stabilized)\n\n # calculate hinge loss\n loss = tf1.reduce_mean(\n tf1.nn.relu(psd_perturbation - masking_threshold_stabilized), axis=[1, 2], keepdims=False\n )\n\n # compute loss gradient\n loss_gradient = tf1.gradients(loss, [perturbation])[0]\n return loss_gradient, loss\n\n def _loss_gradient_masking_threshold_torch(\n self, perturbation: np.ndarray, psd_maximum_stabilized: np.ndarray, masking_threshold_stabilized: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Compute loss gradient of the masking threshold loss in PyTorch.\n\n See also `ImperceptibleASR._loss_gradient_masking_threshold_tf`.\n \"\"\"\n import torch\n\n # define tensors\n\n perturbation_torch = torch.from_numpy(perturbation).to(self.estimator._device)\n masking_threshold_stabilized_torch = torch.from_numpy(masking_threshold_stabilized).to(self.estimator._device)\n psd_maximum_stabilized_torch = torch.from_numpy(psd_maximum_stabilized).to(self.estimator._device)\n\n # track gradient of perturbation\n perturbation_torch.requires_grad = True\n\n # calculate approximate power spectral density\n psd_perturbation = self._approximate_power_spectral_density_torch(\n perturbation_torch, psd_maximum_stabilized_torch\n )\n\n # calculate hinge loss\n loss = torch.mean( # type: ignore\n torch.nn.functional.relu(psd_perturbation - masking_threshold_stabilized_torch), dim=(1, 2), keepdims=False\n )\n\n # compute loss gradient\n loss.sum().backward()\n if perturbation_torch.grad is not None:\n loss_gradient = perturbation_torch.grad.cpu().numpy()\n else:\n raise ValueError(\"Gradient tensor in PyTorch model is `None`.\")\n loss_value = loss.detach().cpu().numpy()\n\n return loss_gradient, loss_value\n\n def _approximate_power_spectral_density_tf(\n self, perturbation: \"Tensor\", psd_maximum_stabilized: \"Tensor\"\n ) -> \"Tensor\":\n \"\"\"\n Approximate the power spectral density for a perturbation `perturbation` in TensorFlow.\n\n Note that a stabilized PSD approximate is returned, where the `10*log10`-term has been canceled out.\n Following Qin et al. (2019) this mitigates optimization instabilities.\n\n :param perturbation: Adversarial perturbation.\n :param psd_maximum_stabilized: Stabilized maximum across frames, i.e. shape is `(batch_size, frame_length)`, of\n the original unnormalized PSD of `x`.\n :return: Approximate PSD tensor of shape `(batch_size, window_size // 2 + 1, frame_length)`.\n \"\"\"\n import tensorflow.compat.v1 as tf1\n\n # compute short-time Fourier transform (STFT)\n stft_matrix = tf1.signal.stft(perturbation, self._window_size, self._hop_size, fft_length=self._window_size)\n\n # compute power spectral density (PSD)\n # note: fixes implementation of Qin et al. by also considering the square root of gain_factor\n gain_factor = np.sqrt(8.0 / 3.0)\n psd_matrix = tf1.square(tf1.abs(gain_factor * stft_matrix / self._window_size))\n\n # approximate normalized psd: psd_matrix_approximated = 10^((96.0 - psd_matrix_max + psd_matrix)/10)\n psd_matrix_approximated = tf1.pow(10.0, 9.6) / tf1.reshape(psd_maximum_stabilized, [-1, 1, 1]) * psd_matrix\n\n # return PSD matrix such that shape is (batch_size, window_size // 2 + 1, frame_length)\n return tf1.transpose(psd_matrix_approximated, [0, 2, 1])\n\n def _approximate_power_spectral_density_torch(\n self, perturbation: \"PTensor\", psd_maximum_stabilized: \"PTensor\"\n ) -> \"PTensor\":\n \"\"\"\n Approximate the power spectral density for a perturbation `perturbation` in PyTorch.\n\n See also `ImperceptibleASR._approximate_power_spectral_density_tf`.\n \"\"\"\n import torch\n\n # compute short-time Fourier transform (STFT)\n\n stft_matrix = torch.view_as_real(\n torch.stft(\n perturbation,\n n_fft=self._window_size,\n hop_length=self._hop_size,\n win_length=self._window_size,\n center=False,\n window=torch.hann_window(self._window_size).to(self.estimator._device),\n return_complex=True,\n ).to(self.estimator._device)\n )\n\n # compute power spectral density (PSD)\n # note: fixes implementation of Qin et al. by also considering the square root of gain_factor\n gain_factor = np.sqrt(8.0 / 3.0)\n stft_matrix_abs = torch.sqrt(torch.sum(torch.square(gain_factor * stft_matrix / self._window_size), -1))\n psd_matrix = torch.square(stft_matrix_abs)\n\n # approximate normalized psd: psd_matrix_approximated = 10^((96.0 - psd_matrix_max + psd_matrix)/10)\n psd_matrix_approximated = pow(10.0, 9.6) / psd_maximum_stabilized.reshape(-1, 1, 1) * psd_matrix\n\n # return PSD matrix such that shape is (batch_size, window_size // 2 + 1, frame_length)\n return psd_matrix_approximated\n\n def _check_params(self) -> None:\n \"\"\"\n Apply attack-specific checks.\n \"\"\"\n if self.eps <= 0:\n raise ValueError(\"The perturbation max norm bound `eps` has to be positive.\")\n\n if not isinstance(self.alpha, float):\n raise ValueError(\"The value of alpha must be of type float.\")\n if self.alpha <= 0.0:\n raise ValueError(\"The value of alpha must be positive\")\n\n if not isinstance(self.max_iter_1, int):\n raise ValueError(\"The maximum number of iterations for stage 1 must be of type int.\")\n if self.max_iter_1 <= 0:\n raise ValueError(\"The maximum number of iterations for stage 1 must be greater than 0.\")\n\n if not isinstance(self.max_iter_2, int):\n raise ValueError(\"The maximum number of iterations for stage 2 must be of type int.\")\n if self.max_iter_2 < 0:\n raise ValueError(\"The maximum number of iterations for stage 2 must be non-negative.\")\n\n if not isinstance(self.learning_rate_1, float):\n raise ValueError(\"The learning rate for stage 1 must be of type float.\")\n if self.learning_rate_1 <= 0.0:\n raise ValueError(\"The learning rate for stage 1 must be greater than 0.0.\")\n\n if not isinstance(self.learning_rate_2, float):\n raise ValueError(\"The learning rate for stage 2 must be of type float.\")\n if self.learning_rate_2 <= 0.0:\n raise ValueError(\"The learning rate for stage 2 must be greater than 0.0.\")\n\n if not isinstance(self.loss_theta_min, float):\n raise ValueError(\"The loss_theta_min threshold must be of type float.\")\n\n if not isinstance(self.decrease_factor_eps, float):\n raise ValueError(\"The factor to decrease eps must be of type float.\")\n if self.decrease_factor_eps <= 0.0:\n raise ValueError(\"The factor to decrease eps must be greater than 0.0.\")\n\n if not isinstance(self.num_iter_decrease_eps, int):\n raise ValueError(\"The number of iterations must be of type int.\")\n if self.num_iter_decrease_eps <= 0:\n raise ValueError(\"The number of iterations must be greater than 0.\")\n\n if not isinstance(self.num_iter_decrease_alpha, int):\n raise ValueError(\"The number of iterations must be of type int.\")\n if self.num_iter_decrease_alpha <= 0:\n raise ValueError(\"The number of iterations must be greater than 0.\")\n\n if not isinstance(self.increase_factor_alpha, float):\n raise ValueError(\"The factor to increase alpha must be of type float.\")\n if self.increase_factor_alpha <= 0.0:\n raise ValueError(\"The factor to increase alpha must be greater than 0.0.\")\n\n if not isinstance(self.num_iter_increase_alpha, int):\n raise ValueError(\"The number of iterations must be of type int.\")\n if self.num_iter_increase_alpha <= 0:\n raise ValueError(\"The number of iterations must be greater than 0.\")\n\n if not isinstance(self.decrease_factor_alpha, float):\n raise ValueError(\"The factor to decrease alpha must be of type float.\")\n if self.decrease_factor_alpha <= 0.0:\n raise ValueError(\"The factor to decrease alpha must be greater than 0.0.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n\nclass PsychoacousticMasker:\n \"\"\"\n Implements psychoacoustic model of Lin and Abdulla (2015) following Qin et al. (2019) simplifications.\n\n | Paper link: Lin and Abdulla (2015), https://www.springer.com/gp/book/9783319079738\n | Paper link: Qin et al. (2019), http://proceedings.mlr.press/v97/qin19a.html\n \"\"\"\n\n def __init__(self, window_size: int = 2048, hop_size: int = 512, sample_rate: int = 16000) -> None:\n \"\"\"\n Initialization.\n\n :param window_size: Length of the window. The number of STFT rows is `(window_size // 2 + 1)`.\n :param hop_size: Number of audio samples between adjacent STFT columns.\n :param sample_rate: Sampling frequency of audio inputs.\n \"\"\"\n self._window_size = window_size\n self._hop_size = hop_size\n self._sample_rate = sample_rate\n\n # init some private properties for lazy loading\n self._fft_frequencies: np.ndarray | None = None\n self._bark: np.ndarray | None = None\n self._absolute_threshold_hearing: np.ndarray | None = None\n\n def calculate_threshold_and_psd_maximum(self, audio: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Compute the global masking threshold for an audio input and also return its maximum power spectral density.\n\n This method is the main method to call in order to obtain global masking thresholds for an audio input. It also\n returns the maximum power spectral density (PSD) for each frame. Given an audio input, the following steps are\n performed:\n\n 1. STFT analysis and sound pressure level normalization\n 2. Identification and filtering of maskers\n 3. Calculation of individual masking thresholds\n 4. Calculation of global masking thresholds\n\n :param audio: Audio samples of shape `(length,)`.\n :return: Global masking thresholds of shape `(window_size // 2 + 1, frame_length)` and the PSD maximum for each\n frame of shape `(frame_length)`.\n \"\"\"\n psd_matrix, psd_max = self.power_spectral_density(audio)\n threshold = np.zeros_like(psd_matrix)\n for frame in range(psd_matrix.shape[1]):\n # apply methods for finding and filtering maskers\n maskers, masker_idx = self.filter_maskers(*self.find_maskers(psd_matrix[:, frame]))\n # apply methods for calculating global threshold\n threshold[:, frame] = self.calculate_global_threshold(\n self.calculate_individual_threshold(maskers, masker_idx)\n )\n return threshold, psd_max\n\n @property\n def window_size(self) -> int:\n \"\"\"\n :return: Window size of the masker.\n \"\"\"\n return self._window_size\n\n @property\n def hop_size(self) -> int:\n \"\"\"\n :return: Hop size of the masker.\n \"\"\"\n return self._hop_size\n\n @property\n def sample_rate(self) -> int:\n \"\"\"\n :return: Sample rate of the masker.\n \"\"\"\n return self._sample_rate\n\n @property\n def fft_frequencies(self) -> np.ndarray:\n \"\"\"\n :return: Discrete fourier transform sample frequencies.\n \"\"\"\n if self._fft_frequencies is None:\n self._fft_frequencies = np.linspace(0, self.sample_rate / 2, self.window_size // 2 + 1)\n return self._fft_frequencies\n\n @property\n def bark(self) -> np.ndarray:\n \"\"\"\n :return: Bark scale for discrete fourier transform sample frequencies.\n \"\"\"\n if self._bark is None:\n self._bark = 13 * np.arctan(0.00076 * self.fft_frequencies) + 3.5 * np.arctan(\n np.square(self.fft_frequencies / 7500.0)\n )\n return self._bark\n\n @property\n def absolute_threshold_hearing(self) -> np.ndarray:\n \"\"\"\n :return: Absolute threshold of hearing (ATH) for discrete fourier transform sample frequencies.\n \"\"\"\n if self._absolute_threshold_hearing is None:\n # ATH applies only to frequency range 20Hz<=f<=20kHz\n # note: deviates from Qin et al. implementation by using the Hz range as valid domain\n valid_domain = np.logical_and(20 <= self.fft_frequencies, self.fft_frequencies <= 2e4)\n freq = self.fft_frequencies[valid_domain] * 0.001\n\n # outside valid ATH domain, set values to -np.inf\n # note: This ensures that every possible masker in the bins <=20Hz is valid. As a consequence, the global\n # masking threshold formula will always return a value different to np.inf\n self._absolute_threshold_hearing = np.ones(valid_domain.shape) * -np.inf\n\n self._absolute_threshold_hearing[valid_domain] = (\n 3.64 * pow(freq, -0.8) - 6.5 * np.exp(-0.6 * np.square(freq - 3.3)) + 0.001 * pow(freq, 4) - 12\n )\n return self._absolute_threshold_hearing\n\n def power_spectral_density(self, audio: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Compute the power spectral density matrix for an audio input.\n\n :param audio: Audio sample of shape `(length,)`.\n :return: PSD matrix of shape `(window_size // 2 + 1, frame_length)` and maximum vector of shape\n `(frame_length)`.\n \"\"\"\n import librosa\n\n # compute short-time Fourier transform (STFT)\n audio_float = audio.astype(np.float32)\n stft_params = {\n \"n_fft\": self.window_size,\n \"hop_length\": self.hop_size,\n \"win_length\": self.window_size,\n \"window\": ss.get_window(\"hann\", self.window_size, fftbins=True),\n \"center\": False,\n }\n stft_matrix = librosa.core.stft(audio_float, **stft_params)\n\n # compute power spectral density (PSD)\n with np.errstate(divide=\"ignore\"):\n gain_factor = np.sqrt(8.0 / 3.0)\n psd_matrix = 20 * np.log10(np.abs(gain_factor * stft_matrix / self.window_size))\n psd_matrix = psd_matrix.clip(min=-200)\n\n # normalize PSD at 96dB\n psd_matrix_max = np.max(psd_matrix)\n psd_matrix_normalized = 96.0 - psd_matrix_max + psd_matrix\n\n return psd_matrix_normalized, psd_matrix_max\n\n @staticmethod\n def find_maskers(psd_vector: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Identify maskers.\n\n Possible maskers are local PSD maxima. Following Qin et al., all maskers are treated as tonal. Thus neglecting\n the nontonal type.\n\n :param psd_vector: PSD vector of shape `(window_size // 2 + 1)`.\n :return: Possible PSD maskers and indices.\n \"\"\"\n # identify maskers. For simplification, it is assumed that all maskers are tonal (vs. nontonal).\n masker_idx = ss.argrelmax(psd_vector)[0]\n\n # smooth maskers with their direct neighbors\n psd_maskers = 10 * np.log10(np.sum([10 ** (psd_vector[masker_idx + i] / 10) for i in range(-1, 2)], axis=0))\n return psd_maskers, masker_idx\n\n def filter_maskers(self, maskers: np.ndarray, masker_idx: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Filter maskers.\n\n First, discard all maskers that are below the absolute threshold of hearing. Second, reduce pairs of maskers\n that are within 0.5 bark distance of each other by keeping the larger masker.\n\n :param maskers: Masker PSD values.\n :param masker_idx: Masker indices.\n :return: Filtered PSD maskers and indices.\n \"\"\"\n # filter on the absolute threshold of hearing\n # note: deviates from Qin et al. implementation by filtering first on ATH and only then on bark distance\n ath_condition = maskers > self.absolute_threshold_hearing[masker_idx]\n masker_idx = masker_idx[ath_condition]\n maskers = maskers[ath_condition]\n\n # filter on the bark distance\n bark_condition = np.ones(masker_idx.shape, dtype=bool)\n i_prev = 0\n for i in range(1, len(masker_idx)):\n # find pairs of maskers that are within 0.5 bark distance of each other\n if self.bark[i] - self.bark[i_prev] < 0.5:\n # discard the smaller masker\n i_todelete, i_prev = (i_prev, i_prev + 1) if maskers[i_prev] < maskers[i] else (i, i_prev)\n bark_condition[i_todelete] = False\n else:\n i_prev = i\n masker_idx = masker_idx[bark_condition]\n maskers = maskers[bark_condition]\n\n return maskers, masker_idx\n\n def calculate_individual_threshold(self, maskers: np.ndarray, masker_idx: np.ndarray) -> np.ndarray:\n \"\"\"\n Calculate individual masking threshold with frequency denoted at bark scale.\n\n :param maskers: Masker PSD values.\n :param masker_idx: Masker indices.\n :return: Individual threshold vector of shape `(window_size // 2 + 1)`.\n \"\"\"\n delta_shift = -6.025 - 0.275 * self.bark\n threshold = np.zeros(masker_idx.shape + self.bark.shape)\n # TODO reduce for loop\n for k, (masker_j, masker) in enumerate(zip(masker_idx, maskers)):\n # critical band rate of the masker\n z_j = self.bark[masker_j]\n # distance maskees to masker in bark\n delta_z = self.bark - z_j\n # define two-slope spread function:\n # if delta_z <= 0, spread_function = 27*delta_z\n # if delta_z > 0, spread_function = [-27+0.37*max(PSD_masker-40,0]*delta_z\n spread_function = 27 * delta_z\n spread_function[delta_z > 0] = (-27 + 0.37 * max(masker - 40, 0)) * delta_z[delta_z > 0]\n\n # calculate threshold\n threshold[k, :] = masker + delta_shift[masker_j] + spread_function\n return threshold\n\n def calculate_global_threshold(self, individual_threshold):\n \"\"\"\n Calculate global masking threshold.\n\n :param individual_threshold: Individual masking threshold vector.\n :return: Global threshold vector of shape `(window_size // 2 + 1)`.\n \"\"\"\n # note: deviates from Qin et al. implementation by taking the log of the summation, which they do for numerical\n # stability of the stage 2 optimization. We stabilize the optimization in the loss itself.\n with np.errstate(divide=\"ignore\"):\n return 10 * np.log10(\n np.sum(10 ** (individual_threshold / 10), axis=0) + 10 ** (self.absolute_threshold_hearing / 10)\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/imperceptible_asr/imperceptible_asr_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the imperceptible, robust, and targeted attack to generate adversarial examples for automatic\nspeech recognition models. This attack will be implemented specifically for DeepSpeech model and is framework dependent,\nspecifically for PyTorch.\n\n| Paper link: https://arxiv.org/abs/1903.10346\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport scipy\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin\nfrom art.estimators.speech_recognition.speech_recognizer import PytorchSpeechRecognizerMixin\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImperceptibleASRPyTorch(EvasionAttack):\n \"\"\"\n This class implements the imperceptible, robust, and targeted attack to generate adversarial examples for automatic\n speech recognition models. This attack will be implemented specifically for DeepSpeech model and is framework\n dependent, specifically for PyTorch.\n\n | Paper link: https://arxiv.org/abs/1903.10346\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"eps\",\n \"max_iter_1\",\n \"max_iter_2\",\n \"learning_rate_1\",\n \"learning_rate_2\",\n \"optimizer_1\",\n \"optimizer_2\",\n \"global_max_length\",\n \"initial_rescale\",\n \"decrease_factor_eps\",\n \"num_iter_decrease_eps\",\n \"alpha\",\n \"increase_factor_alpha\",\n \"num_iter_increase_alpha\",\n \"decrease_factor_alpha\",\n \"num_iter_decrease_alpha\",\n \"win_length\",\n \"hop_length\",\n \"n_fft\",\n \"batch_size\",\n \"use_amp\",\n \"opt_level\",\n ]\n\n _estimator_requirements = (\n PytorchSpeechRecognizerMixin,\n SpeechRecognizerMixin,\n PyTorchEstimator,\n )\n\n def __init__(\n self,\n estimator: PyTorchDeepSpeech,\n eps: float = 0.05,\n max_iter_1: int = 10,\n max_iter_2: int = 4000,\n learning_rate_1: float = 0.001,\n learning_rate_2: float = 5e-4,\n optimizer_1: \"torch.optim.Optimizer\" | None = None,\n optimizer_2: \"torch.optim.Optimizer\" | None = None,\n global_max_length: int = 200000,\n initial_rescale: float = 1.0,\n decrease_factor_eps: float = 0.8,\n num_iter_decrease_eps: int = 1,\n alpha: float = 1.2,\n increase_factor_alpha: float = 1.2,\n num_iter_increase_alpha: int = 20,\n decrease_factor_alpha: float = 0.8,\n num_iter_decrease_alpha: int = 20,\n win_length: int = 2048,\n hop_length: int = 512,\n n_fft: int = 2048,\n batch_size: int = 32,\n use_amp: bool = False,\n opt_level: str = \"O1\",\n ):\n \"\"\"\n Create a :class:`.ImperceptibleASRPyTorch` instance.\n\n :param estimator: A trained estimator.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param max_iter_1: The maximum number of iterations applied for the first stage of the optimization of the\n attack.\n :param max_iter_2: The maximum number of iterations applied for the second stage of the optimization of the\n attack.\n :param learning_rate_1: The learning rate applied for the first stage of the optimization of the attack.\n :param learning_rate_2: The learning rate applied for the second stage of the optimization of the attack.\n :param optimizer_1: The optimizer applied for the first stage of the optimization of the attack. If `None`\n attack will use `torch.optim.Adam`.\n :param optimizer_2: The optimizer applied for the second stage of the optimization of the attack. If `None`\n attack will use `torch.optim.Adam`.\n :param global_max_length: The length of the longest audio signal allowed by this attack.\n :param initial_rescale: Initial rescale coefficient to speed up the decrease of the perturbation size during\n the first stage of the optimization of the attack.\n :param decrease_factor_eps: The factor to adjust the rescale coefficient during the first stage of the\n optimization of the attack.\n :param num_iter_decrease_eps: Number of iterations to adjust the rescale coefficient, and therefore adjust the\n perturbation size.\n :param alpha: Value of the alpha coefficient used in the second stage of the optimization of the attack.\n :param increase_factor_alpha: The factor to increase the alpha coefficient used in the second stage of the\n optimization of the attack.\n :param num_iter_increase_alpha: Number of iterations to increase alpha.\n :param decrease_factor_alpha: The factor to decrease the alpha coefficient used in the second stage of the\n optimization of the attack.\n :param num_iter_decrease_alpha: Number of iterations to decrease alpha.\n :param win_length: Length of the window. The number of STFT rows is `(win_length // 2 + 1)`.\n :param hop_length: Number of audio samples between adjacent STFT columns.\n :param n_fft: FFT window size.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param use_amp: Whether to use the automatic mixed precision tool to enable mixed precision training or\n gradient computation, e.g. with loss gradient computation. When set to True, this option is\n only triggered if there are GPUs available.\n :param opt_level: Specify a pure or mixed precision optimization level. Used when use_amp is True. Accepted\n values are `O0`, `O1`, `O2`, and `O3`.\n \"\"\"\n import torch\n from torch.autograd import Variable\n\n super().__init__(estimator=estimator)\n\n # Set attack attributes\n self._targeted = True\n self.eps = eps\n self.max_iter_1 = max_iter_1\n self.max_iter_2 = max_iter_2\n self.learning_rate_1 = learning_rate_1\n self.learning_rate_2 = learning_rate_2\n self.global_max_length = global_max_length\n self.initial_rescale = initial_rescale\n self.decrease_factor_eps = decrease_factor_eps\n self.num_iter_decrease_eps = num_iter_decrease_eps\n self.alpha = alpha\n self.increase_factor_alpha = increase_factor_alpha\n self.num_iter_increase_alpha = num_iter_increase_alpha\n self.decrease_factor_alpha = decrease_factor_alpha\n self.num_iter_decrease_alpha = num_iter_decrease_alpha\n self.win_length = win_length\n self.hop_length = hop_length\n self.n_fft = n_fft\n self.batch_size = batch_size\n self._use_amp = use_amp\n self._check_params()\n\n # Create the main variable to optimize\n if self.estimator.device.type == \"cpu\":\n self.global_optimal_delta = Variable(\n torch.zeros(self.batch_size, self.global_max_length).type(torch.FloatTensor), # type: ignore\n requires_grad=True,\n )\n else:\n self.global_optimal_delta = Variable(\n torch.zeros(self.batch_size, self.global_max_length).type(torch.cuda.FloatTensor), # type: ignore\n requires_grad=True,\n )\n\n self.global_optimal_delta.to(self.estimator.device)\n\n # Create the optimizers\n self._optimizer_arg_1 = optimizer_1\n if self._optimizer_arg_1 is None:\n self.optimizer_1 = torch.optim.Adam(params=[self.global_optimal_delta], lr=self.learning_rate_1)\n else:\n self.optimizer_1 = self._optimizer_arg_1( # type: ignore\n params=[self.global_optimal_delta], lr=self.learning_rate_1\n )\n\n self._optimizer_arg_2 = optimizer_2\n if self._optimizer_arg_2 is None:\n self.optimizer_2 = torch.optim.Adam(params=[self.global_optimal_delta], lr=self.learning_rate_2)\n else:\n self.optimizer_2 = self._optimizer_arg_2( # type: ignore\n params=[self.global_optimal_delta], lr=self.learning_rate_2\n )\n\n # Setup for AMP use\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n if self.estimator.device.type == \"cpu\":\n enabled = False\n else:\n enabled = True\n\n self.estimator._model, [self.optimizer_1, self.optimizer_2] = amp.initialize(\n models=self.estimator._model,\n optimizers=[self.optimizer_1, self.optimizer_2],\n enabled=enabled,\n opt_level=opt_level,\n loss_scale=1.0,\n )\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`. Note that, this\n class only supports targeted attack.\n :return: An array holding the adversarial examples.\n \"\"\"\n import torch\n\n if y is None: # pragma: no cover\n raise ValueError(\n \"`ImperceptibleASRPyTorch` is a targeted attack and requires the definition of target\"\n \"labels `y`. Currently `y` is set to `None`.\"\n )\n\n # Cast to type float64 to avoid overflow\n adv_x = np.array([x_i.copy().astype(np.float64) for x_i in x])\n\n # Put the estimator in the training mode, otherwise CUDA may not be able to backpropagate through the model in\n # case a PyTorchDeepSpeech estimator is used. However, the PyTorchDeepSpeech estimator uses batch norm layers\n # which need to be frozen\n self.estimator.to_training_mode()\n self.estimator.set_batchnorm(train=False)\n\n # Compute perturbation with batching\n num_batch = int(np.ceil(len(x) / float(self.batch_size)))\n\n for m in range(num_batch):\n # Batch indexes\n batch_index_1, batch_index_2 = (m * self.batch_size, min((m + 1) * self.batch_size, len(x)))\n\n # First reset delta\n self.global_optimal_delta.data = torch.zeros(self.batch_size, self.global_max_length).type(torch.float64)\n\n # Next, reset optimizers\n if self._optimizer_arg_1 is None:\n self.optimizer_1 = torch.optim.Adam(params=[self.global_optimal_delta], lr=self.learning_rate_1)\n else:\n self.optimizer_1 = self._optimizer_arg_1( # type: ignore\n params=[self.global_optimal_delta], lr=self.learning_rate_1\n )\n\n if self._optimizer_arg_2 is None:\n self.optimizer_2 = torch.optim.Adam(params=[self.global_optimal_delta], lr=self.learning_rate_2)\n else:\n self.optimizer_2 = self._optimizer_arg_2( # type: ignore\n params=[self.global_optimal_delta], lr=self.learning_rate_2\n )\n\n # Then compute the batch\n adv_x_batch = self._generate_batch(adv_x[batch_index_1:batch_index_2], y[batch_index_1:batch_index_2])\n\n for i in range(len(adv_x_batch)):\n adv_x[batch_index_1 + i] = adv_x_batch[i, : len(adv_x[batch_index_1 + i])]\n\n # Unfreeze batch norm layers again, needed in case of PyTorchDeepSpeech\n self.estimator.set_batchnorm(train=True)\n\n # Recast to the original type\n adv_x = np.array([adv_x[i].astype(x[i].dtype) for i in range(len(adv_x))])\n\n return adv_x\n\n def _generate_batch(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Generate a batch of adversarial samples and return them in an array.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`. Note that, this\n class only supports targeted attack.\n :return: A batch of adversarial examples.\n \"\"\"\n import torch\n\n # First stage of attack\n successful_adv_input_1st_stage, original_input = self._attack_1st_stage(x=x, y=y)\n successful_perturbation_1st_stage = successful_adv_input_1st_stage - torch.tensor(original_input).to(\n self.estimator.device\n )\n\n # Compute original masking threshold and maximum psd\n theta_batch = []\n original_max_psd_batch = []\n\n for _, x_i in enumerate(x):\n theta, original_max_psd = self._compute_masking_threshold(x_i)\n theta = theta.transpose(1, 0)\n theta_batch.append(theta)\n original_max_psd_batch.append(original_max_psd)\n\n # Reset delta with new result\n local_batch_shape = successful_adv_input_1st_stage.shape\n self.global_optimal_delta.data = torch.zeros(self.batch_size, self.global_max_length).type(torch.float64)\n self.global_optimal_delta.data[: local_batch_shape[0], : local_batch_shape[1]] = (\n successful_perturbation_1st_stage\n )\n\n # Second stage of attack\n successful_adv_input_2nd_stage = self._attack_2nd_stage(\n x=x, y=y, theta_batch=theta_batch, original_max_psd_batch=original_max_psd_batch\n )\n\n results = successful_adv_input_2nd_stage.detach().cpu().numpy()\n\n return results\n\n def _attack_1st_stage(self, x: np.ndarray, y: np.ndarray) -> tuple[\"torch.Tensor\", np.ndarray]:\n \"\"\"\n The first stage of the attack.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`. Note that, this\n class only supports targeted attack.\n :return: A tuple of two tensors:\n - A tensor holding the candidate adversarial examples.\n - An array holding the original inputs.\n \"\"\"\n import torch\n\n # Compute local shape\n local_batch_size = len(x)\n real_lengths = np.array([x_.shape[0] for x_ in x])\n local_max_length = np.max(real_lengths)\n\n # Initialize rescale\n rescale = np.ones([local_batch_size, local_max_length], dtype=np.float64) * self.initial_rescale\n\n # Reformat input\n input_mask = np.zeros([local_batch_size, local_max_length], dtype=np.float64)\n original_input = np.zeros([local_batch_size, local_max_length], dtype=np.float64)\n\n for local_batch_size_idx in range(local_batch_size):\n input_mask[local_batch_size_idx, : len(x[local_batch_size_idx])] = 1\n original_input[local_batch_size_idx, : len(x[local_batch_size_idx])] = x[local_batch_size_idx]\n\n # Optimization loop\n successful_adv_input: list[\"torch.Tensor\" | None] = [None] * local_batch_size\n trans = [None] * local_batch_size\n\n for iter_1st_stage_idx in range(self.max_iter_1):\n # Zero the parameter gradients\n self.optimizer_1.zero_grad()\n\n # Call to forward pass\n loss, local_delta, decoded_output, masked_adv_input, _ = self._forward_1st_stage(\n original_input=original_input,\n original_output=y,\n local_batch_size=local_batch_size,\n local_max_length=local_max_length,\n rescale=rescale,\n input_mask=input_mask,\n real_lengths=real_lengths,\n )\n\n # Actual training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self.optimizer_1) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n # Get sign of the gradients\n if self.global_optimal_delta.grad is not None:\n self.global_optimal_delta.grad = torch.sign(self.global_optimal_delta.grad)\n else:\n raise ValueError(\"Received None instead of gradient tensor.\")\n\n # Do optimization\n self.optimizer_1.step()\n\n # Save the best adversarial example and adjust the rescale coefficient if successful\n if iter_1st_stage_idx % self.num_iter_decrease_eps == 0:\n for local_batch_size_idx in range(local_batch_size):\n if decoded_output[local_batch_size_idx] == y[local_batch_size_idx]:\n # Adjust the rescale coefficient\n max_local_delta = np.max(np.abs(local_delta[local_batch_size_idx].detach().cpu().numpy()))\n\n if rescale[local_batch_size_idx][0] * self.eps > max_local_delta:\n rescale[local_batch_size_idx] = max_local_delta / self.eps\n rescale[local_batch_size_idx] *= self.decrease_factor_eps\n\n # Save the best adversarial example\n successful_adv_input[local_batch_size_idx] = masked_adv_input[local_batch_size_idx]\n trans[local_batch_size_idx] = decoded_output[local_batch_size_idx]\n\n # If attack is unsuccessful\n if iter_1st_stage_idx == self.max_iter_1 - 1:\n for local_batch_size_idx in range(local_batch_size):\n if successful_adv_input[local_batch_size_idx] is None:\n successful_adv_input[local_batch_size_idx] = masked_adv_input[local_batch_size_idx]\n trans[local_batch_size_idx] = decoded_output[local_batch_size_idx]\n\n result = torch.stack(successful_adv_input) # type: ignore\n\n return result, original_input\n\n def _forward_1st_stage(\n self,\n original_input: np.ndarray,\n original_output: np.ndarray,\n local_batch_size: int,\n local_max_length: int,\n rescale: np.ndarray,\n input_mask: np.ndarray,\n real_lengths: np.ndarray,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\", np.ndarray, \"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n The forward pass of the first stage of the attack.\n\n :param original_input: Samples of shape (nb_samples, seq_length). Note that, sequences in the batch must have\n equal lengths. A possible example of `original_input` could be:\n `original_input = np.array([np.array([0.1, 0.2, 0.1]), np.array([0.3, 0.1, 0.0])])`.\n :param original_output: Target values of shape (nb_samples). Each sample in `original_output` is a string, and\n it may possess different lengths. A possible example of `original_output` could be:\n `original_output = np.array(['SIXTY ONE', 'HELLO'])`.\n :param local_batch_size: Current batch size.\n :param local_max_length: Max length of the current batch.\n :param rescale: Current rescale coefficients.\n :param input_mask: Masks of true inputs.\n :param real_lengths: Real lengths of original sequences.\n :return: A tuple of (loss, local_delta, decoded_output, masked_adv_input, local_delta_rescale)\n - loss: The loss tensor of the first stage of the attack.\n - local_delta: The delta of the current batch.\n - decoded_output: Transcription output.\n - masked_adv_input: Perturbed inputs.\n - local_delta_rescale: The rescaled delta.\n \"\"\"\n import torch\n\n # Compute perturbed inputs\n local_delta = self.global_optimal_delta[:local_batch_size, :local_max_length]\n local_delta_rescale = torch.clamp(local_delta, -self.eps, self.eps).to(self.estimator.device)\n local_delta_rescale *= torch.tensor(rescale).to(self.estimator.device)\n adv_input = local_delta_rescale + torch.tensor(original_input).to(self.estimator.device)\n masked_adv_input = adv_input * torch.tensor(input_mask).to(self.estimator.device)\n\n # Compute loss and decoded output\n loss, decoded_output = self.estimator.compute_loss_and_decoded_output(\n masked_adv_input=masked_adv_input,\n original_output=original_output,\n real_lengths=real_lengths,\n )\n\n return loss, local_delta, decoded_output, masked_adv_input, local_delta_rescale\n\n def _attack_2nd_stage(\n self, x: np.ndarray, y: np.ndarray, theta_batch: list[np.ndarray], original_max_psd_batch: list[np.ndarray]\n ) -> \"torch.Tensor\":\n \"\"\"\n The second stage of the attack.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`. Note that, this\n class only supports targeted attack.\n :param theta_batch: Original thresholds.\n :param original_max_psd_batch: Original maximum psd.\n :return: An array holding the candidate adversarial examples.\n \"\"\"\n import torch\n\n # Compute local shape\n local_batch_size = len(x)\n real_lengths = np.array([x_.shape[0] for x_ in x])\n local_max_length = np.max(real_lengths)\n\n # Initialize alpha and rescale\n alpha = np.array([self.alpha] * local_batch_size, dtype=np.float64)\n rescale = np.ones([local_batch_size, local_max_length], dtype=np.float64) * self.initial_rescale\n\n # Reformat input\n input_mask = np.zeros([local_batch_size, local_max_length], dtype=np.float64)\n original_input = np.zeros([local_batch_size, local_max_length], dtype=np.float64)\n\n for local_batch_size_idx in range(local_batch_size):\n input_mask[local_batch_size_idx, : len(x[local_batch_size_idx])] = 1\n original_input[local_batch_size_idx, : len(x[local_batch_size_idx])] = x[local_batch_size_idx]\n\n # Optimization loop\n successful_adv_input: list[\"torch.Tensor\" | None] = [None] * local_batch_size\n best_loss_2nd_stage = [np.inf] * local_batch_size\n trans = [None] * local_batch_size\n\n for iter_2nd_stage_idx in range(self.max_iter_2):\n # Zero the parameter gradients\n self.optimizer_2.zero_grad()\n\n # Call to forward pass of the first stage\n loss_1st_stage, _, decoded_output, masked_adv_input, local_delta_rescale = self._forward_1st_stage(\n original_input=original_input,\n original_output=y,\n local_batch_size=local_batch_size,\n local_max_length=local_max_length,\n rescale=rescale,\n input_mask=input_mask,\n real_lengths=real_lengths,\n )\n\n # Call to forward pass of the first stage\n loss_2nd_stage = self._forward_2nd_stage(\n local_delta_rescale=local_delta_rescale,\n theta_batch=theta_batch,\n original_max_psd_batch=original_max_psd_batch,\n real_lengths=real_lengths,\n )\n\n # Total loss\n loss = loss_1st_stage.type(torch.float64) + torch.tensor(alpha).to(self.estimator.device) * loss_2nd_stage\n loss = torch.mean(loss)\n\n # Actual training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self.optimizer_2) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n # Do optimization\n self.optimizer_2.step()\n\n # Save the best adversarial example and adjust the alpha coefficient\n for local_batch_size_idx in range(local_batch_size):\n if decoded_output[local_batch_size_idx] == y[local_batch_size_idx]:\n if loss_2nd_stage[local_batch_size_idx] < best_loss_2nd_stage[local_batch_size_idx]:\n # Update the best loss at 2nd stage\n best_loss_2nd_stage[local_batch_size_idx] = ( # type: ignore\n loss_2nd_stage[local_batch_size_idx].detach().cpu().numpy()\n )\n\n # Save the best adversarial example\n successful_adv_input[local_batch_size_idx] = masked_adv_input[local_batch_size_idx]\n trans[local_batch_size_idx] = decoded_output[local_batch_size_idx]\n\n # Adjust to increase the alpha coefficient\n if iter_2nd_stage_idx % self.num_iter_increase_alpha == 0:\n alpha[local_batch_size_idx] *= self.increase_factor_alpha\n\n # Adjust to decrease the alpha coefficient\n elif iter_2nd_stage_idx % self.num_iter_decrease_alpha == 0:\n alpha[local_batch_size_idx] *= self.decrease_factor_alpha\n alpha[local_batch_size_idx] = max(alpha[local_batch_size_idx], 0.0005)\n\n # If attack is unsuccessful\n if iter_2nd_stage_idx == self.max_iter_2 - 1:\n for local_batch_size_idx in range(local_batch_size):\n if successful_adv_input[local_batch_size_idx] is None:\n successful_adv_input[local_batch_size_idx] = masked_adv_input[local_batch_size_idx]\n trans[local_batch_size_idx] = decoded_output[local_batch_size_idx]\n\n result = torch.stack(successful_adv_input) # type: ignore\n\n return result\n\n def _forward_2nd_stage(\n self,\n local_delta_rescale: \"torch.Tensor\",\n theta_batch: list[np.ndarray],\n original_max_psd_batch: list[np.ndarray],\n real_lengths: np.ndarray,\n ) -> \"torch.Tensor\":\n \"\"\"\n The forward pass of the second stage of the attack.\n\n :param local_delta_rescale: Local delta after rescaled.\n :param theta_batch: Original thresholds.\n :param original_max_psd_batch: Original maximum psd.\n :param real_lengths: Real lengths of original sequences.\n :return: The loss tensor of the second stage of the attack.\n \"\"\"\n import torch\n\n # Compute loss for masking threshold\n losses = []\n relu = torch.nn.ReLU()\n\n for i, _ in enumerate(theta_batch):\n psd_transform_delta = self._psd_transform(\n delta=local_delta_rescale[i, : real_lengths[i]], original_max_psd=original_max_psd_batch[i]\n )\n\n loss = torch.mean(relu(psd_transform_delta - torch.tensor(theta_batch[i]).to(self.estimator.device)))\n losses.append(loss)\n\n losses_stack = torch.stack(losses)\n\n return losses_stack\n\n def _compute_masking_threshold(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Compute the masking threshold and the maximum psd of the original audio.\n\n :param x: Samples of shape (seq_length,).\n :return: A tuple of the masking threshold and the maximum psd.\n \"\"\"\n import librosa\n\n # First compute the psd matrix\n # Get window for the transformation\n window = scipy.signal.get_window(\"hann\", self.win_length, fftbins=True)\n\n # Do transformation\n transformed_x = librosa.core.stft(\n y=x, n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length, window=window, center=False\n )\n transformed_x *= np.sqrt(8.0 / 3.0)\n\n psd = abs(transformed_x / self.win_length)\n original_max_psd = np.max(psd * psd)\n with np.errstate(divide=\"ignore\"):\n psd = (20 * np.log10(psd)).clip(min=-200)\n psd = 96 - np.max(psd) + psd\n\n # Compute freqs and barks\n freqs = librosa.core.fft_frequencies(sr=self.estimator.sample_rate, n_fft=self.n_fft)\n barks = 13 * np.arctan(0.00076 * freqs) + 3.5 * np.arctan(pow(freqs / 7500.0, 2))\n\n # Compute quiet threshold\n ath = np.zeros(len(barks), dtype=np.float64) - np.inf\n bark_idx = int(np.argmax(barks > 1))\n ath[bark_idx:] = (\n 3.64 * pow(freqs[bark_idx:] * 0.001, -0.8)\n - 6.5 * np.exp(-0.6 * pow(0.001 * freqs[bark_idx:] - 3.3, 2))\n + 0.001 * pow(0.001 * freqs[bark_idx:], 4)\n - 12\n )\n\n # Compute the global masking threshold theta\n theta = []\n\n for i in range(psd.shape[1]):\n # Compute masker index\n masker_idx = scipy.signal.argrelextrema(psd[:, i], np.greater)[0]\n\n if 0 in masker_idx:\n masker_idx = np.delete(masker_idx, 0)\n\n if len(psd[:, i]) - 1 in masker_idx:\n masker_idx = np.delete(masker_idx, len(psd[:, i]) - 1)\n\n barks_psd = np.zeros([len(masker_idx), 3], dtype=np.float64)\n barks_psd[:, 0] = barks[masker_idx]\n barks_psd[:, 1] = 10 * np.log10(\n pow(10, psd[:, i][masker_idx - 1] / 10.0)\n + pow(10, psd[:, i][masker_idx] / 10.0)\n + pow(10, psd[:, i][masker_idx + 1] / 10.0)\n )\n barks_psd[:, 2] = masker_idx\n\n for j in range(len(masker_idx)):\n if barks_psd.shape[0] <= j + 1:\n break\n\n while barks_psd[j + 1, 0] - barks_psd[j, 0] < 0.5:\n quiet_threshold = (\n 3.64 * pow(freqs[int(barks_psd[j, 2])] * 0.001, -0.8)\n - 6.5 * np.exp(-0.6 * pow(0.001 * freqs[int(barks_psd[j, 2])] - 3.3, 2))\n + 0.001 * pow(0.001 * freqs[int(barks_psd[j, 2])], 4)\n - 12\n )\n if barks_psd[j, 1] < quiet_threshold:\n barks_psd = np.delete(barks_psd, j, axis=0)\n\n if barks_psd.shape[0] == j + 1:\n break\n\n if barks_psd[j, 1] < barks_psd[j + 1, 1]:\n barks_psd = np.delete(barks_psd, j, axis=0)\n else:\n barks_psd = np.delete(barks_psd, j + 1, axis=0)\n\n if barks_psd.shape[0] == j + 1:\n break\n\n # Compute the global masking threshold\n delta = 1 * (-6.025 - 0.275 * barks_psd[:, 0])\n\n t_s = []\n\n for m in range(barks_psd.shape[0]):\n d_z = barks - barks_psd[m, 0]\n zero_idx = int(np.argmax(d_z > 0))\n s_f = np.zeros(len(d_z), dtype=np.float64)\n s_f[:zero_idx] = 27 * d_z[:zero_idx]\n s_f[zero_idx:] = (-27 + 0.37 * max(barks_psd[m, 1] - 40, 0)) * d_z[zero_idx:]\n t_s.append(barks_psd[m, 1] + delta[m] + s_f)\n\n t_s_array = np.array(t_s)\n\n theta.append(np.sum(pow(10, t_s_array / 10.0), axis=0) + pow(10, ath / 10.0))\n\n theta_array = np.array(theta)\n\n return theta_array, original_max_psd # type: ignore\n\n def _psd_transform(self, delta: \"torch.Tensor\", original_max_psd: np.ndarray) -> \"torch.Tensor\":\n \"\"\"\n Compute the psd matrix of the perturbation.\n\n :param delta: The perturbation.\n :param original_max_psd: The maximum psd of the original audio.\n :return: The psd matrix.\n \"\"\"\n import torch\n\n # Get window for the transformation\n window_fn = torch.hann_window # type: ignore\n\n # Return STFT of delta\n delta_stft = torch.view_as_real(\n torch.stft(\n delta,\n n_fft=self.n_fft,\n hop_length=self.hop_length,\n win_length=self.win_length,\n center=False,\n window=window_fn(self.win_length).to(self.estimator.device),\n return_complex=True,\n ).to(self.estimator.device)\n )\n\n # Take abs of complex STFT results\n transformed_delta = torch.sqrt(torch.sum(torch.square(delta_stft), -1))\n\n # Compute the psd matrix\n psd = (8.0 / 3.0) * transformed_delta / self.win_length\n psd = psd**2\n psd = (\n torch.pow(torch.tensor(10.0).type(torch.float64), torch.tensor(9.6).type(torch.float64)).to(\n self.estimator.device\n )\n / torch.reshape(torch.tensor(original_max_psd).to(self.estimator.device), [-1, 1, 1])\n * psd.type(torch.float64)\n )\n\n return psd\n\n def _check_params(self) -> None:\n \"\"\"\n Apply attack-specific checks.\n \"\"\"\n if self.eps <= 0:\n raise ValueError(\"The perturbation size `eps` has to be positive.\")\n\n if not isinstance(self.max_iter_1, int):\n raise ValueError(\"The maximum number of iterations must be of type int.\")\n if self.max_iter_1 <= 0:\n raise ValueError(\"The maximum number of iterations must be greater than 0.\")\n\n if not isinstance(self.max_iter_2, int):\n raise ValueError(\"The maximum number of iterations must be of type int.\")\n if self.max_iter_2 <= 0:\n raise ValueError(\"The maximum number of iterations must be greater than 0.\")\n\n if not isinstance(self.learning_rate_1, float):\n raise ValueError(\"The learning rate must be of type float.\")\n if self.learning_rate_1 <= 0.0:\n raise ValueError(\"The learning rate must be greater than 0.0.\")\n\n if not isinstance(self.learning_rate_2, float):\n raise ValueError(\"The learning rate must be of type float.\")\n if self.learning_rate_2 <= 0.0:\n raise ValueError(\"The learning rate must be greater than 0.0.\")\n\n if not isinstance(self.global_max_length, int):\n raise ValueError(\"The length of the longest audio signal must be of type int.\")\n if self.global_max_length <= 0:\n raise ValueError(\"The length of the longest audio signal must be greater than 0.\")\n\n if not isinstance(self.initial_rescale, float):\n raise ValueError(\"The initial rescale coefficient must be of type float.\")\n if self.initial_rescale <= 0.0:\n raise ValueError(\"The initial rescale coefficient must be greater than 0.0.\")\n\n if not isinstance(self.decrease_factor_eps, float):\n raise ValueError(\"The rescale factor of `eps` must be of type float.\")\n if self.decrease_factor_eps <= 0.0:\n raise ValueError(\"The rescale factor of `eps` must be greater than 0.0.\")\n\n if not isinstance(self.num_iter_decrease_eps, int):\n raise ValueError(\"The number of iterations must be of type int.\")\n if self.num_iter_decrease_eps <= 0:\n raise ValueError(\"The number of iterations must be greater than 0.\")\n\n if not isinstance(self.alpha, float):\n raise ValueError(\"The value of alpha must be of type float.\")\n if self.alpha <= 0.0:\n raise ValueError(\"The value of alpha must be greater than 0.0.\")\n\n if not isinstance(self.increase_factor_alpha, float):\n raise ValueError(\"The factor to increase alpha must be of type float.\")\n if self.increase_factor_alpha <= 0.0:\n raise ValueError(\"The factor to increase alpha must be greater than 0.0.\")\n\n if not isinstance(self.num_iter_increase_alpha, int):\n raise ValueError(\"The number of iterations must be of type int.\")\n if self.num_iter_increase_alpha <= 0:\n raise ValueError(\"The number of iterations must be greater than 0.\")\n\n if not isinstance(self.decrease_factor_alpha, float):\n raise ValueError(\"The factor to decrease alpha must be of type float.\")\n if self.decrease_factor_alpha <= 0.0:\n raise ValueError(\"The factor to decrease alpha must be greater than 0.0.\")\n\n if not isinstance(self.num_iter_decrease_alpha, int):\n raise ValueError(\"The number of iterations must be of type int.\")\n if self.num_iter_decrease_alpha <= 0:\n raise ValueError(\"The number of iterations must be greater than 0.\")\n\n if not isinstance(self.win_length, int):\n raise ValueError(\"Length of the window must be of type int.\")\n if self.win_length <= 0:\n raise ValueError(\"Length of the window must be greater than 0.\")\n\n if not isinstance(self.hop_length, int):\n raise ValueError(\"Number of audio samples between adjacent STFT columns must be of type int.\")\n if self.hop_length <= 0:\n raise ValueError(\"Number of audio samples between adjacent STFT columns must be greater than 0.\")\n\n if not isinstance(self.n_fft, int):\n raise ValueError(\"FFT window size must be of type int.\")\n if self.n_fft <= 0:\n raise ValueError(\"FFT window size must be greater than 0.\")\n\n if self.win_length > self.n_fft:\n raise ValueError(\"Length of the window must be smaller than or equal to FFT window size.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/laser_attack/algorithms.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the greedy search algorithm of the `LaserBeam` attack.\n\n| Paper link: https://arxiv.org/abs/2103.06504\n\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\n\nfrom art.attacks.evasion.laser_attack.utils import AdversarialObject, AdvObjectGenerator, DebugInfo, ImageGenerator\n\n\ndef greedy_search(\n image: np.ndarray,\n estimator,\n iterations: int,\n actual_class: int,\n actual_class_confidence: float,\n adv_object_generator: AdvObjectGenerator,\n image_generator: ImageGenerator,\n debug: DebugInfo | None = None,\n) -> tuple[AdversarialObject | None, int | None]:\n \"\"\"\n Greedy search algorithm used to generate parameters of an adversarial object that added to the :image will mislead\n the neural network.\n Based on the paper:\n https://openaccess.thecvf.com/content/CVPR2021/papers/Duan_Adversarial_Laser_Beam_Effective_Physical-World_Attack_to_DNNs_in_a_CVPR_2021_paper.pdf\n\n :param image: Image to attack.\n :param estimator: Predictor of the image class.\n :param iterations: Maximum number of iterations of the algorithm.\n :param actual_class:\n :param actual_class_confidence:\n :param adv_object_generator: Object responsible for adversarial object generation.\n :param image_generator: Object responsible for image generation.\n :param debug: Optional debug handler.\n \"\"\"\n\n params = adv_object_generator.random()\n for _ in range(iterations):\n for sign in [-1, 1]:\n params_prim = adv_object_generator.update_params(params, sign=sign)\n adversarial_image = image_generator.update_image(image, params_prim)\n prediction = estimator.predict(adversarial_image)\n if debug is not None:\n DebugInfo.report(debug, params_prim, np.squeeze(adversarial_image, 0))\n predicted_class = prediction.argmax()\n confidence_adv = prediction[0][actual_class]\n\n if confidence_adv <= actual_class_confidence:\n params = params_prim\n actual_class_confidence = confidence_adv\n break\n\n if predicted_class != actual_class:\n return params, predicted_class\n\n return None, None\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/laser_attack/laser_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the `LaserAttack` attack.\n\n| Paper link: https://arxiv.org/abs/2103.06504\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport logging\nimport math\nfrom typing import Any\n\nimport numpy as np\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.laser_attack.algorithms import greedy_search\nfrom art.attacks.evasion.laser_attack.utils import (\n AdversarialObject,\n AdvObjectGenerator,\n DebugInfo,\n ImageGenerator,\n Line,\n wavelength_to_rgb,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass LaserAttack(EvasionAttack):\n \"\"\"\n Implementation of a generic laser attack case.\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"iterations\",\n \"laser_generator\",\n \"image_generator\",\n \"random_initializations\",\n \"optimisation_algorithm\",\n \"debug\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n estimator,\n iterations: int,\n laser_generator: AdvObjectGenerator,\n image_generator: ImageGenerator = ImageGenerator(),\n random_initializations: int = 1,\n optimisation_algorithm: Callable = greedy_search,\n debug: DebugInfo | None = None,\n ) -> None:\n \"\"\"\n :param estimator: Predictor of the image class.\n :param iterations: Maximum number of iterations of the algorithm.\n :param laser_generator: Object responsible for generation laser beams images and their update.\n :param image_generator: Object responsible for image generation.\n :param random_initializations: How many times repeat the attack.\n :param optimisation_algorithm: Algorithm used to generate adversarial example. May be replaced.\n :param debug: Optional debug handler.\n \"\"\"\n\n super().__init__(estimator=estimator)\n self.iterations = iterations\n self.random_initializations = random_initializations\n self.optimisation_algorithm = optimisation_algorithm\n self._laser_generator = laser_generator\n self._image_generator = image_generator\n self._debug = debug\n\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial examples.\n\n :param x: Images to attack as a tensor in NHWC order\n :param y: Array of correct classes\n :return: Array of adversarial images\n \"\"\"\n\n if x.ndim != 4: # pragma: no cover\n raise ValueError(\"Unrecognized input dimension. Only tensors NHWC are acceptable.\")\n\n parameters = self.generate_parameters(x, y)\n adversarial_images = np.zeros_like(x)\n for image_index in range(x.shape[0]):\n laser_params, _ = parameters[image_index]\n if laser_params is None:\n adversarial_images[image_index] = x[image_index]\n continue\n adversarial_image = self._image_generator.update_image(x[image_index], laser_params)\n adversarial_images[image_index] = adversarial_image\n\n return adversarial_images\n\n def generate_parameters(\n self,\n x: np.ndarray,\n y: np.ndarray | None = None,\n ) -> list[tuple[AdversarialObject | None, int | None]]:\n \"\"\"\n Generate adversarial parameters for given images.\n\n :param x: Images to attack as a tensor (NRGB = (1, ...))\n :param y: Correct classes\n :return: List of tuples of adversarial objects and predicted class.\n \"\"\"\n result = []\n for image_index in range(x.shape[0]):\n laser_params, adv_class = self._generate_params_for_single_input(\n x[image_index], y[image_index] if y is not None else None\n )\n result.append((laser_params, adv_class))\n return result\n\n def _generate_params_for_single_input(\n self, x: np.ndarray, y: int | None = None\n ) -> tuple[AdversarialObject | None, int | None]:\n \"\"\"\n Generate adversarial example params for a single image.\n\n :param x: Image to attack as a tensor (NRGB = (1, ...))\n :param y: Correct class of the image. If not provided, it is set to the prediction of the model.\n :return: Adversarial object params and adversarial class number.\n \"\"\"\n\n image = np.expand_dims(x, 0)\n prediction = self.estimator.predict(image)\n if y is not None:\n actual_class = y\n else:\n actual_class = prediction.argmax()\n actual_class_confidence = prediction[0][actual_class]\n\n for _ in range(self.random_initializations):\n laser_params, predicted_class = self._attack_single_image(image, actual_class, actual_class_confidence)\n if laser_params is not None:\n logger.info(\"Found adversarial params: %s\", laser_params)\n return laser_params, predicted_class\n logger.warning(\"Couldn't find adversarial laser parameters\")\n\n return None, None\n\n def _check_params(self) -> None:\n super()._check_params()\n if self.estimator.channels_first:\n raise ValueError(\"Channels first models are not supported. Supported tensor format: NHWC\")\n if self.iterations <= 0:\n raise ValueError(\"The iterations number has to be positive.\")\n if self.random_initializations <= 0:\n raise ValueError(\"The random initializations has to be positive.\")\n\n def _attack_single_image(\n self, x: np.ndarray, y: int, confidence: float\n ) -> tuple[AdversarialObject | None, int | None]:\n \"\"\"\n Attack particular image with given class.\n\n :param x: Image to attack.\n :param y: Correct class of the image.\n :returns: Pair of adversarial parameters and predicted class.\n \"\"\"\n\n return self.optimisation_algorithm(\n image=x,\n estimator=self.estimator,\n iterations=self.iterations,\n actual_class=y,\n actual_class_confidence=confidence,\n adv_object_generator=self._laser_generator,\n image_generator=self._image_generator,\n debug=self._debug,\n )\n\n\nclass LaserBeam(AdversarialObject):\n \"\"\"\n Representation of the attacking object used in the paper.\n \"\"\"\n\n def __init__(self, wavelength: float, width: float, line: Line):\n \"\"\"\n :param wavelength: Wavelength in nanometers of the laser beam.\n :param width: Width of the laser beam in pixels.\n :param line: Line object used to determine shape of the laser beam.\n \"\"\"\n self.wavelength = float(wavelength)\n self.line = line\n self.width = float(width)\n self.rgb = np.array(wavelength_to_rgb(self.wavelength))\n\n def __call__(self, x: int, y: int) -> np.ndarray:\n \"\"\"\n Generate pixel of a laser beam.\n\n :param x: X coordinate of a pixel.\n :param y: Y coordinate of a pixel.\n :returns: List of 3 normalized RGB values (between 0 and 1) that represents a pixel.\n \"\"\"\n _x, _y = float(x), float(y)\n distance = self.line.distance_of_point_from_the_line(_x, _y)\n\n if distance <= self.width / 2.0:\n return self.rgb\n if self.width / 2.0 <= distance <= 5 * self.width:\n return math.sqrt(self.width) / math.pow(distance, 2) * self.rgb # type: ignore\n\n return np.array([0.0, 0.0, 0.0])\n\n def __repr__(self) -> str:\n return f\"LaserBeam(wavelength={self.wavelength}, Line={str(self.line)}, width={self.width})\"\n\n @staticmethod\n def from_numpy(theta: np.ndarray) -> \"LaserBeam\":\n \"\"\"\n :param theta: List of the laser beam parameters, passed as list in the order:\n wavelength[nm], slope angle[radians], bias[pixels], width[pixels].\n :returns: New class object based on :theta.\n \"\"\"\n return LaserBeam(\n wavelength=theta[0],\n line=Line(theta[1], theta[2]),\n width=theta[3],\n )\n\n @staticmethod\n def from_array(theta: list) -> \"LaserBeam\":\n \"\"\"\n Create instance of the class using parameters :theta.\n\n :param theta: List of the laser beam parameters, passed as list in the order:\n wavelength[nm], slope angle[radians], bias[pixels], width[pixels].\n :returns: New class object based on :theta.\n \"\"\"\n return LaserBeam(\n wavelength=theta[0],\n line=Line(theta[1], theta[2]),\n width=theta[3],\n )\n\n def to_numpy(self) -> np.ndarray:\n line = self.line\n return np.array([self.wavelength, line.angle, line.bias, self.width])\n\n def __mul__(self, other: float | int | list | np.ndarray) -> \"LaserBeam\":\n if isinstance(other, (float, int)):\n return LaserBeam.from_numpy(other * self.to_numpy())\n if isinstance(other, np.ndarray):\n return LaserBeam.from_numpy(self.to_numpy() * other)\n if isinstance(other, list):\n return LaserBeam.from_numpy(self.to_numpy() * np.array(other))\n raise Exception(\"Not accepted value.\")\n\n def __rmul__(self, other) -> \"LaserBeam\":\n return self * other\n\n\nclass LaserBeamGenerator(AdvObjectGenerator):\n \"\"\"\n Generator of the LaserBeam objects for the LaserBeamAttack purpose\n \"\"\"\n\n def __init__(self, min_params: LaserBeam, max_params: LaserBeam, max_step: float = 20 / 100) -> None:\n \"\"\"\n :params min_params: left bound of the params range\n :params max_params: right bound of the params range\n :params max_step: maximal part of the random LaserBeam object drawn from the range.\n \"\"\"\n self.min_params = min_params\n self.max_params = max_params\n self.max_step = max_step\n self.__params_ranges = max_params.to_numpy() - min_params.to_numpy()\n\n def update_params(self, params: Any, **kwargs) -> LaserBeam:\n \"\"\"\n Updates parameters of the received LaserBeam object in the random direction.\n\n :param params: LaserBeam object to be updated.\n :returns: Updated object.\n \"\"\"\n sign = kwargs.get(\"sign\", 1)\n random_step = np.random.uniform(0, self.max_step)\n d_params = self.__params_ranges * random_step * self._random_direction()\n theta_prim = LaserBeam.from_numpy(params.to_numpy() + sign * d_params)\n theta_prim = self.clip(theta_prim)\n return theta_prim\n\n @staticmethod\n def _random_direction() -> np.ndarray:\n \"\"\"\n Generate random array of ones that will decide which parameters of a laser beam will be updated:\n wavelength, angle, bias and width.\n\n :returns: Random array of ones (mask).\n \"\"\"\n q_mask = np.asfarray(\n [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n [1, 1, 0, 0],\n [1, 0, 1, 0],\n [1, 0, 0, 1],\n [0, 1, 1, 0],\n [0, 1, 0, 1],\n [0, 0, 1, 1],\n ]\n )\n\n mask = q_mask[np.random.choice(len(q_mask))]\n return mask\n\n def clip(self, params: LaserBeam):\n \"\"\"\n Keep received parameters in the tolerance ranges.\n\n :param params: Parameters of the LaserBeam that will be eventually clipped.\n :return: LaserBeam parameters in the desired ranges.\n \"\"\"\n clipped_params = np.clip(params.to_numpy(), self.min_params.to_numpy(), self.max_params.to_numpy())\n params.wavelength = clipped_params[0]\n params.line.angle = clipped_params[1]\n params.line.bias = clipped_params[2]\n params.width = clipped_params[3]\n return params\n\n def random(self) -> LaserBeam:\n \"\"\"\n Generate object of the LaserBeam class that will have randomly generated parameters in the tolerance ranges.\n\n :return: LaserBeam object with random parameters\n \"\"\"\n random_params = self.min_params.to_numpy() + np.random.uniform(0, 1) * (\n self.max_params.to_numpy() - self.min_params.to_numpy()\n )\n\n return LaserBeam.from_numpy(random_params)\n\n\nclass LaserBeamAttack(LaserAttack):\n \"\"\"\n Implementation of the `LaserBeam` attack.\n\n | Paper link: https://arxiv.org/abs/2103.06504\n \"\"\"\n\n def __init__(\n self,\n estimator,\n iterations: int,\n max_laser_beam: LaserBeam | tuple[float, float, float, int],\n min_laser_beam: LaserBeam | tuple[float, float, float, int] = (380.0, 0.0, 1.0, 1),\n random_initializations: int = 1,\n image_generator: ImageGenerator = ImageGenerator(),\n debug: DebugInfo | None = None,\n ) -> None:\n \"\"\"\n :param estimator: Predictor of the image class.\n :param iterations: Maximum number of iterations of the algorithm.\n :param max_laser_beam: LaserBeam with maximal parameters or tuple (wavelength, angle::radians, bias, width)\n of the laser parameters.\n :param min_laser_beam: LaserBeam with minimal parameters or tuple (wavelength, angle::radians, bias, width)\n of the laser parameters.\n :param image_generator: Object responsible for image generation.\n :param random_initializations: How many times repeat the attack.\n :param debug: Optional debug handler.\n \"\"\"\n\n if isinstance(min_laser_beam, tuple):\n min_laser_beam_obj = LaserBeam.from_array(list(min_laser_beam))\n else:\n min_laser_beam_obj = min_laser_beam\n if isinstance(max_laser_beam, tuple):\n max_laser_beam_obj = LaserBeam.from_array(list(max_laser_beam))\n else:\n max_laser_beam_obj = max_laser_beam\n\n super().__init__(\n estimator,\n iterations,\n LaserBeamGenerator(min_laser_beam_obj, max_laser_beam_obj),\n image_generator=image_generator,\n random_initializations=random_initializations,\n debug=debug,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/laser_attack/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements helper functions for the `LaserAttack`.\n\n| Paper link: https://arxiv.org/abs/2103.06504\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Callable\nfrom logging import Logger\nimport math\nfrom pathlib import Path\nimport string\nfrom typing import Any\n\nimport numpy as np\n\n\nclass Line:\n \"\"\"\n Representation of the linear function.\n \"\"\"\n\n def __init__(self, angle: float, bias: float):\n \"\"\"\n :param angle: Angle in radian.\n :param bias: Bias of the angle.\n \"\"\"\n self.angle = angle\n self.bias = bias\n\n def __call__(self, x: float) -> float:\n return math.tan(self.angle) * x + self.bias # type: ignore\n\n def distance_of_point_from_the_line(self, x: float, y: float) -> float:\n \"\"\"\n Calculate distance between line and point using L2 norm.\n https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Another_formula\n\n :param x: X coordinate of a point.\n :param y: Y coordinate of a point.\n :returns: Distance.\n \"\"\"\n y_difference = np.abs(self(x) - y)\n slope_squared = math.pow(math.tan(self.angle), 2) # type: ignore\n return y_difference / math.sqrt(1.0 + slope_squared) # type: ignore\n\n def to_numpy(self) -> np.ndarray:\n \"\"\"\n Convert instance to a numpy array.\n \"\"\"\n return np.array([self.angle, self.bias])\n\n\nclass Range:\n \"\"\"\n Representation of mathematical range concept\n \"\"\"\n\n def __init__(self, left: float, right: float):\n \"\"\"\n :param left: Left range.\n :param right: Right range.\n \"\"\"\n self.left = left\n self.right = right\n\n def __contains__(self, value):\n return self.left <= value < self.right\n\n @property\n def length(self):\n \"\"\"\n Calculate length of the range.\n \"\"\"\n return self.right - self.left\n\n\nclass AdversarialObject(ABC):\n \"\"\"\n Abstract class that represents an adversarial object placed on an input image in order to attack a neural network.\n \"\"\"\n\n @abstractmethod\n def to_numpy(self) -> np.ndarray:\n \"\"\"\n Convert instance to a numpy array.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def __call__(self, x: int, y: int) -> Any:\n raise NotImplementedError\n\n\nclass AdvObjectGenerator(ABC):\n \"\"\"\n Abstract class that define basic behaviours related to generation of an adversarial objects on images.\n \"\"\"\n\n min_params: AdversarialObject\n max_params: AdversarialObject\n\n @abstractmethod\n def update_params(self, params: Any, **kwargs) -> AdversarialObject:\n \"\"\"\n Update instance properties.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def random(self) -> AdversarialObject:\n \"\"\"\n Generate instance with a random properties.\n \"\"\"\n raise NotImplementedError\n\n\nclass ImageGenerator:\n \"\"\"\n General class responsible for generation and updating images used to attack neural network. Images are crated basing\n on adversarial objects passed to the class.\n \"\"\"\n\n def update_image(self, original_image: np.ndarray, params: AdversarialObject) -> np.ndarray:\n \"\"\"\n Update original image used for prediction by adding image of the adversarial object to it,\n in order to create adversarial example.\n\n :param original_image: Image to attack.\n :param params: Adversarial object.\n :returns: Original image with the adversarial object on it.\n \"\"\"\n image_shape = original_image.shape\n if len(original_image.shape) == 4:\n image_shape = image_shape[1:]\n\n adv_object_image = self.generate_image(params, image_shape)\n if len(original_image.shape) == 4:\n adv_object_image = np.expand_dims(adv_object_image, 0)\n return self.add_images(original_image, adv_object_image)\n\n @staticmethod\n def add_images(image1: np.ndarray, image2: np.ndarray) -> np.ndarray:\n \"\"\"\n Add two images and return resultant image.\n\n :param image1: First image.\n :param image2: Second image.\n \"\"\"\n return add_images(image1, image2)\n\n @staticmethod\n def generate_image(adv_object: Callable, shape: tuple) -> np.ndarray:\n \"\"\"\n Generate image of the adversarial object.\n\n :param adv_object: Adversarial object.\n :param shape: Shape of the desired image.\n :returns: Image of the adversarial object.\n \"\"\"\n laser_image = np.zeros(shape)\n if laser_image.ndim == 3 and laser_image.shape[2] == 3:\n for i in range(shape[0]):\n for j in range(shape[1]):\n rgb = adv_object(i, j)\n for chan in range(3):\n laser_image[i, j, chan] = np.clip(rgb[chan], 0, 1)\n elif laser_image.ndim == 2:\n for i in range(shape[0]):\n for j in range(shape[1]):\n rgb = np.mean(adv_object(i, j))\n laser_image[i, j] = np.clip(rgb, 0, 1)\n\n return laser_image\n\n\ndef wavelength_to_rgb(wavelength: float | int) -> list[float]:\n \"\"\"\n Converts wavelength in nanometers to the RGB color.\n\n :param wavelength: wavelength in the nanometers\n :returns: Array of normalized RGB values.\n \"\"\"\n wavelength = float(wavelength)\n range1 = Range(380, 440)\n range2 = Range(440, 490)\n range3 = Range(490, 510)\n range4 = Range(510, 580)\n range5 = Range(580, 645)\n range6 = Range(645, 780)\n\n _r, _g, _b = 0.0, 0.0, 0.0\n if wavelength in range1:\n _r = (range1.right - wavelength) / range1.length\n _g = 0.0\n _b = 1.0\n elif wavelength in range2:\n _r = 0.0\n _g = (wavelength - range2.left) / range2.length\n _b = 1.0\n elif wavelength in range3:\n _r = 0.0\n _g = 1.0\n _b = (range3.right - wavelength) / range3.length\n elif wavelength in range4:\n _r = (wavelength - range4.left) / range4.length\n _g = 1.0\n _b = 0.0\n elif wavelength in range5:\n _r = 1.0\n _g = (range5.right - wavelength) / range5.length\n _b = 0.0\n elif wavelength in range6:\n _r = 1.0\n _g = 0.0\n _b = 0.0\n\n return [_r, _g, _b]\n\n\ndef add_images(image1: np.ndarray, image2: np.ndarray) -> np.ndarray:\n \"\"\"\n Add two normalized RGB images and return resultant image.\n If some pixel value exceeds 1, then it's set to 1.\n\n :param image1: First image.\n :param image2: Second image.\n :returns: Resultant image.\n \"\"\"\n if image1.shape != image2.shape:\n raise Exception(\"Wrong size\")\n return np.clip(image1 + image2, 0, 1)\n\n\ndef save_nrgb_image(image: np.ndarray, number=0, name_length=5, directory=\"attack\"):\n \"\"\"\n Saves normalized RGB image, passed as numpy array to the set directory - default: \"attack\".\n\n :param image: Image to save.\n :param number: i.e. class of the image.\n :param name_length: Length of the random string in the name.\n :param directory: Directory where images will be saved.\n \"\"\"\n import matplotlib.pyplot as plt\n\n alphabet = np.array(list(string.ascii_letters))\n Path(directory).mkdir(exist_ok=True)\n im_name = f\"{directory}/{number}_{''.join(np.random.choice(alphabet, size=name_length))}.jpg\"\n plt.imsave(im_name, image)\n\n\nclass DebugInfo:\n \"\"\"\n Logs debug information during attacking process.\n \"\"\"\n\n def __init__(self, logger: Logger, artifacts_directory: str):\n \"\"\"\n :param logger: Logger instance.\n :param artifacts_directory: Artifacts directory.\n \"\"\"\n self.logger = logger\n self.artifacts_directory = artifacts_directory\n\n def log(self, adv_object: AdversarialObject) -> None:\n \"\"\"\n Prints debug info on the stderr.\n\n :param adv_object: Parameters of the adversarial object, printed out to the stderr.\n \"\"\"\n self.logger.info(adv_object)\n\n def save_image(self, image: np.ndarray) -> None:\n \"\"\"\n Saves images generated during lasting process to the artifact's directory.\n\n :param image: Image to save.\n \"\"\"\n save_nrgb_image(image, name_length=5, directory=self.artifacts_directory)\n\n @staticmethod\n def report(instance: \"DebugInfo\", adv_object: AdversarialObject, image: np.ndarray) -> None:\n \"\"\"\n Log info and save image in the preset directory, based on the :instance.\n\n :param instance: DebugInfo object.\n :param adv_object: Object that will be printed out.\n :param image: Image to save.\n \"\"\"\n if instance.logger is not None:\n instance.log(adv_object)\n if instance.artifacts_directory is not None:\n instance.save_image(image)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/over_the_air_flickering/over_the_air_flickering_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n# and associated documentation files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or\n# substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nThis module contains an implementation of the Over-the-Air Adversarial Flickering attack on video recognition networks.\n\n| Paper link: https://arxiv.org/abs/2002.05123\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin, LossGradientsMixin\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import check_and_transform_label_format, get_labels_np_array\n\nif TYPE_CHECKING:\n\n import torch\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass OverTheAirFlickeringPyTorch(EvasionAttack):\n \"\"\"\n This module contains an implementation of the Over-the-Air Adversarial Flickering attack on video recognition\n networks.\n\n | Paper link: https://arxiv.org/abs/2002.05123\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"eps_step\",\n \"max_iter\",\n \"beta_0\",\n \"beta_1\",\n \"beta_2\",\n \"loss_margin\",\n \"batch_size\",\n \"start_frame_index\",\n \"num_frames\",\n \"round_samples\",\n \"targeted\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin, LossGradientsMixin)\n\n def __init__(\n self,\n classifier: \"PyTorchClassifier\",\n eps_step: float = 0.01,\n max_iter: int = 30,\n beta_0: float = 1.0,\n beta_1: float = 0.5,\n beta_2: float = 0.5,\n loss_margin: float = 0.05,\n batch_size: int = 1,\n start_frame_index: int = 0,\n num_frames: int | None = None,\n round_samples: float = 0.0,\n targeted: bool = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create an instance of the :class:`.OverTheAirFlickeringPyTorch`.\n\n :param classifier: A trained classifier.\n :param eps_step: The step size per iteration.\n :param max_iter: The number of iterations.\n :param beta_0: Weighting of the sum of all regularisation terms corresponding to `lambda` in the original paper.\n :param beta_1: Weighting of thickness regularisation.\n :param beta_2: Weighting of roughness regularisation.\n :param loss_margin: The loss margin.\n :param batch_size: Batch size.\n :param start_frame_index: The first frame to be perturbed.\n :param num_frames: The number of frames to be perturbed.\n :param round_samples: Granularity of the input values to be enforced if > 0.0.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.eps_step = eps_step\n self.max_iter = max_iter\n self.beta_0 = beta_0\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.loss_margin = loss_margin\n self.batch_size = batch_size\n self.start_frame_index = start_frame_index\n self.num_frames = num_frames\n self.round_samples = round_samples\n self.end_frame_index = (\n self.start_frame_index + self.num_frames if self.num_frames is not None else self.num_frames\n )\n self._targeted = targeted\n self.verbose = verbose\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial examples.\n\n :param x: Original input samples representing videos of format NFHWC.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n if y is None:\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as true labels\n logger.info(\"Using model predictions as true labels.\")\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n\n dataset = torch.utils.data.TensorDataset(\n torch.from_numpy(x.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(y.astype(ART_NUMPY_DTYPE)),\n )\n\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=self.batch_size, shuffle=False, drop_last=False\n )\n\n x_adv = x.copy().astype(ART_NUMPY_DTYPE)\n\n # Compute perturbation with batching\n for batch_id, batch_all in enumerate(\n tqdm(data_loader, desc=\"OverTheAirFlickeringPyTorch - Batches\", leave=False, disable=not self.verbose)\n ):\n (batch, batch_labels) = batch_all[0], batch_all[1]\n\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n x_adv[batch_index_1:batch_index_2] = self._generate_batch(batch, batch_labels)\n\n return x_adv\n\n def _generate_batch(self, x: \"torch.Tensor\", y: \"torch.Tensor\") -> np.ndarray:\n \"\"\"\n Generate a batch of adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n x = x.to(self.estimator.device)\n y = y.to(self.estimator.device)\n x_adv = torch.clone(x)\n\n for _ in range(self.max_iter):\n x_adv = self._compute_torch(\n x_adv,\n x,\n y,\n self.eps_step,\n )\n\n return x_adv.cpu().detach().numpy()\n\n def _compute_torch(\n self,\n x_adv: \"torch.Tensor\",\n x: \"torch.Tensor\",\n y: \"torch.Tensor\",\n eps_step: float,\n ) -> \"torch.Tensor\":\n \"\"\"\n Compute adversarial examples for one iteration.\n\n :param x_adv: Current adversarial examples.\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n # Get perturbation\n perturbation = x_adv - x\n grad = self._compute_perturbation(x_adv, y, perturbation)\n\n # Apply perturbation and clip\n x_adv = self._apply_perturbation(x_adv, grad, eps_step)\n\n return x_adv\n\n def _compute_perturbation(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\", perturbation: \"torch.Tensor\"\n ) -> \"torch.Tensor\":\n \"\"\"\n Compute perturbation.\n\n :param x: Current adversarial examples.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n :param perturbation: Currently, accumulated perturbation\n :return: Perturbations.\n \"\"\"\n import torch\n\n # Get gradient wrt loss\n grad = self._get_loss_gradients(x, y, perturbation)\n\n grad = torch.repeat_interleave(torch.repeat_interleave(grad, x.shape[2], dim=2), x.shape[3], dim=3)\n\n if self.start_frame_index is not None:\n full_grad = torch.zeros(x.shape, dtype=grad.dtype, device=grad.device)\n full_grad[:, self.start_frame_index : self.end_frame_index, :, :, :] = grad[\n :, self.start_frame_index : self.end_frame_index, :, :, :\n ]\n grad = full_grad\n\n return grad\n\n def _get_loss_gradients(self, x: \"torch.Tensor\", y: \"torch.Tensor\", perturbation: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute custom, framework-specific, regularized loss gradients.\n \"\"\"\n import torch\n\n softmax = torch.nn.Softmax(dim=1).to(self.estimator.device)\n\n grads_batch = []\n\n for i in range(x.shape[0]):\n eps = torch.autograd.Variable(\n torch.zeros((1, x.shape[1], 1, 1, x.shape[4]), device=self.estimator.device), requires_grad=True\n )\n x_in = x[[i]] + torch.repeat_interleave(torch.repeat_interleave(eps, x.shape[2], dim=2), x.shape[3], dim=3)\n x_in = self._clip_and_round_pytorch(x_in)\n preds, _ = self.estimator._predict_framework(x=x_in)\n\n # calculate adversarial loss\n y_preds = softmax(preds)[0]\n y_mask = y[i].eq(1)\n label_prob = torch.masked_select(y_preds, y_mask)\n max_non_label_prob = torch.max(y_preds - y[i], dim=0)[0]\n\n l_1 = torch.zeros(1).to(self.estimator.device)\n l_m = (label_prob - max_non_label_prob) * (1 - 2 * int(self.targeted)) + self.loss_margin\n l_2 = (l_m**2) / self.loss_margin\n l_3 = l_m\n\n adversarial_loss = torch.max(l_1, torch.min(l_2, l_3)[0])[0]\n\n # calculate regularization terms\n # thickness - loss term\n perturbation_i = perturbation[[i]] + eps\n norm_reg = torch.mean(perturbation_i**2) + 1e-12\n perturbation_roll_right = torch.roll(perturbation_i, 1, dims=1)\n perturbation_roll_left = torch.roll(perturbation_i, -1, dims=1)\n\n # 1st order diff - loss term\n diff_norm_reg = torch.mean((perturbation_i - perturbation_roll_right) ** 2) + 1e-12\n\n # 2nd order diff - loss term\n laplacian_norm_reg = (\n torch.mean((-2 * perturbation_i + perturbation_roll_right + perturbation_roll_left) ** 2) + 1e-12\n )\n\n regularization_loss = self.beta_0 * (\n self.beta_1 * norm_reg + self.beta_2 * diff_norm_reg + self.beta_2 * laplacian_norm_reg\n )\n\n loss = adversarial_loss + regularization_loss\n\n self.estimator.model.zero_grad()\n\n # Compute gradients\n loss.backward()\n grads = eps.grad\n if grads is not None:\n grads_batch.append(grads[0, ...])\n else:\n raise ValueError(\"Received None instead of gradient tensor.\")\n\n grads_batch_tensor = torch.stack(grads_batch)\n\n return grads_batch_tensor\n\n def _clip_and_round_pytorch(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Rounds the input to the correct level of granularity. Useful to ensure data passed to classifier can be\n represented in the correct domain, e.g., [0, 255] integers verses [0,1] or [0, 255] floating points.\n\n :param x: Sample input with shape as expected by the model.\n :return: Clipped and rounded inputs.\n \"\"\"\n import torch\n\n if self.estimator.clip_values is not None:\n x = torch.clamp(x, self.estimator.clip_values[0], self.estimator.clip_values[1])\n\n if self.round_samples != 0.0:\n x = torch.round(x / self.round_samples) * self.round_samples\n\n return x\n\n def _apply_perturbation(self, x_adv: \"torch.Tensor\", grad: \"torch.Tensor\", eps_step: float) -> \"torch.Tensor\":\n \"\"\"\n Apply perturbation on examples.\n\n :param x: Current adversarial examples.\n :param grad: Current gradients.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n x_adv = x_adv - eps_step * torch.sign(grad)\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = torch.max(\n torch.min(x_adv, torch.tensor(clip_max).to(self.estimator.device)),\n torch.tensor(clip_min).to(self.estimator.device),\n )\n\n return x_adv\n\n def _check_params(self) -> None:\n\n if not isinstance(self.eps_step, (int, float)) or self.eps_step <= 0.0:\n raise ValueError(\"The argument `eps_step` must be positive of type int or float.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n raise ValueError(\"The argument `max_iter` must be positive of type int.\")\n\n if not isinstance(self.beta_0, (int, float)) or self.beta_0 < 0.0:\n raise ValueError(\"The argument `beta_0` must be 0.0 or positive of type int or float.\")\n\n if not isinstance(self.beta_1, (int, float)) or self.beta_1 < 0.0:\n raise ValueError(\"The argument `beta_1` must be 0.0 or positive of type int or float.\")\n\n if not isinstance(self.beta_2, (int, float)) or self.beta_2 < 0.0:\n raise ValueError(\"The argument `beta_2` must be 0.0 or positive of type int or float.\")\n\n if not isinstance(self.loss_margin, (int, float)) or self.loss_margin <= 0.0:\n raise ValueError(\"The argument `loss_margin` must be positive of type int or float.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The argument `batch_size` must be positive of type int.\")\n\n if not isinstance(self.start_frame_index, int) or self.start_frame_index < 0:\n raise ValueError(\"The argument `start_frame_index` must be 0 or positive of type int.\")\n\n if self.num_frames is not None and (not isinstance(self.num_frames, int) or self.num_frames <= 0):\n raise ValueError(\"The argument `num_frames` must be positive of type int.\")\n\n if not isinstance(self.round_samples, (int, float)) or self.round_samples < 0.0:\n raise ValueError(\"The argument `round_samples` must be 0.0 or positive of type int or float.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/overload/box_iou.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# pylint: disable=invalid-name,missing-module-docstring\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2025\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n\n import torch\n\n\ndef box_iou(boxes1: \"torch.Tensor\", boxes2: \"torch.Tensor\", eps: float = 1e-7) -> \"torch.Tensor\":\n \"\"\"\n Compute the Intersection over Union (IoU) between two sets of bounding boxes.\n\n :param boxes1: Bounding boxes with shape (N, 4), format (x1, y1, x2, y2).\n :param boxes2: Bounding boxes with shape (M, 4), format (x1, y1, x2, y2).\n :param eps: Small value to avoid division by zero.\n\n :return: IoU matrix of shape (N, M) containing pairwise IoU values.\n \"\"\"\n import torch\n\n # Expand dimensions for broadcasting\n boxes1 = boxes1.unsqueeze(1) # (N, 1, 4)\n boxes2 = boxes2.unsqueeze(0) # (1, M, 4)\n\n # Calculate coordinates of the intersection rectangle\n top_left = torch.max(boxes1[..., :2], boxes2[..., :2]) # (N, M, 2)\n bottom_right = torch.min(boxes1[..., 2:], boxes2[..., 2:]) # (N, M, 2)\n\n # Compute width and height of the intersection\n inter_dims = (bottom_right - top_left).clamp(min=0) # (N, M, 2)\n inter_area = inter_dims.prod(dim=2) # (N, M)\n\n # Compute areas of each box\n area1 = (boxes1[..., 2:] - boxes1[..., :2]).prod(dim=2) # (N, 1)\n area2 = (boxes2[..., 2:] - boxes2[..., :2]).prod(dim=2) # (1, M)\n\n # Compute IoU\n union_area = area1 + area2 - inter_area\n iou = inter_area / (union_area + eps)\n\n return iou\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/overload/overload.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Overload attack. This is a white-box attack.\n\n| Paper link: https://arxiv.org/abs/2304.05370\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.overload.box_iou import box_iou\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import PYTORCH_OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass OverloadPyTorch(EvasionAttack):\n \"\"\"\n The overload attack.\n\n | Paper link: https://arxiv.org/abs/2304.05370\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"eps\",\n \"max_iter\",\n \"num_grid\",\n \"batch_size\",\n ]\n\n _estimator_requirements = ()\n\n def __init__(\n self,\n estimator: \"PYTORCH_OBJECT_DETECTOR_TYPE\",\n eps: float,\n max_iter: int,\n num_grid: int,\n batch_size: int,\n threshold: float,\n ) -> None:\n \"\"\"\n Create an overload attack instance.\n\n :param estimator: A PyTorch object detection estimator for a YOLO5 model.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param max_iter: The maximum number of iterations.\n :param num_grid: The number of grids for width and high dimension.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param threshold: IoU threshold.\n \"\"\"\n super().__init__(estimator=estimator)\n self.eps = eps\n self.max_iter = max_iter\n self.num_grid = num_grid\n self.batch_size = batch_size\n self.threshold = threshold\n self._check_params()\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Not used.\n :return: An array holding the adversarial examples.\n \"\"\"\n\n # Compute adversarial examples with implicit batching\n x_adv = x.copy()\n for batch_id in range(int(np.ceil(x_adv.shape[0] / float(self.batch_size)))):\n batch_index_1 = batch_id * self.batch_size\n batch_index_2 = min((batch_id + 1) * self.batch_size, x_adv.shape[0])\n x_batch = x_adv[batch_index_1:batch_index_2]\n x_adv[batch_index_1:batch_index_2] = self._generate_batch(x_batch)\n\n return x_adv\n\n def _generate_batch(self, x_batch: np.ndarray) -> np.ndarray:\n \"\"\"\n Run the attack on a batch of images.\n\n :param x_batch: A batch of original examples.\n :return: A batch of adversarial examples.\n \"\"\"\n\n import torch\n\n x_org = torch.from_numpy(x_batch).to(self.estimator.device)\n x_adv = x_org.clone()\n\n cond = torch.logical_or(x_org < 0.0, x_org > 1.0)\n if torch.any(cond):\n raise ValueError(\"The value of each pixel must be normalized in the range [0, 1].\")\n\n for _ in range(self.max_iter):\n x_adv = self._attack(x_adv, x_org)\n\n return x_adv.cpu().detach().numpy()\n\n def _attack(self, x_adv: \"torch.Tensor\", x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Run attack.\n\n :param x_batch: A batch of original examples.\n :param y_batch: Not Used.\n :return: A batch of adversarial examples.\n \"\"\"\n\n import torch\n\n x_adv.requires_grad_()\n with torch.enable_grad():\n loss, pixel_weight = self._loss(x_adv)\n grad = torch.autograd.grad(torch.mean(loss), [x_adv])[0]\n\n with torch.inference_mode():\n x_adv.add_(pixel_weight * torch.sign(grad))\n x_adv.clamp_(x - self.eps, x + self.eps)\n x_adv.clamp_(0.0, 1.0)\n\n x_adv.requires_grad_(False)\n return x_adv\n\n def _loss(self, x: \"torch.Tensor\") -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Compute the weight of each pixel and the overload loss for a given image.\n\n :param x: A given image\n :return: Overload loss and the weight of each pixel\n \"\"\"\n\n import torch\n\n adv_logits = self.estimator.model.model(x)\n if isinstance(adv_logits, tuple):\n adv_logits = adv_logits[0]\n\n conf = adv_logits[..., 4]\n prob = adv_logits[..., 5:]\n prob = torch.where(conf[:, :, None] * prob > self.threshold, torch.ones_like(prob), prob)\n prob = torch.sum(prob, dim=2)\n conf = conf * prob\n\n ind_loss = -(1.0 - conf) * (1.0 - conf)\n ind_loss = torch.sum(ind_loss, dim=1)\n\n pixel_weight = torch.ones_like(x)\n pixel_weight.requires_grad_(False)\n with torch.inference_mode():\n stride_x = x.shape[-2] // self.num_grid\n stride_y = x.shape[-1] // self.num_grid\n grid_box = torch.zeros((0, 4), device=x.device)\n for i_i in range(self.num_grid):\n for j_j in range(self.num_grid):\n x_1 = i_i * stride_x\n y_1 = j_j * stride_y\n x_2 = min(x_1 + stride_x, x.shape[-2])\n y_2 = min(y_1 + stride_y, x.shape[-1])\n b_b = torch.as_tensor([x_1, y_1, x_2, y_2], device=x.device)[None, :]\n grid_box = torch.cat([grid_box, b_b], dim=0)\n\n for x_i in range(x.shape[0]):\n xyhw = adv_logits[x_i, :, :4]\n prob = torch.max(adv_logits[x_i, :, 5:], dim=1).values\n box_idx = adv_logits[x_i, :, 4] * prob > self.threshold\n xyhw = xyhw[box_idx]\n c_xyxy = self.xywh2xyxy(xyhw)\n scores = box_iou(grid_box, c_xyxy)\n scores = torch.where(scores > 0.0, torch.ones_like(scores), torch.zeros_like(scores))\n scores = torch.sum(scores, dim=1)\n\n # a native implementation:\n # Increase the weight of the grid with fewer objects\n idx_min = torch.argmin(scores)\n grid_min = grid_box[idx_min]\n x_1, y_1, x_2, y_2 = grid_min.int()\n pixel_weight[x_i, :, y_1:y_2, x_1:x_2] = pixel_weight[x_i, :, y_1:y_2, x_1:x_2] * 2\n pixel_weight = pixel_weight / torch.max(pixel_weight[x_i, :]) / 255.0\n\n return ind_loss, pixel_weight\n\n @staticmethod\n def xywh2xyxy(xywh: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Convert the representation from xywh format yo xyxy format.\n\n :param xyhw: An n by 4 boxes store the information in xyhw format\n where [x ,y, w h] is [center_x, center_y, width, height]\n :return: The n by 4 boxes in xyxy format\n where [x1, y1, x2, y2] is [top_left_x, top_left_y, bottom_right_x, bottom_right_y]\n \"\"\"\n xyxy = xywh.clone()\n xyxy[:, 0] = xywh[:, 0] - xywh[:, 2] / 2\n xyxy[:, 1] = xywh[:, 1] - xywh[:, 3] / 2\n xyxy[:, 2] = xywh[:, 0] + xywh[:, 2] / 2\n xyxy[:, 3] = xywh[:, 1] + xywh[:, 3] / 2\n return xyxy\n\n def _check_params(self) -> None:\n\n if not isinstance(self.eps, float):\n raise TypeError(\"The eps has to be of type float.\")\n\n if self.eps < 0 or self.eps > 1:\n raise ValueError(\"The eps must be in the range [0, 1].\")\n\n if not isinstance(self.max_iter, int):\n raise TypeError(\"The max_iter has to be of type int.\")\n\n if self.max_iter < 1:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if not isinstance(self.num_grid, int):\n raise TypeError(\"The num_grid has to be of type int.\")\n\n if self.num_grid < 1:\n raise ValueError(\"The number of grid must be a positive integer.\")\n\n if not isinstance(self.batch_size, int):\n raise TypeError(\"The batch_size has to be of type int.\")\n\n if self.batch_size < 1:\n raise ValueError(\"The batch size must be a positive integer.\")\n\n if self.threshold < 0.0 or self.threshold > 1.0:\n raise ValueError(\"The threshold must be in the range [0, 1].\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/projected_gradient_descent/projected_gradient_descent.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Projected Gradient Descent attack `ProjectedGradientDescent` as an iterative method in which,\nafter each iteration, the perturbation is projected on a lp-ball of specified radius (in addition to clipping the\nvalues of the adversarial sample so that it lies in the permitted data range). This is the attack proposed by Madry et\nal. for adversarial training.\n\n| Paper link: https://arxiv.org/abs/1706.06083\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_numpy import (\n ProjectedGradientDescentNumpy,\n)\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_pytorch import (\n ProjectedGradientDescentPyTorch,\n)\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_tensorflow_v2 import (\n ProjectedGradientDescentTensorFlowV2,\n)\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE, OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectedGradientDescent(EvasionAttack):\n \"\"\"\n The Projected Gradient Descent attack is an iterative method in which, after each iteration, the perturbation is\n projected on a lp-ball of specified radius (in addition to clipping the values of the adversarial sample so that it\n lies in the permitted data range). This is the attack proposed by Madry et al. for adversarial training.\n\n | Paper link: https://arxiv.org/abs/1706.06083\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"decay\",\n \"targeted\",\n \"num_random_init\",\n \"batch_size\",\n \"max_iter\",\n \"random_eps\",\n \"summary_writer\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\" | \"OBJECT_DETECTOR_TYPE\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n decay: float | None = None,\n max_iter: int = 100,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 32,\n random_eps: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.ProjectedGradientDescent` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation, supporting \"inf\", `np.inf` or a real `p >= 1`.\n Currently, when `p` is not infinity, the projection step only rescales the noise, which may be\n suboptimal for `p != 2`.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_eps: When True, epsilon is drawn randomly from truncated normal distribution. The literature\n suggests this for FGSM based training to generalize across different epsilons. eps_step\n is modified to preserve the ratio of eps / eps_step. The effectiveness of this\n method with PGD is untested (https://arxiv.org/pdf/1611.01236.pdf).\n :param decay: Decay factor for accumulating the velocity vector when using momentum.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting\n at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=estimator, summary_writer=False)\n\n self.norm = norm\n self.eps = eps\n self.eps_step = eps_step\n self.max_iter = max_iter\n self.targeted = targeted\n self.num_random_init = num_random_init\n self.batch_size = batch_size\n self.random_eps = random_eps\n self.verbose = verbose\n ProjectedGradientDescent._check_params(self)\n\n self._attack: (\n ProjectedGradientDescentPyTorch | ProjectedGradientDescentTensorFlowV2 | ProjectedGradientDescentNumpy\n )\n if isinstance(self.estimator, PyTorchClassifier) and self.estimator.all_framework_preprocessing:\n self._attack = ProjectedGradientDescentPyTorch(\n estimator=estimator, # type: ignore\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n random_eps=random_eps,\n summary_writer=summary_writer,\n verbose=verbose,\n )\n\n elif isinstance(self.estimator, TensorFlowV2Classifier) and self.estimator.all_framework_preprocessing:\n self._attack = ProjectedGradientDescentTensorFlowV2(\n estimator=estimator, # type: ignore\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n random_eps=random_eps,\n summary_writer=summary_writer,\n verbose=verbose,\n )\n\n else:\n self._attack = ProjectedGradientDescentNumpy(\n estimator=estimator,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n random_eps=random_eps,\n summary_writer=summary_writer,\n verbose=verbose,\n )\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n logger.info(\"Creating adversarial samples.\")\n return self._attack.generate(x=x, y=y, **kwargs)\n\n @property\n def summary_writer(self):\n \"\"\"The summary writer.\"\"\"\n return self._attack.summary_writer\n\n def set_params(self, **kwargs) -> None:\n super().set_params(**kwargs)\n self._attack.set_params(**kwargs)\n\n def _check_params(self) -> None:\n\n norm: float = np.inf if self.norm == \"inf\" else float(self.norm)\n if norm < 1:\n raise ValueError('Norm order must be either \"inf\", `np.inf` or a real `p >= 1`.')\n\n if not (\n isinstance(self.eps, (int, float))\n and isinstance(self.eps_step, (int, float))\n or isinstance(self.eps, np.ndarray)\n and isinstance(self.eps_step, np.ndarray)\n ):\n raise TypeError(\n \"The perturbation size `eps` and the perturbation step-size `eps_step` must have the same type of `int`\"\n \", `float`, or `np.ndarray`.\"\n )\n\n if isinstance(self.eps, (int, float)):\n if self.eps < 0:\n raise ValueError(\"The perturbation size `eps` has to be nonnegative.\")\n else:\n if (self.eps < 0).any():\n raise ValueError(\"The perturbation size `eps` has to be nonnegative.\")\n\n if isinstance(self.eps_step, (int, float)):\n if self.eps_step <= 0:\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n else:\n if (self.eps_step <= 0).any():\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if self.eps.shape != self.eps_step.shape:\n raise ValueError(\n \"The perturbation size `eps` and the perturbation step-size `eps_step` must have the same shape.\"\n )\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The flag `targeted` has to be of type bool.\")\n\n if not isinstance(self.num_random_init, int):\n raise TypeError(\"The number of random initialisations has to be of type integer.\")\n\n if self.num_random_init < 0:\n raise ValueError(\"The number of random initialisations `random_init` has to be greater than or equal to 0.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if self.max_iter < 0:\n raise ValueError(\"The number of iterations `max_iter` has to be a nonnegative integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The verbose has to be a Boolean.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/projected_gradient_descent/projected_gradient_descent_numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Projected Gradient Descent attack `ProjectedGradientDescent` as an iterative method in which,\nafter each iteration, the perturbation is projected on a lp-ball of specified radius (in addition to clipping the\nvalues of the adversarial sample so that it lies in the permitted data range). This is the attack proposed by Madry et\nal. for adversarial training.\n\n| Paper link: https://arxiv.org/abs/1706.06083\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.stats import truncnorm\nfrom tqdm.auto import trange\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.utils import compute_success, get_labels_np_array, check_and_transform_label_format, compute_success_array\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE, OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectedGradientDescentCommon(FastGradientMethod):\n \"\"\"\n Common class for different variations of implementation of the Projected Gradient Descent attack. The attack is an\n iterative method in which, after each iteration, the perturbation is projected on a lp-ball of specified radius (in\n addition to clipping the values of the adversarial sample so that it lies in the permitted data range). This is the\n attack proposed by Madry et al. for adversarial training.\n\n | Paper link: https://arxiv.org/abs/1706.06083\n \"\"\"\n\n attack_params = FastGradientMethod.attack_params + [\"decay\", \"max_iter\", \"random_eps\", \"verbose\"]\n _estimator_requirements = (BaseEstimator, LossGradientsMixin)\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\" | \"OBJECT_DETECTOR_TYPE\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n decay: float | None = None,\n max_iter: int = 100,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 32,\n random_eps: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a :class:`.ProjectedGradientDescentCommon` instance.\n\n :param estimator: A trained classifier.\n :param norm: The norm of the adversarial perturbation, supporting \"inf\", `np.inf` or a real `p >= 1`.\n Currently, when `p` is not infinity, the projection step only rescales the noise, which may be\n suboptimal for `p != 2`.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_eps: When True, epsilon is drawn randomly from truncated normal distribution. The literature\n suggests this for FGSM based training to generalize across different epsilons. eps_step is\n modified to preserve the ratio of eps / eps_step. The effectiveness of this method with PGD\n is untested (https://arxiv.org/pdf/1611.01236.pdf).\n :param decay: Decay factor for accumulating the velocity vector when using momentum.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0\n starting at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n estimator=estimator, # type: ignore\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n minimal=False,\n summary_writer=summary_writer,\n )\n self.decay = decay\n self.max_iter = max_iter\n self.random_eps = random_eps\n self.verbose = verbose\n ProjectedGradientDescentCommon._check_params(self)\n\n lower: int | float | np.ndarray\n upper: int | float | np.ndarray\n var_mu: int | float | np.ndarray\n sigma: int | float | np.ndarray\n\n if self.random_eps:\n if isinstance(eps, (int, float)):\n lower, upper = 0, eps\n var_mu, sigma = 0, (eps / 2)\n else:\n lower, upper = np.zeros_like(eps), eps\n var_mu, sigma = np.zeros_like(eps), (eps / 2)\n\n self.norm_dist = truncnorm((lower - var_mu) / sigma, (upper - var_mu) / sigma, loc=var_mu, scale=sigma)\n\n def _random_eps(self):\n \"\"\"\n Check whether random eps is enabled, then scale eps and eps_step appropriately.\n \"\"\"\n if self.random_eps:\n ratio = self.eps_step / self.eps\n\n if isinstance(self.eps, (int, float)):\n self.eps = np.round(self.norm_dist.rvs(1)[0], 10)\n else:\n self.eps = np.round(self.norm_dist.rvs(size=self.eps.shape), 10)\n\n self.eps_step = ratio * self.eps\n\n def _set_targets(self, x: np.ndarray, y: np.ndarray | None, classifier_mixin: bool = True) -> np.ndarray:\n \"\"\"\n Check and set up targets.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param classifier_mixin: Whether the estimator is of type `ClassifierMixin`.\n :return: The targets.\n \"\"\"\n if classifier_mixin:\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if y is None:\n # Throw error if attack is targeted, but no targets are provided\n if self.targeted: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n # Use model predictions as correct outputs\n if classifier_mixin:\n targets = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n else:\n targets = self.estimator.predict(x, batch_size=self.batch_size)\n\n else:\n targets = y\n\n return targets\n\n def _check_params(self) -> None: # pragma: no cover\n\n norm: float = np.inf if self.norm == \"inf\" else float(self.norm)\n if norm < 1:\n raise ValueError('Norm order must be either \"inf\", `np.inf` or a real `p >= 1`.')\n\n if not (\n isinstance(self.eps, (int, float))\n and isinstance(self.eps_step, (int, float))\n or isinstance(self.eps, np.ndarray)\n and isinstance(self.eps_step, np.ndarray)\n ):\n raise TypeError(\n \"The perturbation size `eps` and the perturbation step-size `eps_step` must have the same type of `int`\"\n \", `float`, or `np.ndarray`.\"\n )\n\n if isinstance(self.eps, (int, float)):\n if self.eps < 0:\n raise ValueError(\"The perturbation size `eps` has to be non-negative.\")\n else:\n if (self.eps < 0).any():\n raise ValueError(\"The perturbation size `eps` has to be non-negative.\")\n\n if isinstance(self.eps_step, (int, float)):\n if self.eps_step <= 0:\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n else:\n if (self.eps_step <= 0).any():\n raise ValueError(\"The perturbation step-size `eps_step` has to be positive.\")\n\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if self.eps.shape != self.eps_step.shape:\n raise ValueError(\n \"The perturbation size `eps` and the perturbation step-size `eps_step` must have the same shape.\"\n )\n\n if not isinstance(self.targeted, bool):\n raise ValueError(\"The flag `targeted` has to be of type bool.\")\n\n if not isinstance(self.num_random_init, int):\n raise TypeError(\"The number of random initialisations has to be of type integer.\")\n\n if self.num_random_init < 0:\n raise ValueError(\"The number of random initialisations `random_init` has to be greater than or equal to 0.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if self.max_iter < 0:\n raise ValueError(\"The number of iterations `max_iter` has to be a non-negative integer.\")\n\n if self.decay is not None and self.decay < 0.0:\n raise ValueError(\"The decay factor `decay` has to be a nonnegative float.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The verbose has to be a Boolean.\")\n\n\nclass ProjectedGradientDescentNumpy(ProjectedGradientDescentCommon):\n \"\"\"\n The Projected Gradient Descent attack is an iterative method in which, after each iteration, the perturbation is\n projected on a lp-ball of specified radius (in addition to clipping the values of the adversarial sample so that it\n lies in the permitted data range). This is the attack proposed by Madry et al. for adversarial training.\n\n | Paper link: https://arxiv.org/abs/1706.06083\n \"\"\"\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\" | \"OBJECT_DETECTOR_TYPE\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n decay: float | None = None,\n max_iter: int = 100,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 32,\n random_eps: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a :class:`.ProjectedGradientDescentNumpy` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation, supporting \"inf\", `np.inf` or a real `p >= 1`.\n Currently, when `p` is not infinity, the projection step only rescales the noise, which may be\n suboptimal for `p != 2`.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_eps: When True, epsilon is drawn randomly from truncated normal distribution. The literature\n suggests this for FGSM based training to generalize across different epsilons. eps_step\n is modified to preserve the ratio of eps / eps_step. The effectiveness of this method with\n PGD is untested (https://arxiv.org/pdf/1611.01236.pdf).\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False)\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting\n at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n if summary_writer and num_random_init > 1:\n raise ValueError(\"TensorBoard is not yet supported for more than 1 random restart (num_random_init>1).\")\n\n super().__init__(\n estimator=estimator,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n random_eps=random_eps,\n summary_writer=summary_writer,\n verbose=verbose,\n )\n\n self._project = True\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n mask = self._get_mask(x, **kwargs)\n\n # Ensure eps is broadcastable\n self._check_compatibility_input_and_eps(x=x)\n\n # Check whether random eps is enabled\n self._random_eps()\n\n if isinstance(self.estimator, ClassifierMixin):\n # Set up targets\n targets = self._set_targets(x, y)\n\n # Start to compute adversarial examples\n adv_x = x.astype(ART_NUMPY_DTYPE)\n\n for batch_id in range(int(np.ceil(x.shape[0] / float(self.batch_size)))):\n\n self._batch_id = batch_id\n\n for rand_init_num in trange(\n max(1, self.num_random_init), desc=\"PGD - Random Initializations\", disable=not self.verbose\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch_index_2 = min(batch_index_2, x.shape[0])\n batch = x[batch_index_1:batch_index_2]\n batch_labels = targets[batch_index_1:batch_index_2]\n mask_batch = mask\n\n if mask is not None:\n if len(mask.shape) == len(x.shape):\n mask_batch = mask[batch_index_1:batch_index_2]\n\n momentum = np.zeros(batch.shape)\n\n for i_max_iter in trange(\n self.max_iter, desc=\"PGD - Iterations\", leave=False, disable=not self.verbose\n ):\n self._i_max_iter = i_max_iter\n\n batch = self._compute(\n batch,\n x[batch_index_1:batch_index_2],\n batch_labels,\n mask_batch,\n self.eps,\n self.eps_step,\n self._project,\n self.num_random_init > 0 and i_max_iter == 0,\n self._batch_id,\n decay=self.decay,\n momentum=momentum,\n )\n\n if rand_init_num == 0:\n # initial (and possibly only) random restart: we only have this set of\n # adversarial examples for now\n adv_x[batch_index_1:batch_index_2] = np.copy(batch)\n else:\n # replace adversarial examples if they are successful\n attack_success = compute_success_array(\n self.estimator, # type: ignore\n x[batch_index_1:batch_index_2],\n targets[batch_index_1:batch_index_2],\n batch,\n self.targeted,\n batch_size=self.batch_size,\n )\n adv_x[batch_index_1:batch_index_2][attack_success] = batch[attack_success]\n\n logger.info(\n \"Success rate of attack: %.2f%%\",\n 100\n * compute_success(\n self.estimator, # type: ignore\n x,\n targets,\n adv_x,\n self.targeted,\n batch_size=self.batch_size, # type: ignore\n ),\n )\n else:\n if self.num_random_init > 0: # pragma: no cover\n raise ValueError(\"Random initialisation is only supported for classification.\")\n\n # Set up targets\n targets = self._set_targets(x, y, classifier_mixin=False)\n\n # Start to compute adversarial examples\n if x.dtype == object:\n adv_x = x.copy()\n else:\n adv_x = x.astype(ART_NUMPY_DTYPE)\n\n momentum = np.zeros(adv_x.shape)\n\n for i_max_iter in trange(self.max_iter, desc=\"PGD - Iterations\", disable=not self.verbose):\n self._i_max_iter = i_max_iter\n\n adv_x = self._compute(\n adv_x,\n x,\n targets,\n mask,\n self.eps,\n self.eps_step,\n self._project,\n self.num_random_init > 0 and i_max_iter == 0,\n decay=self.decay,\n momentum=momentum,\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return adv_x\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/projected_gradient_descent/projected_gradient_descent_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Projected Gradient Descent attack `ProjectedGradientDescent` as an iterative method in which,\nafter each iteration, the perturbation is projected on a lp-ball of specified radius (in addition to clipping the\nvalues of the adversarial sample so that it lies in the permitted data range). This is the attack proposed by Madry et\nal. for adversarial training.\n\n| Paper link: https://arxiv.org/abs/1706.06083\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.summary_writer import SummaryWriter\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_numpy import (\n ProjectedGradientDescentCommon,\n)\nfrom art.utils import compute_success, random_sphere, compute_success_array\n\nif TYPE_CHECKING:\n\n import torch\n from art.estimators.classification.pytorch import PyTorchClassifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectedGradientDescentPyTorch(ProjectedGradientDescentCommon):\n \"\"\"\n The Projected Gradient Descent attack is an iterative method in which, after each iteration, the perturbation is\n projected on a lp-ball of specified radius (in addition to clipping the values of the adversarial sample so that it\n lies in the permitted data range). This is the attack proposed by Madry et al. for adversarial training.\n\n | Paper link: https://arxiv.org/abs/1706.06083\n \"\"\"\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin) # type: ignore\n\n def __init__(\n self,\n estimator: \"PyTorchClassifier\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n decay: float | None = None,\n max_iter: int = 100,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 32,\n random_eps: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.ProjectedGradientDescentPyTorch` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation, supporting \"inf\", `np.inf` or a real `p >= 1`.\n Currently, when `p` is not infinity, the projection step only rescales the noise, which may be\n suboptimal for `p != 2`.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_eps: When True, epsilon is drawn randomly from truncated normal distribution. The literature\n suggests this for FGSM based training to generalize across different epsilons. eps_step is\n modified to preserve the ratio of eps / eps_step. The effectiveness of this method with PGD\n is untested (https://arxiv.org/pdf/1611.01236.pdf).\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting\n at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n if not estimator.all_framework_preprocessing:\n raise NotImplementedError(\n \"The framework-specific implementation only supports framework-specific preprocessing.\"\n )\n\n if summary_writer and num_random_init > 1:\n raise ValueError(\"TensorBoard is not yet supported for more than 1 random restart (num_random_init>1).\")\n\n super().__init__(\n estimator=estimator,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n random_eps=random_eps,\n verbose=verbose,\n summary_writer=summary_writer,\n )\n\n self._batch_id = 0\n self._i_max_iter = 0\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n import torch\n\n mask = self._get_mask(x, **kwargs)\n\n # Ensure eps is broadcastable\n self._check_compatibility_input_and_eps(x=x)\n\n # Check whether random eps is enabled\n self._random_eps()\n\n # Set up targets\n targets = self._set_targets(x, y)\n\n # Create dataset\n if mask is not None:\n # Here we need to make a distinction: if the masks are different for each input, we need to index\n # those for the current batch. Otherwise, (i.e. mask is meant to be broadcasted), keep it as it is.\n if len(mask.shape) == len(x.shape):\n dataset = torch.utils.data.TensorDataset(\n torch.from_numpy(x.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(targets.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(mask.astype(ART_NUMPY_DTYPE)),\n )\n\n else:\n dataset = torch.utils.data.TensorDataset(\n torch.from_numpy(x.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(targets.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(np.array([mask.astype(ART_NUMPY_DTYPE)] * x.shape[0])),\n )\n\n else:\n dataset = torch.utils.data.TensorDataset(\n torch.from_numpy(x.astype(ART_NUMPY_DTYPE)),\n torch.from_numpy(targets.astype(ART_NUMPY_DTYPE)),\n )\n\n data_loader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=self.batch_size, shuffle=False, drop_last=False\n )\n\n # Start to compute adversarial examples\n adv_x = x.astype(ART_NUMPY_DTYPE)\n\n # Compute perturbation with batching\n for batch_id, batch_all in enumerate(\n tqdm(data_loader, desc=\"PGD - Batches\", leave=False, disable=not self.verbose)\n ):\n\n self._batch_id = batch_id\n\n if mask is not None:\n (batch, batch_labels, mask_batch) = batch_all[0], batch_all[1], batch_all[2]\n else:\n (batch, batch_labels, mask_batch) = batch_all[0], batch_all[1], None\n\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n\n batch_eps: int | float | np.ndarray\n batch_eps_step: int | float | np.ndarray\n\n # Compute batch_eps and batch_eps_step\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if len(self.eps.shape) == len(x.shape) and self.eps.shape[0] == x.shape[0]:\n batch_eps = self.eps[batch_index_1:batch_index_2]\n batch_eps_step = self.eps_step[batch_index_1:batch_index_2]\n\n else:\n batch_eps = self.eps\n batch_eps_step = self.eps_step\n\n else:\n batch_eps = self.eps\n batch_eps_step = self.eps_step\n\n for rand_init_num in range(max(1, self.num_random_init)):\n if rand_init_num == 0:\n # first iteration: use the adversarial examples as they are the only ones we have now\n adv_x[batch_index_1:batch_index_2] = self._generate_batch(\n x=batch, targets=batch_labels, mask=mask_batch, eps=batch_eps, eps_step=batch_eps_step\n )\n else:\n adversarial_batch = self._generate_batch(\n x=batch, targets=batch_labels, mask=mask_batch, eps=batch_eps, eps_step=batch_eps_step\n )\n\n # return the successful adversarial examples\n attack_success = compute_success_array(\n self.estimator,\n batch,\n batch_labels,\n adversarial_batch,\n self.targeted,\n batch_size=self.batch_size,\n )\n adv_x[batch_index_1:batch_index_2][attack_success] = adversarial_batch[attack_success]\n\n logger.info(\n \"Success rate of attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, targets, adv_x, self.targeted, batch_size=self.batch_size),\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return adv_x\n\n def _generate_batch(\n self,\n x: \"torch.Tensor\",\n targets: \"torch.Tensor\",\n mask: \"torch.Tensor\",\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n ) -> np.ndarray:\n \"\"\"\n Generate a batch of adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param targets: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n inputs = x.to(self.estimator.device)\n targets = targets.to(self.estimator.device)\n adv_x = torch.clone(inputs)\n momentum = torch.zeros(inputs.shape).to(self.estimator.device)\n\n if mask is not None:\n mask = mask.to(self.estimator.device)\n\n for i_max_iter in range(self.max_iter):\n self._i_max_iter = i_max_iter\n adv_x = self._compute_pytorch(\n adv_x, inputs, targets, mask, eps, eps_step, self.num_random_init > 0 and i_max_iter == 0, momentum\n )\n\n return adv_x.cpu().detach().numpy()\n\n def _compute_perturbation_pytorch(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\", mask: \"torch.Tensor\" | None, momentum: \"torch.Tensor\"\n ) -> \"torch.Tensor\":\n \"\"\"\n Compute perturbations.\n\n :param x: Current adversarial examples.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :return: Perturbations.\n \"\"\"\n import torch\n\n # Get gradient wrt loss; invert it if attack is targeted\n grad = self.estimator.loss_gradient(x=x, y=y) * (-1 if self.targeted else 1)\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n self.summary_writer.update(\n batch_id=self._batch_id,\n global_step=self._i_max_iter,\n grad=grad.cpu().detach().numpy(),\n patch=None,\n estimator=self.estimator,\n x=x.cpu().detach().numpy(),\n y=y.cpu().detach().numpy(),\n targeted=self.targeted,\n )\n\n # Check for nan before normalisation and replace with 0\n if torch.any(grad.isnan()): # pragma: no cover\n logger.warning(\"Elements of the loss gradient are NaN and have been replaced with 0.0.\")\n grad[grad.isnan()] = 0.0\n\n # Apply mask\n if mask is not None:\n grad = torch.where(mask == 0.0, torch.tensor(0.0).to(self.estimator.device), grad)\n\n # Compute gradient momentum\n if self.decay is not None:\n # Update momentum in-place (important).\n # The L1 normalization for accumulation is an arbitrary choice of the paper.\n grad_2d = grad.reshape(len(grad), -1)\n norm1 = torch.linalg.norm(grad_2d, ord=1, dim=1, keepdim=True)\n normalized_grad = (grad_2d * norm1.where(norm1 == 0, 1 / norm1)).reshape(grad.shape)\n momentum *= self.decay\n momentum += normalized_grad\n # Use the momentum to compute the perturbation, instead of the gradient\n grad = momentum\n\n # Apply norm bound\n norm: float = np.inf if self.norm == \"inf\" else float(self.norm)\n grad_2d = grad.reshape(len(grad), -1)\n if norm == np.inf:\n grad_2d = torch.ones_like(grad_2d)\n elif norm == 1:\n i_max = torch.argmax(grad_2d.abs(), dim=1)\n grad_2d = torch.zeros_like(grad_2d)\n grad_2d[range(len(grad_2d)), i_max] = 1\n elif norm > 1:\n conjugate = norm / (norm - 1)\n q_norm = torch.linalg.norm(grad_2d, ord=conjugate, dim=1, keepdim=True)\n grad_2d = (grad_2d.abs() * q_norm.where(q_norm == 0, 1 / q_norm)) ** (conjugate - 1)\n\n grad = grad_2d.reshape(grad.shape) * grad.sign()\n\n assert x.shape == grad.shape\n\n return grad\n\n def _apply_perturbation_pytorch(\n self, x: \"torch.Tensor\", perturbation: \"torch.Tensor\", eps_step: int | float | np.ndarray\n ) -> \"torch.Tensor\":\n \"\"\"\n Apply perturbation on examples.\n\n :param x: Current adversarial examples.\n :param perturbation: Current perturbations.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n eps_step = np.array(eps_step, dtype=ART_NUMPY_DTYPE)\n perturbation_step = torch.tensor(eps_step).to(self.estimator.device) * perturbation\n perturbation_step[torch.isnan(perturbation_step)] = 0\n x = x + perturbation_step\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x = torch.max(\n torch.min(x, torch.tensor(clip_max).to(self.estimator.device)),\n torch.tensor(clip_min).to(self.estimator.device),\n )\n\n return x\n\n def _compute_pytorch(\n self,\n x: \"torch.Tensor\",\n x_init: \"torch.Tensor\",\n y: \"torch.Tensor\",\n mask: \"torch.Tensor\",\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n random_init: bool,\n momentum: \"torch.Tensor\",\n ) -> \"torch.Tensor\":\n \"\"\"\n Compute adversarial examples for one iteration.\n\n :param x: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236).\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_init: Random initialisation within the epsilon ball. For random_init=False starting at the\n original input.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n if random_init:\n n = x.shape[0]\n m = np.prod(x.shape[1:]).item()\n\n random_perturbation_array = random_sphere(n, m, eps, self.norm).reshape(x.shape).astype(ART_NUMPY_DTYPE)\n random_perturbation = torch.from_numpy(random_perturbation_array).to(self.estimator.device)\n\n if mask is not None:\n random_perturbation = random_perturbation * mask\n\n x_adv = x + random_perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = torch.max(\n torch.min(x_adv, torch.tensor(clip_max).to(self.estimator.device)),\n torch.tensor(clip_min).to(self.estimator.device),\n )\n\n else:\n x_adv = x\n\n # Get perturbation\n perturbation = self._compute_perturbation_pytorch(x_adv, y, mask, momentum)\n\n # Apply perturbation and clip\n x_adv = self._apply_perturbation_pytorch(x_adv, perturbation, eps_step)\n\n # Do projection\n perturbation = self._projection(x_adv - x_init, eps, self.norm)\n\n # Recompute x_adv\n x_adv = perturbation + x_init\n\n return x_adv\n\n @staticmethod\n def _projection(\n values: \"torch.Tensor\",\n eps: int | float | np.ndarray,\n norm_p: int | float | str,\n *,\n suboptimal: bool = True,\n ) -> \"torch.Tensor\":\n \"\"\"\n Project `values` on the L_p norm ball of size `eps`.\n\n :param values: Values to clip.\n :param eps: If a scalar, the norm of the L_p ball onto which samples are projected. Equivalently in general,\n can be any array of non-negatives broadcastable with `values`, and the projection occurs onto the\n unit ball for the weighted L_{p, w} norm with `w = 1 / eps`. Currently, for any given sample,\n non-uniform weights are only supported with infinity norm. Example: To specify sample-wise scalar,\n you can provide `eps.shape = (n_samples,) + (1,) * values[0].ndim`.\n :param norm_p: Lp norm to use for clipping, with `norm_p > 0`. Only 2, `np.inf` and \"inf\" are supported\n with `suboptimal=False` for now.\n :param suboptimal: If `True` simply projects by rescaling to Lp ball. Fast but may be suboptimal for\n `norm_p != 2`.\n Ignored when `norm_p in [np.inf, \"inf\"]` because optimal solution is fast. Defaults to `True`.\n :return: Values of `values` after projection.\n \"\"\"\n import torch\n\n norm = np.inf if norm_p == \"inf\" else float(norm_p)\n assert norm > 0\n\n values_tmp = values.reshape(len(values), -1) # (n_samples, d)\n\n eps = np.broadcast_to(eps, values.shape)\n eps = eps.reshape(len(eps), -1) # (n_samples, d)\n assert np.all(eps >= 0)\n if norm != np.inf and not np.all(eps == eps[:, [0]]):\n raise NotImplementedError(\n \"Projection onto the weighted L_p ball is currently not supported with finite `norm_p`.\"\n )\n\n if (suboptimal or norm == 2) and norm != np.inf: # Simple rescaling\n values_norm = torch.linalg.norm(values_tmp, ord=norm, dim=1, keepdim=True) # (n_samples, 1)\n values_tmp = values_tmp * values_norm.where(\n values_norm == 0,\n torch.minimum(\n torch.ones(1).to(values_tmp.device), torch.tensor(eps).to(values_tmp.device) / values_norm\n ),\n )\n else: # Optimal\n if norm == np.inf: # Easy exact case\n values_tmp = values_tmp.sign() * torch.minimum(\n values_tmp.abs(), torch.tensor(eps).to(values_tmp.device)\n )\n elif norm >= 1: # Convex optim\n raise NotImplementedError(\n \"Finite values of `norm_p >= 1` are currently not supported with `suboptimal=False`.\"\n )\n else: # Non-convex optim\n raise NotImplementedError(\"Values of `norm_p < 1` are currently not supported with `suboptimal=False`\")\n\n values = values_tmp.reshape(values.shape).to(values.dtype)\n\n return values\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/projected_gradient_descent/projected_gradient_descent_tensorflow_v2.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Projected Gradient Descent attack `ProjectedGradientDescent` as an iterative method in which,\nafter each iteration, the perturbation is projected on a lp-ball of specified radius (in addition to clipping the\nvalues of the adversarial sample so that it lies in the permitted data range). This is the attack proposed by Madry et\nal. for adversarial training.\n\n| Paper link: https://arxiv.org/abs/1706.06083\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_numpy import (\n ProjectedGradientDescentCommon,\n)\nfrom art.utils import compute_success, random_sphere, compute_success_array\nfrom art.summary_writer import SummaryWriter\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from art.estimators.classification.tensorflow import TensorFlowV2Classifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectedGradientDescentTensorFlowV2(ProjectedGradientDescentCommon):\n \"\"\"\n The Projected Gradient Descent attack is an iterative method in which, after each iteration, the perturbation is\n projected on a lp-ball of specified radius (in addition to clipping the values of the adversarial sample so that it\n lies in the permitted data range). This is the attack proposed by Madry et al. for adversarial training.\n\n | Paper link: https://arxiv.org/abs/1706.06083\n \"\"\"\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin) # type: ignore\n\n def __init__(\n self,\n estimator: \"TensorFlowV2Classifier\",\n norm: int | float | str = np.inf,\n eps: int | float | np.ndarray = 0.3,\n eps_step: int | float | np.ndarray = 0.1,\n decay: float | None = None,\n max_iter: int = 100,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 32,\n random_eps: bool = False,\n summary_writer: str | bool | SummaryWriter = False,\n verbose: bool = True,\n ):\n \"\"\"\n Create a :class:`.ProjectedGradientDescentTensorFlowV2` instance.\n\n :param estimator: A trained estimator.\n :param norm: The norm of the adversarial perturbation, supporting \"inf\", `np.inf` or a real `p >= 1`.\n Currently, when `p` is not infinity, the projection step only rescales the noise, which may be\n suboptimal for `p != 2`.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_eps: When True, epsilon is drawn randomly from truncated normal distribution. The literature\n suggests this for FGSM based training to generalize across different epsilons. eps_step is\n modified to preserve the ratio of eps / eps_step. The effectiveness of this method with PGD\n is untested (https://arxiv.org/pdf/1611.01236.pdf).\n :param decay: Decay factor for accumulating the velocity vector when using momentum.\n :param max_iter: The maximum number of iterations.\n :param targeted: Indicates whether the attack is targeted (True) or untargeted (False).\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting\n at the original input.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param summary_writer: Activate summary writer for TensorBoard.\n Default is `False` and deactivated summary writer.\n If `True` save runs/CURRENT_DATETIME_HOSTNAME in current directory.\n If of type `str` save in path.\n If of type `SummaryWriter` apply provided custom summary writer.\n Use hierarchical folder structure to compare between runs easily. e.g. pass in\n \u2018runs/exp1\u2019, \u2018runs/exp2\u2019, etc. for each new experiment to compare across them.\n :param verbose: Show progress bars.\n \"\"\"\n if not estimator.all_framework_preprocessing:\n raise NotImplementedError(\n \"The framework-specific implementation only supports framework-specific preprocessing.\"\n )\n\n if summary_writer and num_random_init > 1:\n raise ValueError(\"TensorBoard is not yet supported for more than 1 random restart (num_random_init>1).\")\n\n super().__init__(\n estimator=estimator,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n decay=decay,\n max_iter=max_iter,\n targeted=targeted,\n num_random_init=num_random_init,\n batch_size=batch_size,\n random_eps=random_eps,\n summary_writer=summary_writer,\n verbose=verbose,\n )\n\n def generate(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :type mask: `np.ndarray`\n :return: An array holding the adversarial examples.\n \"\"\"\n import tensorflow as tf\n\n mask = self._get_mask(x, **kwargs)\n\n # Ensure eps is broadcastable\n self._check_compatibility_input_and_eps(x=x)\n\n # Check whether random eps is enabled\n self._random_eps()\n\n # Set up targets\n targets = self._set_targets(x, y)\n\n # Create dataset\n if mask is not None:\n # Here we need to make a distinction: if the masks are different for each input, we need to index\n # those for the current batch. Otherwise, (i.e. mask is meant to be broadcasted), keep it as it is.\n if len(mask.shape) == len(x.shape):\n dataset = tf.data.Dataset.from_tensor_slices(\n (\n x.astype(ART_NUMPY_DTYPE),\n targets.astype(ART_NUMPY_DTYPE),\n mask.astype(ART_NUMPY_DTYPE),\n )\n ).batch(self.batch_size, drop_remainder=False)\n\n else:\n dataset = tf.data.Dataset.from_tensor_slices(\n (\n x.astype(ART_NUMPY_DTYPE),\n targets.astype(ART_NUMPY_DTYPE),\n np.array([mask.astype(ART_NUMPY_DTYPE)] * x.shape[0]),\n )\n ).batch(self.batch_size, drop_remainder=False)\n\n else:\n dataset = tf.data.Dataset.from_tensor_slices(\n (\n x.astype(ART_NUMPY_DTYPE),\n targets.astype(ART_NUMPY_DTYPE),\n )\n ).batch(self.batch_size, drop_remainder=False)\n\n # Start to compute adversarial examples\n adv_x = x.astype(ART_NUMPY_DTYPE)\n data_loader = iter(dataset)\n\n # Compute perturbation with batching\n for batch_id, batch_all in enumerate(\n tqdm(data_loader, desc=\"PGD - Batches\", leave=False, disable=not self.verbose)\n ):\n\n self._batch_id = batch_id\n\n if mask is not None:\n (batch, batch_labels, mask_batch) = batch_all[0], batch_all[1], batch_all[2]\n else:\n (batch, batch_labels, mask_batch) = batch_all[0], batch_all[1], None\n\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n\n batch_eps: int | float | np.ndarray\n batch_eps_step: int | float | np.ndarray\n\n # Compute batch_eps and batch_eps_step\n if isinstance(self.eps, np.ndarray) and isinstance(self.eps_step, np.ndarray):\n if len(self.eps.shape) == len(x.shape) and self.eps.shape[0] == x.shape[0]:\n batch_eps = self.eps[batch_index_1:batch_index_2]\n batch_eps_step = self.eps_step[batch_index_1:batch_index_2]\n\n else:\n batch_eps = self.eps\n batch_eps_step = self.eps_step\n\n else:\n batch_eps = self.eps\n batch_eps_step = self.eps_step\n\n for rand_init_num in range(max(1, self.num_random_init)):\n if rand_init_num == 0:\n # first iteration: use the adversarial examples as they are the only ones we have now\n adv_x[batch_index_1:batch_index_2] = self._generate_batch(\n x=batch, targets=batch_labels, mask=mask_batch, eps=batch_eps, eps_step=batch_eps_step\n )\n else:\n adversarial_batch = self._generate_batch(\n x=batch, targets=batch_labels, mask=mask_batch, eps=batch_eps, eps_step=batch_eps_step\n )\n attack_success = compute_success_array(\n self.estimator,\n batch,\n batch_labels,\n adversarial_batch,\n self.targeted,\n batch_size=self.batch_size,\n )\n # return the successful adversarial examples\n adv_x[batch_index_1:batch_index_2][attack_success] = adversarial_batch[attack_success]\n\n logger.info(\n \"Success rate of attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, targets, adv_x, self.targeted, batch_size=self.batch_size),\n )\n\n if self.summary_writer is not None:\n self.summary_writer.reset()\n\n return adv_x\n\n def _generate_batch(\n self,\n x: \"tf.Tensor\",\n targets: \"tf.Tensor\",\n mask: \"tf.Tensor\",\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n ) -> \"tf.Tensor\":\n \"\"\"\n Generate a batch of adversarial samples and return them in an array.\n\n :param x: An array with the original inputs.\n :param targets: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n :param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be\n broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially\n perturbed.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n import tensorflow as tf\n\n adv_x = tf.identity(x)\n momentum = tf.zeros(x.shape)\n\n for i_max_iter in range(self.max_iter):\n self._i_max_iter = i_max_iter\n adv_x = self._compute_tf(\n adv_x,\n x,\n targets,\n mask,\n eps,\n eps_step,\n momentum,\n self.num_random_init > 0 and i_max_iter == 0,\n )\n\n return adv_x\n\n def _compute_perturbation(\n self,\n x: \"tf.Tensor\",\n y: \"tf.Tensor\",\n mask: \"tf.Tensor\" | None,\n decay: float | None = None,\n momentum: \"tf.Tensor\" | None = None,\n ) -> \"tf.Tensor\":\n \"\"\"\n Compute perturbations.\n\n :param x: Current adversarial examples.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :param decay: Decay factor for accumulating the velocity vector when using momentum.\n :param momentum: An array accumulating the velocity vector in the gradient direction for MIFGSM.\n :return: Perturbations.\n \"\"\"\n import tensorflow as tf\n\n # Get gradient wrt loss; invert it if attack is targeted\n grad: tf.Tensor = self.estimator.loss_gradient(x, y) * tf.constant(\n -1 if self.targeted else 1, dtype=ART_NUMPY_DTYPE\n )\n\n # Write summary\n if self.summary_writer is not None: # pragma: no cover\n self.summary_writer.update(\n batch_id=self._batch_id,\n global_step=self._i_max_iter,\n grad=grad.numpy(),\n patch=None,\n estimator=self.estimator,\n x=x.numpy(),\n y=y.numpy(),\n targeted=self.targeted,\n )\n\n # Check for NaN before normalisation and replace with 0\n if tf.reduce_any(tf.math.is_nan(grad)): # pragma: no cover\n logger.warning(\"Elements of the loss gradient are NaN and have been replaced with 0.0.\")\n grad = tf.where(tf.math.is_nan(grad), tf.zeros_like(grad), grad)\n\n # Apply mask\n if mask is not None:\n grad = tf.where(mask == 0.0, 0.0, grad)\n\n # Compute gradient momentum\n if decay is not None and momentum is not None:\n raise NotImplementedError( # Upon fixing #2439, remove pylint disable flag below.\n \"Momentum Iterative Attack currently disabled for Tensorflow framework. See issue #2439\"\n )\n # Update momentum in-place (important).\n # The L1 normalization for accumulation is an arbitrary choice of the paper.\n grad_2d = tf.reshape(grad, (len(grad), -1)) # pylint: disable=unreachable\n norm1 = tf.norm(grad_2d, ord=1, axis=1, keepdims=True)\n normalized_grad = tf.reshape((grad_2d * tf.where(norm1 == 0, 0.0, 1 / norm1)), grad.shape)\n momentum *= self.decay\n momentum += normalized_grad\n # Use the momentum to compute the perturbation, instead of the gradient\n grad = momentum\n\n # Apply norm bound\n norm: float = np.inf if self.norm == \"inf\" else float(self.norm)\n grad_2d = tf.reshape(grad, (len(grad), -1))\n if norm == np.inf:\n grad_2d = tf.ones_like(grad_2d, dtype=grad_2d.dtype)\n elif norm == 1:\n grad_2d = tf.abs(grad_2d)\n grad_2d = tf.where(grad_2d == tf.reduce_max(grad_2d, axis=1, keepdims=True), 1.0, 0.0)\n grad_2d /= tf.reduce_sum(grad_2d, axis=1, keepdims=True)\n elif norm > 1:\n conjugate = norm / (norm - 1)\n q_norm = tf.norm(grad_2d, ord=conjugate, axis=1, keepdims=True)\n grad_2d = (tf.abs(grad_2d) * tf.where(q_norm == 0, 0.0, 1 / q_norm)) ** (conjugate - 1)\n\n grad = tf.reshape(grad_2d, grad.shape) * tf.sign(grad)\n\n assert x.shape == grad.shape\n\n return grad\n\n def _apply_perturbation(\n self, x: \"tf.Tensor\", perturbation: \"tf.Tensor\", eps_step: int | float | np.ndarray\n ) -> \"tf.Tensor\":\n \"\"\"\n Apply perturbation on examples.\n\n :param x: Current adversarial examples.\n :param perturbation: Current perturbations.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n import tensorflow as tf\n\n perturbation_step = tf.constant(eps_step, dtype=ART_NUMPY_DTYPE) * perturbation\n perturbation_step = tf.where(tf.math.is_nan(perturbation_step), 0, perturbation_step)\n x = x + perturbation_step\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x = tf.clip_by_value(x, clip_value_min=clip_min, clip_value_max=clip_max)\n\n return x\n\n def _compute_tf(\n self,\n x: \"tf.Tensor\",\n x_init: \"tf.Tensor\",\n y: \"tf.Tensor\",\n mask: \"tf.Tensor\",\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n momentum: \"tf.Tensor\" | None,\n random_init: bool,\n ) -> \"tf.Tensor\":\n \"\"\"\n Compute adversarial examples for one iteration.\n\n :param x: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.\n Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any\n features for which the mask is zero will not be adversarially perturbed.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_init: Random initialisation within the epsilon ball. For random_init=False starting at the\n original input.\n :param momentum: An array accumulating the velocity vector in the gradient direction for MIFGSM.\n :return: Adversarial examples and accumulated momentum.\n \"\"\"\n import tensorflow as tf\n\n if random_init:\n n = x.shape[0]\n m = np.prod(x.shape[1:]).item()\n\n random_perturbation = random_sphere(n, m, eps, self.norm).reshape(x.shape).astype(ART_NUMPY_DTYPE)\n random_perturbation = tf.convert_to_tensor(random_perturbation)\n if mask is not None:\n random_perturbation = random_perturbation * mask\n\n x_adv = x + random_perturbation\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n x_adv = tf.clip_by_value(x_adv, clip_min, clip_max)\n\n else:\n x_adv = x\n\n # Get perturbation\n perturbation = self._compute_perturbation(x_adv, y, mask, self.decay, momentum)\n\n # Apply perturbation and clip\n x_adv = self._apply_perturbation(x_adv, perturbation, eps_step)\n\n # Do projection\n perturbation = self._projection(x_adv - x_init, eps, self.norm)\n\n # Recompute x_adv\n x_adv = tf.add(perturbation, x_init)\n\n return x_adv\n\n @staticmethod\n def _projection(\n values: \"tf.Tensor\",\n eps: int | float | np.ndarray,\n norm_p: int | float | str,\n *,\n suboptimal: bool = True,\n ) -> \"tf.Tensor\":\n \"\"\"\n Project `values` on the L_p norm ball of size `eps`.\n\n :param values: Values to clip.\n :param eps: If a scalar, the norm of the L_p ball onto which samples are projected. Equivalently in general,\n can be any array of non-negatives broadcastable with `values`, and the projection occurs onto the\n unit ball for the weighted L_{p, w} norm with `w = 1 / eps`. Currently, for any given sample,\n non-uniform weights are only supported with infinity norm. Example: To specify sample-wise scalar,\n you can provide `eps.shape = (n_samples,) + (1,) * values[0].ndim`.\n :param norm_p: Lp norm to use for clipping, with `norm_p > 0`. Only 2, `np.inf` and \"inf\" are supported\n with `suboptimal=False` for now.\n :param suboptimal: If `True` simply projects by rescaling to Lp ball. Fast but may be suboptimal for\n `norm_p != 2`.\n Ignored when `norm_p in [np.inf, \"inf\"]` because optimal solution is fast. Defaults to `True`.\n :return: Values of `values` after projection.\n \"\"\"\n import tensorflow as tf\n\n norm = np.inf if norm_p == \"inf\" else float(norm_p)\n assert norm > 0\n\n values_tmp = tf.reshape(values, (len(values), -1)) # (n_samples, d)\n\n eps = np.broadcast_to(eps, values.shape)\n eps = eps.reshape(len(eps), -1) # (n_samples, d)\n assert np.all(eps >= 0)\n if norm != np.inf and not np.all(eps == eps[:, [0]]):\n raise NotImplementedError(\n \"Projection onto the weighted L_p ball is currently not supported with finite `norm_p`.\"\n )\n\n if (suboptimal or norm == 2) and norm != np.inf: # Simple rescaling\n values_norm = tf.norm(values_tmp, ord=norm, axis=1, keepdims=True) # (n_samples, 1)\n values_tmp = values_tmp * tf.where(values_norm == 0, 0, tf.minimum(1, eps / values_norm))\n else: # Optimal\n if norm == np.inf: # Easy exact case\n values_tmp = tf.sign(values_tmp) * tf.minimum(tf.abs(values_tmp), eps)\n elif norm >= 1: # Convex optim\n raise NotImplementedError(\n \"Finite values of `norm_p >= 1` are currently not supported with `suboptimal=False`.\"\n )\n else: # Non-convex optim\n raise NotImplementedError(\"Values of `norm_p < 1` are currently not supported with `suboptimal=False`\")\n\n values = tf.cast(tf.reshape(values_tmp, values.shape), values.dtype)\n\n return values\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/steal_now_attack_later/bbox_ioa.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# pylint: disable=C0114\n# GNU AFFERO GENERAL PUBLIC LICENSE\n# Version 3, 19 November 2007\n#\n# Copyright (C) 2007 Free Software Foundation, Inc. \n# Everyone is permitted to copy and distribute verbatim copies\n# of this license document, but changing it is not allowed.\n#\n# Preamble\n#\n# The GNU Affero General Public License is a free, copyleft license for\n# software and other kinds of works, specifically designed to ensure\n# cooperation with the community in the case of network server software.\n#\n# The licenses for most software and other practical works are designed\n# to take away your freedom to share and change the works. By contrast,\n# our General Public Licenses are intended to guarantee your freedom to\n# share and change all versions of a program--to make sure it remains free\n# software for all its users.\n#\n# When we speak of free software, we are referring to freedom, not\n# price. Our General Public Licenses are designed to make sure that you\n# have the freedom to distribute copies of free software (and charge for\n# them if you wish), that you receive source code or can get it if you\n# want it, that you can change the software or use pieces of it in new\n# free programs, and that you know you can do these things.\n#\n# Developers that use our General Public Licenses protect your rights\n# with two steps: (1) assert copyright on the software, and (2) offer\n# you this License which gives you legal permission to copy, distribute\n# and/or modify the software.\n#\n# A secondary benefit of defending all users' freedom is that\n# improvements made in alternate versions of the program, if they\n# receive widespread use, become available for other developers to\n# incorporate. Many developers of free software are heartened and\n# encouraged by the resulting cooperation. However, in the case of\n# software used on network servers, this result may fail to come about.\n# The GNU General Public License permits making a modified version and\n# letting the public access it on a server without ever releasing its\n# source code to the public.\n#\n# The GNU Affero General Public License is designed specifically to\n# ensure that, in such cases, the modified source code becomes available\n# to the community. It requires the operator of a network server to\n# provide the source code of the modified version running there to the\n# users of that server. Therefore, public use of a modified version, on\n# a publicly accessible server, gives the public access to the source\n# code of the modified version.\n#\n# An older license, called the Affero General Public License and\n# published by Affero, was designed to accomplish similar goals. This is\n# a different license, not a version of the Affero GPL, but Affero has\n# released a new version of the Affero GPL which permits relicensing under\n# this license.\n#\n# The precise terms and conditions for copying, distribution and\n# modification follow.\n#\n# TERMS AND CONDITIONS\n#\n# 0. Definitions.\n#\n# \"This License\" refers to version 3 of the GNU Affero General Public License.\n#\n# \"Copyright\" also means copyright-like laws that apply to other kinds of\n# works, such as semiconductor masks.\n#\n# \"The Program\" refers to any copyrightable work licensed under this\n# License. Each licensee is addressed as \"you\". \"Licensees\" and\n# \"recipients\" may be individuals or organizations.\n#\n# To \"modify\" a work means to copy from or adapt all or part of the work\n# in a fashion requiring copyright permission, other than the making of an\n# exact copy. The resulting work is called a \"modified version\" of the\n# earlier work or a work \"based on\" the earlier work.\n#\n# A \"covered work\" means either the unmodified Program or a work based\n# on the Program.\n#\n# To \"propagate\" a work means to do anything with it that, without\n# permission, would make you directly or secondarily liable for\n# infringement under applicable copyright law, except executing it on a\n# computer or modifying a private copy. Propagation includes copying,\n# distribution (with or without modification), making available to the\n# public, and in some countries other activities as well.\n#\n# To \"convey\" a work means any kind of propagation that enables other\n# parties to make or receive copies. Mere interaction with a user through\n# a computer network, with no transfer of a copy, is not conveying.\n#\n# An interactive user interface displays \"Appropriate Legal Notices\"\n# to the extent that it includes a convenient and prominently visible\n# feature that (1) displays an appropriate copyright notice, and (2)\n# tells the user that there is no warranty for the work (except to the\n# extent that warranties are provided), that licensees may convey the\n# work under this License, and how to view a copy of this License. If\n# the interface presents a list of user commands or options, such as a\n# menu, a prominent item in the list meets this criterion.\n#\n# 1. Source Code.\n#\n# The \"source code\" for a work means the preferred form of the work\n# for making modifications to it. \"Object code\" means any non-source\n# form of a work.\n#\n# A \"Standard Interface\" means an interface that either is an official\n# standard defined by a recognized standards body, or, in the case of\n# interfaces specified for a particular programming language, one that\n# is widely used among developers working in that language.\n#\n# The \"System Libraries\" of an executable work include anything, other\n# than the work as a whole, that (a) is included in the normal form of\n# packaging a Major Component, but which is not part of that Major\n# Component, and (b) serves only to enable use of the work with that\n# Major Component, or to implement a Standard Interface for which an\n# implementation is available to the public in source code form. A\n# \"Major Component\", in this context, means a major essential component\n# (kernel, window system, and so on) of the specific operating system\n# (if any) on which the executable work runs, or a compiler used to\n# produce the work, or an object code interpreter used to run it.\n#\n# The \"Corresponding Source\" for a work in object code form means all\n# the source code needed to generate, install, and (for an executable\n# work) run the object code and to modify the work, including scripts to\n# control those activities. However, it does not include the work's\n# System Libraries, or general-purpose tools or generally available free\n# programs which are used unmodified in performing those activities but\n# which are not part of the work. For example, Corresponding Source\n# includes interface definition files associated with source files for\n# the work, and the source code for shared libraries and dynamically\n# linked subprograms that the work is specifically designed to require,\n# such as by intimate data communication or control flow between those\n# subprograms and other parts of the work.\n#\n# The Corresponding Source need not include anything that users\n# can regenerate automatically from other parts of the Corresponding\n# Source.\n#\n# The Corresponding Source for a work in source code form is that\n# same work.\n#\n# 2. Basic Permissions.\n#\n# All rights granted under this License are granted for the term of\n# copyright on the Program, and are irrevocable provided the stated\n# conditions are met. This License explicitly affirms your unlimited\n# permission to run the unmodified Program. The output from running a\n# covered work is covered by this License only if the output, given its\n# content, constitutes a covered work. This License acknowledges your\n# rights of fair use or other equivalent, as provided by copyright law.\n#\n# You may make, run and propagate covered works that you do not\n# convey, without conditions so long as your license otherwise remains\n# in force. You may convey covered works to others for the sole purpose\n# of having them make modifications exclusively for you, or provide you\n# with facilities for running those works, provided that you comply with\n# the terms of this License in conveying all material for which you do\n# not control copyright. Those thus making or running the covered works\n# for you must do so exclusively on your behalf, under your direction\n# and control, on terms that prohibit them from making any copies of\n# your copyrighted material outside their relationship with you.\n#\n# Conveying under any other circumstances is permitted solely under\n# the conditions stated below. Sublicensing is not allowed; section 10\n# makes it unnecessary.\n#\n# 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n#\n# No covered work shall be deemed part of an effective technological\n# measure under any applicable law fulfilling obligations under article\n# 11 of the WIPO copyright treaty adopted on 20 December 1996, or\n# similar laws prohibiting or restricting circumvention of such\n# measures.\n#\n# When you convey a covered work, you waive any legal power to forbid\n# circumvention of technological measures to the extent such circumvention\n# is effected by exercising rights under this License with respect to\n# the covered work, and you disclaim any intention to limit operation or\n# modification of the work as a means of enforcing, against the work's\n# users, your or third parties' legal rights to forbid circumvention of\n# technological measures.\n#\n# 4. Conveying Verbatim Copies.\n#\n# You may convey verbatim copies of the Program's source code as you\n# receive it, in any medium, provided that you conspicuously and\n# appropriately publish on each copy an appropriate copyright notice;\n# keep intact all notices stating that this License and any\n# non-permissive terms added in accord with section 7 apply to the code;\n# keep intact all notices of the absence of any warranty; and give all\n# recipients a copy of this License along with the Program.\n#\n# You may charge any price or no price for each copy that you convey,\n# and you may offer support or warranty protection for a fee.\n#\n# 5. Conveying Modified Source Versions.\n#\n# You may convey a work based on the Program, or the modifications to\n# produce it from the Program, in the form of source code under the\n# terms of section 4, provided that you also meet all of these conditions:\n#\n# a) The work must carry prominent notices stating that you modified\n# it, and giving a relevant date.\n#\n# b) The work must carry prominent notices stating that it is\n# released under this License and any conditions added under section\n# 7. This requirement modifies the requirement in section 4 to\n# \"keep intact all notices\".\n#\n# c) You must license the entire work, as a whole, under this\n# License to anyone who comes into possession of a copy. This\n# License will therefore apply, along with any applicable section 7\n# additional terms, to the whole of the work, and all its parts,\n# regardless of how they are packaged. This License gives no\n# permission to license the work in any other way, but it does not\n# invalidate such permission if you have separately received it.\n#\n# d) If the work has interactive user interfaces, each must display\n# Appropriate Legal Notices; however, if the Program has interactive\n# interfaces that do not display Appropriate Legal Notices, your\n# work need not make them do so.\n#\n# A compilation of a covered work with other separate and independent\n# works, which are not by their nature extensions of the covered work,\n# and which are not combined with it such as to form a larger program,\n# in or on a volume of a storage or distribution medium, is called an\n# \"aggregate\" if the compilation and its resulting copyright are not\n# used to limit the access or legal rights of the compilation's users\n# beyond what the individual works permit. Inclusion of a covered work\n# in an aggregate does not cause this License to apply to the other\n# parts of the aggregate.\n#\n# 6. Conveying Non-Source Forms.\n#\n# You may convey a covered work in object code form under the terms\n# of sections 4 and 5, provided that you also convey the\n# machine-readable Corresponding Source under the terms of this License,\n# in one of these ways:\n#\n# a) Convey the object code in, or embodied in, a physical product\n# (including a physical distribution medium), accompanied by the\n# Corresponding Source fixed on a durable physical medium\n# customarily used for software interchange.\n#\n# b) Convey the object code in, or embodied in, a physical product\n# (including a physical distribution medium), accompanied by a\n# written offer, valid for at least three years and valid for as\n# long as you offer spare parts or customer support for that product\n# model, to give anyone who possesses the object code either (1) a\n# copy of the Corresponding Source for all the software in the\n# product that is covered by this License, on a durable physical\n# medium customarily used for software interchange, for a price no\n# more than your reasonable cost of physically performing this\n# conveying of source, or (2) access to copy the\n# Corresponding Source from a network server at no charge.\n#\n# c) Convey individual copies of the object code with a copy of the\n# written offer to provide the Corresponding Source. This\n# alternative is allowed only occasionally and noncommercially, and\n# only if you received the object code with such an offer, in accord\n# with subsection 6b.\n#\n# d) Convey the object code by offering access from a designated\n# place (gratis or for a charge), and offer equivalent access to the\n# Corresponding Source in the same way through the same place at no\n# further charge. You need not require recipients to copy the\n# Corresponding Source along with the object code. If the place to\n# copy the object code is a network server, the Corresponding Source\n# may be on a different server (operated by you or a third party)\n# that supports equivalent copying facilities, provided you maintain\n# clear directions next to the object code saying where to find the\n# Corresponding Source. Regardless of what server hosts the\n# Corresponding Source, you remain obligated to ensure that it is\n# available for as long as needed to satisfy these requirements.\n#\n# e) Convey the object code using peer-to-peer transmission, provided\n# you inform other peers where the object code and Corresponding\n# Source of the work are being offered to the general public at no\n# charge under subsection 6d.\n#\n# A separable portion of the object code, whose source code is excluded\n# from the Corresponding Source as a System Library, need not be\n# included in conveying the object code work.\n#\n# A \"User Product\" is either (1) a \"consumer product\", which means any\n# tangible personal property which is normally used for personal, family,\n# or household purposes, or (2) anything designed or sold for incorporation\n# into a dwelling. In determining whether a product is a consumer product,\n# doubtful cases shall be resolved in favor of coverage. For a particular\n# product received by a particular user, \"normally used\" refers to a\n# typical or common use of that class of product, regardless of the status\n# of the particular user or of the way in which the particular user\n# actually uses, or expects or is expected to use, the product. A product\n# is a consumer product regardless of whether the product has substantial\n# commercial, industrial or non-consumer uses, unless such uses represent\n# the only significant mode of use of the product.\n#\n# \"Installation Information\" for a User Product means any methods,\n# procedures, authorization keys, or other information required to install\n# and execute modified versions of a covered work in that User Product from\n# a modified version of its Corresponding Source. The information must\n# suffice to ensure that the continued functioning of the modified object\n# code is in no case prevented or interfered with solely because\n# modification has been made.\n#\n# If you convey an object code work under this section in, or with, or\n# specifically for use in, a User Product, and the conveying occurs as\n# part of a transaction in which the right of possession and use of the\n# User Product is transferred to the recipient in perpetuity or for a\n# fixed term (regardless of how the transaction is characterized), the\n# Corresponding Source conveyed under this section must be accompanied\n# by the Installation Information. But this requirement does not apply\n# if neither you nor any third party retains the ability to install\n# modified object code on the User Product (for example, the work has\n# been installed in ROM).\n#\n# The requirement to provide Installation Information does not include a\n# requirement to continue to provide support service, warranty, or updates\n# for a work that has been modified or installed by the recipient, or for\n# the User Product in which it has been modified or installed. Access to a\n# network may be denied when the modification itself materially and\n# adversely affects the operation of the network or violates the rules and\n# protocols for communication across the network.\n#\n# Corresponding Source conveyed, and Installation Information provided,\n# in accord with this section must be in a format that is publicly\n# documented (and with an implementation available to the public in\n# source code form), and must require no special password or key for\n# unpacking, reading or copying.\n#\n# 7. Additional Terms.\n#\n# \"Additional permissions\" are terms that supplement the terms of this\n# License by making exceptions from one or more of its conditions.\n# Additional permissions that are applicable to the entire Program shall\n# be treated as though they were included in this License, to the extent\n# that they are valid under applicable law. If additional permissions\n# apply only to part of the Program, that part may be used separately\n# under those permissions, but the entire Program remains governed by\n# this License without regard to the additional permissions.\n#\n# When you convey a copy of a covered work, you may at your option\n# remove any additional permissions from that copy, or from any part of\n# it. (Additional permissions may be written to require their own\n# removal in certain cases when you modify the work.) You may place\n# additional permissions on material, added by you to a covered work,\n# for which you have or can give appropriate copyright permission.\n#\n# Notwithstanding any other provision of this License, for material you\n# add to a covered work, you may (if authorized by the copyright holders of\n# that material) supplement the terms of this License with terms:\n#\n# a) Disclaiming warranty or limiting liability differently from the\n# terms of sections 15 and 16 of this License; or\n#\n# b) Requiring preservation of specified reasonable legal notices or\n# author attributions in that material or in the Appropriate Legal\n# Notices displayed by works containing it; or\n#\n# c) Prohibiting misrepresentation of the origin of that material, or\n# requiring that modified versions of such material be marked in\n# reasonable ways as different from the original version; or\n#\n# d) Limiting the use for publicity purposes of names of licensors or\n# authors of the material; or\n#\n# e) Declining to grant rights under trademark law for use of some\n# trade names, trademarks, or service marks; or\n#\n# f) Requiring indemnification of licensors and authors of that\n# material by anyone who conveys the material (or modified versions of\n# it) with contractual assumptions of liability to the recipient, for\n# any liability that these contractual assumptions directly impose on\n# those licensors and authors.\n#\n# All other non-permissive additional terms are considered \"further\n# restrictions\" within the meaning of section 10. If the Program as you\n# received it, or any part of it, contains a notice stating that it is\n# governed by this License along with a term that is a further\n# restriction, you may remove that term. If a license document contains\n# a further restriction but permits relicensing or conveying under this\n# License, you may add to a covered work material governed by the terms\n# of that license document, provided that the further restriction does\n# not survive such relicensing or conveying.\n#\n# If you add terms to a covered work in accord with this section, you\n# must place, in the relevant source files, a statement of the\n# additional terms that apply to those files, or a notice indicating\n# where to find the applicable terms.\n#\n# Additional terms, permissive or non-permissive, may be stated in the\n# form of a separately written license, or stated as exceptions;\n# the above requirements apply either way.\n#\n# 8. Termination.\n#\n# You may not propagate or modify a covered work except as expressly\n# provided under this License. Any attempt otherwise to propagate or\n# modify it is void, and will automatically terminate your rights under\n# this License (including any patent licenses granted under the third\n# paragraph of section 11).\n#\n# However, if you cease all violation of this License, then your\n# license from a particular copyright holder is reinstated (a)\n# provisionally, unless and until the copyright holder explicitly and\n# finally terminates your license, and (b) permanently, if the copyright\n# holder fails to notify you of the violation by some reasonable means\n# prior to 60 days after the cessation.\n#\n# Moreover, your license from a particular copyright holder is\n# reinstated permanently if the copyright holder notifies you of the\n# violation by some reasonable means, this is the first time you have\n# received notice of violation of this License (for any work) from that\n# copyright holder, and you cure the violation prior to 30 days after\n# your receipt of the notice.\n#\n# Termination of your rights under this section does not terminate the\n# licenses of parties who have received copies or rights from you under\n# this License. If your rights have been terminated and not permanently\n# reinstated, you do not qualify to receive new licenses for the same\n# material under section 10.\n#\n# 9. Acceptance Not Required for Having Copies.\n#\n# You are not required to accept this License in order to receive or\n# run a copy of the Program. Ancillary propagation of a covered work\n# occurring solely as a consequence of using peer-to-peer transmission\n# to receive a copy likewise does not require acceptance. However,\n# nothing other than this License grants you permission to propagate or\n# modify any covered work. These actions infringe copyright if you do\n# not accept this License. Therefore, by modifying or propagating a\n# covered work, you indicate your acceptance of this License to do so.\n#\n# 10. Automatic Licensing of Downstream Recipients.\n#\n# Each time you convey a covered work, the recipient automatically\n# receives a license from the original licensors, to run, modify and\n# propagate that work, subject to this License. You are not responsible\n# for enforcing compliance by third parties with this License.\n#\n# An \"entity transaction\" is a transaction transferring control of an\n# organization, or substantially all assets of one, or subdividing an\n# organization, or merging organizations. If propagation of a covered\n# work results from an entity transaction, each party to that\n# transaction who receives a copy of the work also receives whatever\n# licenses to the work the party's predecessor in interest had or could\n# give under the previous paragraph, plus a right to possession of the\n# Corresponding Source of the work from the predecessor in interest, if\n# the predecessor has it or can get it with reasonable efforts.\n#\n# You may not impose any further restrictions on the exercise of the\n# rights granted or affirmed under this License. For example, you may\n# not impose a license fee, royalty, or other charge for exercise of\n# rights granted under this License, and you may not initiate litigation\n# (including a cross-claim or counterclaim in a lawsuit) alleging that\n# any patent claim is infringed by making, using, selling, offering for\n# sale, or importing the Program or any portion of it.\n#\n# 11. Patents.\n#\n# A \"contributor\" is a copyright holder who authorizes use under this\n# License of the Program or a work on which the Program is based. The\n# work thus licensed is called the contributor's \"contributor version\".\n#\n# A contributor's \"essential patent claims\" are all patent claims\n# owned or controlled by the contributor, whether already acquired or\n# hereafter acquired, that would be infringed by some manner, permitted\n# by this License, of making, using, or selling its contributor version,\n# but do not include claims that would be infringed only as a\n# consequence of further modification of the contributor version. For\n# purposes of this definition, \"control\" includes the right to grant\n# patent sublicenses in a manner consistent with the requirements of\n# this License.\n#\n# Each contributor grants you a non-exclusive, worldwide, royalty-free\n# patent license under the contributor's essential patent claims, to\n# make, use, sell, offer for sale, import and otherwise run, modify and\n# propagate the contents of its contributor version.\n#\n# In the following three paragraphs, a \"patent license\" is any express\n# agreement or commitment, however denominated, not to enforce a patent\n# (such as an express permission to practice a patent or covenant not to\n# sue for patent infringement). To \"grant\" such a patent license to a\n# party means to make such an agreement or commitment not to enforce a\n# patent against the party.\n#\n# If you convey a covered work, knowingly relying on a patent license,\n# and the Corresponding Source of the work is not available for anyone\n# to copy, free of charge and under the terms of this License, through a\n# publicly available network server or other readily accessible means,\n# then you must either (1) cause the Corresponding Source to be so\n# available, or (2) arrange to deprive yourself of the benefit of the\n# patent license for this particular work, or (3) arrange, in a manner\n# consistent with the requirements of this License, to extend the patent\n# license to downstream recipients. \"Knowingly relying\" means you have\n# actual knowledge that, but for the patent license, your conveying the\n# covered work in a country, or your recipient's use of the covered work\n# in a country, would infringe one or more identifiable patents in that\n# country that you have reason to believe are valid.\n#\n# If, pursuant to or in connection with a single transaction or\n# arrangement, you convey, or propagate by procuring conveyance of, a\n# covered work, and grant a patent license to some of the parties\n# receiving the covered work authorizing them to use, propagate, modify\n# or convey a specific copy of the covered work, then the patent license\n# you grant is automatically extended to all recipients of the covered\n# work and works based on it.\n#\n# A patent license is \"discriminatory\" if it does not include within\n# the scope of its coverage, prohibits the exercise of, or is\n# conditioned on the non-exercise of one or more of the rights that are\n# specifically granted under this License. You may not convey a covered\n# work if you are a party to an arrangement with a third party that is\n# in the business of distributing software, under which you make payment\n# to the third party based on the extent of your activity of conveying\n# the work, and under which the third party grants, to any of the\n# parties who would receive the covered work from you, a discriminatory\n# patent license (a) in connection with copies of the covered work\n# conveyed by you (or copies made from those copies), or (b) primarily\n# for and in connection with specific products or compilations that\n# contain the covered work, unless you entered into that arrangement,\n# or that patent license was granted, prior to 28 March 2007.\n#\n# Nothing in this License shall be construed as excluding or limiting\n# any implied license or other defenses to infringement that may\n# otherwise be available to you under applicable patent law.\n#\n# 12. No Surrender of Others' Freedom.\n#\n# If conditions are imposed on you (whether by court order, agreement or\n# otherwise) that contradict the conditions of this License, they do not\n# excuse you from the conditions of this License. If you cannot convey a\n# covered work so as to satisfy simultaneously your obligations under this\n# License and any other pertinent obligations, then as a consequence you may\n# not convey it at all. For example, if you agree to terms that obligate you\n# to collect a royalty for further conveying from those to whom you convey\n# the Program, the only way you could satisfy both those terms and this\n# License would be to refrain entirely from conveying the Program.\n#\n# 13. Remote Network Interaction; Use with the GNU General Public License.\n#\n# Notwithstanding any other provision of this License, if you modify the\n# Program, your modified version must prominently offer all users\n# interacting with it remotely through a computer network (if your version\n# supports such interaction) an opportunity to receive the Corresponding\n# Source of your version by providing access to the Corresponding Source\n# from a network server at no charge, through some standard or customary\n# means of facilitating copying of software. This Corresponding Source\n# shall include the Corresponding Source for any work covered by version 3\n# of the GNU General Public License that is incorporated pursuant to the\n# following paragraph.\n#\n# Notwithstanding any other provision of this License, you have\n# permission to link or combine any covered work with a work licensed\n# under version 3 of the GNU General Public License into a single\n# combined work, and to convey the resulting work. The terms of this\n# License will continue to apply to the part which is the covered work,\n# but the work with which it is combined will remain governed by version\n# 3 of the GNU General Public License.\n#\n# 14. Revised Versions of this License.\n#\n# The Free Software Foundation may publish revised and/or new versions of\n# the GNU Affero General Public License from time to time. Such new versions\n# will be similar in spirit to the present version, but may differ in detail to\n# address new problems or concerns.\n#\n# Each version is given a distinguishing version number. If the\n# Program specifies that a certain numbered version of the GNU Affero General\n# Public License \"or any later version\" applies to it, you have the\n# option of following the terms and conditions either of that numbered\n# version or of any later version published by the Free Software\n# Foundation. If the Program does not specify a version number of the\n# GNU Affero General Public License, you may choose any version ever published\n# by the Free Software Foundation.\n#\n# If the Program specifies that a proxy can decide which future\n# versions of the GNU Affero General Public License can be used, that proxy's\n# public statement of acceptance of a version permanently authorizes you\n# to choose that version for the Program.\n#\n# Later license versions may give you additional or different\n# permissions. However, no additional obligations are imposed on any\n# author or copyright holder as a result of your choosing to follow a\n# later version.\n#\n# 15. Disclaimer of Warranty.\n#\n# THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\n# APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\n# HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\n# OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\n# IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\n# ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n#\n# 16. Limitation of Liability.\n#\n# IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n# WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\n# THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\n# GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\n# USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\n# DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\n# PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\n# EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGES.\n#\n# 17. Interpretation of Sections 15 and 16.\n#\n# If the disclaimer of warranty and limitation of liability provided\n# above cannot be given local legal effect according to their terms,\n# reviewing courts shall apply local law that most closely approximates\n# an absolute waiver of all civil liability in connection with the\n# Program, unless a warranty or assumption of liability accompanies a\n# copy of the Program in return for a fee.\n#\n# END OF TERMS AND CONDITIONS\n#\n# How to Apply These Terms to Your New Programs\n#\n# If you develop a new program, and you want it to be of the greatest\n# possible use to the public, the best way to achieve this is to make it\n# free software which everyone can redistribute and change under these terms.\n#\n# To do so, attach the following notices to the program. It is safest\n# to attach them to the start of each source file to most effectively\n# state the exclusion of warranty; and each file should have at least\n# the \"copyright\" line and a pointer to where the full notice is found.\n#\n# \n# Copyright (C) \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n# Also add information on how to contact you by electronic and paper mail.\n#\n# If your software can interact with users remotely through a computer\n# network, you should also make sure that it provides a way for users to\n# get its source. For example, if your program is a web application, its\n# interface could display a \"Source\" link that leads users to an archive\n# of the code. There are many ways you could offer source, and different\n# solutions will be better for different programs; see section 13 for the\n# specific requirements.\n#\n# You should also get your employer (if you work as a programmer) or school,\n# if any, to sign a \"copyright disclaimer\" for the program, if necessary.\n# For more information on this, and how to apply and follow the GNU AGPL, see\n# .\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n import torch\n\n\ndef bbox_ioa(box1: \"torch.Tensor\", box2: \"torch.Tensor\", eps: float = 1e-7) -> \"torch.Tensor\":\n \"\"\"\n === NOTE ===\n This function is copied from YOLOv5 repository (yolov5/utils/metrics.py)\n === ==== ===\n Calculate the intersection over two boxes represented by the format x1y1x2y2.\n\n :param box1: The first box.\n :param box2: The second box.\n\n :return: Intersection over box2 area\n \"\"\"\n\n # Get the coordinates of bounding boxes\n b1_x1, b1_y1, b1_x2, b1_y2 = box1\n b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n # Intersection area\n inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * (\n np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)\n ).clip(0)\n\n # box2 area\n box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps\n\n # Intersection over box2 area\n return inter_area / box2_area\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/steal_now_attack_later/drop_block2d.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# pylint: disable=C0114\n# BSD 3-Clause License\n#\n# Copyright (c) Soumith Chintala 2016,\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n import torch\n\n\ndef drop_block2d(x: \"torch.Tensor\", prob: float, block_size: int):\n \"\"\"\n === NOTE ===\n This function is modified from torchvision (torchvision/ops/drop_block.py)\n BSD 3-Clause License\n === ==== ===\n :param x (Tensor[N, C, H, W]): The input tensor or 4-dimensions with the first one\n being its batch i.e. a batch with ``N`` rows.\n :param prob (float): Probability of an element to be dropped.\n :param block_size (int): Size of the block to drop.\n\n :return: Tensor[N, C, H, W]: The mask of activate pixels.\n \"\"\"\n import torch\n\n if prob < 0.0 or prob > 1.0:\n raise ValueError(f\"drop probability has to be between 0 and 1, but got {prob}.\")\n if x.ndim != 4:\n raise ValueError(f\"input should be 4 dimensional. Got {x.ndim} dimensions.\")\n\n N, _, H, W = x.size() # pylint: disable=C0103\n block_size = min(block_size, W, H)\n # compute the gamma of Bernoulli distribution\n gamma = (prob * H * W) / ((block_size**2) * ((H - block_size + 1) * (W - block_size + 1)))\n noise = torch.empty((N, 1, H - block_size + 1, W - block_size + 1), dtype=x.dtype, device=x.device)\n noise.bernoulli_(gamma)\n\n noise = torch.nn.functional.pad(noise, [block_size // 2] * 4, value=0)\n noise = torch.nn.functional.max_pool2d(\n noise, stride=(1, 1), kernel_size=(block_size, block_size), padding=block_size // 2\n )\n mask = 1 - noise\n return mask\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/evasion/steal_now_attack_later/steal_now_attack_later.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nThis module implements the paper: Steal Now and Attack Later: Evaluating Robustness of Object Detection against\nBlack-box Adversarial Attacks\n\n| Paper link: https://arxiv.org/abs/2304.05370\n\"\"\"\n\n# pylint: disable=C0302\n\nimport logging\nimport random\nfrom typing import Callable, Optional, Tuple, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.steal_now_attack_later.bbox_ioa import bbox_ioa\nfrom art.attacks.evasion.steal_now_attack_later.drop_block2d import drop_block2d\n\nif TYPE_CHECKING:\n # pylint: disable=C0412\n import torch\n from art.utils import PYTORCH_OBJECT_DETECTOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\ndef _generate_tile_kernel(patch: list, mask: list, tile_size: int) -> Tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Generate specific size of perturbed tiles from randomly selected patches.\n\n :param patch: Candidate patches.\n :param mask: Masks for each patch.\n :param tile_size: The size of each tile.\n :return: Perturbed tiles and corresponding masks.\n \"\"\"\n import torch\n import torchvision\n\n idx_seq = list(range(len(patch)))\n target = random.sample(idx_seq, k=1)[0]\n t_patch = patch[target]\n t_mask = mask[target]\n if t_mask is None:\n t_mask = torch.ones_like(t_patch)\n width, height = t_patch.shape[-2], t_patch.shape[-1]\n boundary = 1\n tile_size = max(tile_size - 2 * boundary, 1)\n\n if height > width:\n flip = True\n FlipOp = torchvision.transforms.RandomVerticalFlip(0.2) # pylint: disable=C0103\n max_len = height\n min_len = width\n t_patch = torch.permute(t_patch, (0, 2, 1))\n t_mask = torch.permute(t_mask, (0, 2, 1))\n else:\n flip = False\n FlipOp = torchvision.transforms.RandomHorizontalFlip(0.2) # pylint: disable=C0103\n max_len = width\n min_len = height\n\n if max_len > tile_size:\n new_len = max(round(min_len * tile_size / max_len), 1)\n p_1 = torchvision.transforms.Resize((tile_size, new_len))(t_patch)\n # fix for the case that (strides - new_len) > new_len\n p_list = []\n\n for _ in range(tile_size // new_len):\n p_list.append(FlipOp(p_1))\n\n p_2 = torchvision.transforms.RandomCrop((tile_size, tile_size % new_len))(p_1)\n p_list.append(FlipOp(p_2))\n\n n_patch = torch.cat(p_list, dim=-1)\n n_patch = torchvision.transforms.CenterCrop((tile_size + 2 * boundary, tile_size + 2 * boundary))(n_patch)\n n_mask = torch.where(n_patch == 0, torch.zeros_like(n_patch), torch.ones_like(n_patch))\n\n elif max_len >= tile_size / 2.0:\n new_len = max(round(min_len * (tile_size / 2.0) / max_len), 1)\n\n p_list = []\n for _ in range(tile_size // new_len):\n repeat = 2\n p1_list = []\n for _ in range(repeat):\n p_1 = torchvision.transforms.Resize((max(tile_size // 2, 1), new_len))(t_patch)\n if torch.rand([]) < 0.6:\n p1_list.append(FlipOp(p_1))\n else:\n p1_list.append(torch.zeros_like(p_1))\n p_1 = torch.cat(p1_list, dim=-2)\n p_list.append(p_1)\n\n p_2 = torchvision.transforms.RandomCrop((tile_size, max(tile_size % new_len, 1)))(p_1)\n p_list.append(FlipOp(p_2))\n\n n_patch = torch.cat(p_list, dim=-1)\n n_patch = torchvision.transforms.CenterCrop((tile_size + 2 * boundary, tile_size + 2 * boundary))(n_patch)\n n_mask = torch.where(n_patch == 0, torch.zeros_like(n_patch), torch.ones_like(n_patch))\n\n else:\n t_1 = torch.cat([t_patch[None, :], t_mask[None, :]], dim=0)\n p_list = []\n n_list = []\n for _ in range(tile_size // min_len):\n p1_list = []\n m1_list = []\n for _ in range(tile_size // max_len):\n if torch.rand([]) < 0.4:\n t_1 = FlipOp(t_1)\n p1_list.append(t_1[0, :])\n m1_list.append(t_1[1, :])\n else:\n p1_list.append(torch.zeros_like(t_patch))\n m1_list.append(torch.zeros_like(t_mask))\n p_1 = torch.cat(p1_list, dim=-2)\n m_1 = torch.cat(m1_list, dim=-2)\n p_list.append(p_1)\n n_list.append(m_1)\n n_patch = torch.cat(p_list, dim=-1)\n n_mask = torch.cat(n_list, dim=-1)\n n_patch = torchvision.transforms.CenterCrop((tile_size + 2 * boundary, tile_size + 2 * boundary))(n_patch)\n n_mask = torchvision.transforms.CenterCrop((tile_size + 2 * boundary, tile_size + 2 * boundary))(n_mask)\n\n if flip:\n n_patch = torch.permute(n_patch, (0, 2, 1))\n n_mask = torch.permute(n_mask, (0, 2, 1))\n\n return n_patch, n_mask\n\n\ndef generate_tile(patches: list, masks: list, tile_size: int, scale: list) -> Tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Generate different size of perturbed tiles from randomly selected patches.\n\n :param patch: Candidate patches.\n :param mask: Masks for each patch.\n :param tile_size: The size of each tile.\n :param scale: Scale factor for various tiling size.\n :return: Perturbed tiles and corresponding masks.\n \"\"\"\n import torch\n\n if len(patches) == 0:\n raise ValueError(\"candidates should not be empty.\")\n device = patches[0].device\n\n tile = torch.zeros((0, 3, tile_size, tile_size), device=device)\n mask = torch.zeros((0, 3, tile_size, tile_size), device=device)\n for cur_s in scale:\n cur_strides = tile_size // cur_s\n cur_tile = []\n cur_mask = []\n\n for _ in range(cur_s):\n t1_list = []\n m1_list = []\n for _ in range(cur_s):\n g_tile, f_mask = _generate_tile_kernel(patches, masks, tile_size=cur_strides)\n t1_list.append(g_tile[None, :])\n m1_list.append(f_mask[None, :])\n cur_t = torch.cat(t1_list, dim=-2)\n cur_m = torch.cat(m1_list, dim=-2)\n cur_tile.append(cur_t)\n cur_mask.append(cur_m)\n cur_tile = torch.cat(cur_tile, dim=-1) # type: ignore\n cur_mask = torch.cat(cur_mask, dim=-1) # type: ignore\n\n tile = torch.cat([tile, cur_tile], dim=0) # type: ignore\n mask = torch.cat([mask, cur_mask], dim=0) # type: ignore\n\n return tile, mask\n\n\nclass TileObj:\n \"\"\"\n Internally used object that stores information about each tile.\n \"\"\"\n\n def __init__(self, tile_size: int, device: \"torch.device\") -> None:\n \"\"\"\n Create a tile instance.\n \"\"\"\n import torch\n\n self.patch = torch.zeros((3, tile_size, tile_size), device=device)\n self.diff = torch.ones([], device=device) * self.patch.shape.numel()\n self.bcount = 0\n self.eligible = False\n\n def update(self, eligible=None, bcount=None, diff=None, patch=None) -> None:\n \"\"\"\n Update the properties of the object\n \"\"\"\n if eligible is not None:\n self.eligible = eligible\n\n if bcount is not None:\n self.bcount = bcount\n\n if diff is not None:\n self.diff = diff\n\n if patch is not None:\n self.patch = patch\n\n def compare(self, target: \"TileObj\") -> bool:\n \"\"\"\n Comparison operation.\n \"\"\"\n\n if self.eligible is True and target.eligible is False:\n return True\n\n if self.eligible is False and target.eligible is True:\n return False\n\n if self.bcount > target.bcount:\n return True\n if self.bcount < target.bcount:\n return False\n\n return bool(self.diff < target.diff)\n\n\nclass TileArray:\n \"\"\"\n Internally used object that stores the list of tiles.\n \"\"\"\n\n def __init__(self, xyxy: list, threshold: int, tile_size: int, k: int, device: \"torch.device\") -> None:\n \"\"\"\n Initialization operation.\n \"\"\"\n import torch\n\n self.threshold = threshold\n self.tile_size = tile_size\n self.device = device\n self.xyxy = torch.Tensor(xyxy).to(device)\n self.k = k\n self.patch_list = [TileObj(tile_size=tile_size, device=device)] * self.k\n\n def insert(self, target: TileObj) -> None:\n \"\"\"\n Insertion operation.\n \"\"\"\n if target.bcount < self.threshold:\n return\n\n prev = self.patch_list\n out = []\n for k_it in range(self.k):\n if target.compare(prev[k_it]):\n out.append(target)\n out = out + prev[k_it:]\n break\n\n out.append(prev[k_it])\n\n self.patch_list = out[: self.k]\n\n def pop(self) -> None:\n \"\"\"\n Pop operation.\n \"\"\"\n out = self.patch_list[1:] + [TileObj(tile_size=self.tile_size, device=self.device)]\n self.patch_list = out\n\n\nclass SNAL(EvasionAttack):\n \"\"\"\n Steal Now and Attack Later\n\n | Paper link: https://arxiv.org/abs/2404.15881\n \"\"\"\n\n attack_params = EvasionAttack.attack_params + [\n \"eps\",\n \"max_iter\",\n \"num_grid\",\n \"batch_size\",\n ]\n\n _estimator_requirements = ()\n\n def __init__(\n self,\n estimator: \"PYTORCH_OBJECT_DETECTOR_TYPE\",\n candidates: list,\n collector: Callable,\n eps: float,\n max_iter: int,\n num_grid: int,\n ) -> None:\n \"\"\"\n Create a SNAL attack instance.\n\n :param estimator: A trained YOLOv8 model or other models with the same output format\n :param candidates: The collected patches to generate perturbations.\n :param collector: A callable uses to generate patches.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param max_iter: The maximum number of iterations.\n :param num_grid: The number of grids for width and high dimension.\n \"\"\"\n super().__init__(estimator=estimator)\n self.eps = eps\n self.max_iter = max_iter\n self.num_grid = num_grid\n self.batch_size = 1\n self.candidates = candidates\n self.threshold_objs = 1 # the expect number of objects\n self.collector = collector\n self._check_params()\n\n def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray:\n \"\"\"\n Generate adversarial samples and return them in an array.\n\n :param x: An array with the original inputs to be attacked.\n :param y: Not used.\n :return: An array holding the adversarial examples.\n \"\"\"\n\n # Compute adversarial examples with implicit batching\n x_adv = x.copy()\n for batch_id in range(int(np.ceil(x_adv.shape[0] / float(self.batch_size)))):\n batch_index_1 = batch_id * self.batch_size\n batch_index_2 = min((batch_id + 1) * self.batch_size, x_adv.shape[0])\n x_batch = x_adv[batch_index_1:batch_index_2]\n x_adv[batch_index_1:batch_index_2] = self._generate_batch(x_batch)\n\n return x_adv\n\n def _generate_batch(\n self, x_batch: np.ndarray, y_batch: Optional[np.ndarray] = None # pylint: disable=W0613\n ) -> np.ndarray:\n \"\"\"\n Run the attack on a batch of images.\n\n :param x_batch: A batch of original examples.\n :param y_batch: Not Used.\n :return: A batch of adversarial examples.\n \"\"\"\n import torch\n\n x_org = torch.from_numpy(x_batch).to(self.estimator.device)\n x_adv = x_org.clone()\n\n cond = torch.logical_or(x_org < 0.0, x_org > 1.0)\n if torch.any(cond):\n raise ValueError(\"The value of each pixel must be normalized in the range [0, 1].\")\n\n x_adv = self._attack(x_adv, x_org)\n\n return x_adv.cpu().detach().numpy()\n\n def _attack(self, x_adv: \"torch.Tensor\", x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Run attack.\n\n :param x_batch: A batch of original examples.\n :param y_batch: Not Used.\n :return: A batch of adversarial examples.\n \"\"\"\n import torch\n\n if self.candidates is None:\n raise ValueError(\"A set of patches should be collected before executing the attack.\")\n\n if x.shape[-1] % self.num_grid != 0 or x.shape[-2] % self.num_grid != 0:\n raise ValueError(\"The size of the image must be divided by the number of grids\")\n tile_size = x.shape[-1] // self.num_grid\n\n # Prepare a 2D array to store the results of each grid\n buffer_depth = 5\n tile_mat = {}\n for idx_i in range(self.num_grid):\n for idx_j in range(self.num_grid):\n x_1 = idx_i * tile_size\n y_1 = idx_j * tile_size\n x_2 = x_1 + tile_size\n y_2 = y_1 + tile_size\n tile_mat[(idx_i, idx_j)] = TileArray(\n list([x_1, y_1, x_2, y_2]), self.threshold_objs, tile_size, buffer_depth, self.estimator.device\n )\n\n # init guess\n n_samples = 10\n x_adv, tile_mat = self._init_guess(tile_mat, x_adv, x, tile_size, n_samples=n_samples)\n\n batch_idx = 0\n candidates_patch = self.candidates\n candidates_mask = [None] * len(candidates_patch)\n\n r_tile = torch.zeros((0, 3, tile_size, tile_size), device=self.estimator.device)\n r_mask = torch.zeros((0, 3, tile_size, tile_size), device=self.estimator.device)\n while r_tile.shape[0] < n_samples:\n t_tile, t_mask = generate_tile(candidates_patch, candidates_mask, tile_size, [1, 2])\n r_tile = torch.cat([r_tile, t_tile], dim=0)\n r_mask = torch.cat([r_mask, t_mask], dim=0)\n\n for _ in range(self.max_iter):\n adv_patch, adv_position = self.collector(self.estimator, x_adv)\n adv_position = adv_position[0]\n candidates_patch = candidates_patch + adv_patch[0]\n candidates_mask = candidates_mask + [None] * len(adv_patch[0])\n\n for key, obj in tile_mat.items():\n idx_i, idx_j = key\n box_1 = obj.xyxy\n obj_threshold = obj.threshold\n [x_1, y_1, x_2, y_2] = box_1.type(torch.IntTensor) # type: ignore\n overlay = bbox_ioa(box_1.type(torch.FloatTensor), adv_position.type(torch.FloatTensor)) # type: ignore\n bcount = torch.sum(overlay > 0.0).item()\n\n pert = x_adv[batch_idx, :, y_1:y_2, x_1:x_2] - x[batch_idx, :, y_1:y_2, x_1:x_2]\n loss = self._get_loss(pert, self.eps)\n eligible = torch.max(torch.abs(pert)) < self.eps and bcount >= obj_threshold\n tpatch_cur = TileObj(tile_size=tile_size, device=self.estimator.device)\n tpatch_cur.update(eligible, bcount, torch.sum(loss), x_adv[batch_idx, :, y_1:y_2, x_1:x_2].clone())\n\n # insert op\n prev = tile_mat[(idx_i, idx_j)]\n prev.insert(tpatch_cur)\n tile_mat[(idx_i, idx_j)] = prev\n\n sorted_patch = tile_mat[(idx_i, idx_j)].patch_list\n bcount_list = []\n for cur_sp in sorted_patch:\n if cur_sp.bcount >= obj_threshold:\n bcount_list.append(cur_sp)\n\n if len(bcount_list) == buffer_depth and bcount_list[-1].bcount > obj_threshold:\n tile_mat[(idx_i, idx_j)].threshold = obj_threshold + 1\n\n if len(bcount_list) < buffer_depth:\n\n while r_tile.shape[0] < int(1.5 * n_samples):\n t_tile, t_mask = generate_tile(candidates_patch, candidates_mask, tile_size, [1, 2])\n r_tile = torch.cat([r_tile, t_tile], dim=0)\n r_mask = torch.cat([r_mask, t_mask], dim=0)\n\n # select n_sample candidates\n c_tile = r_tile\n idx_perm = torch.randperm(c_tile.shape[0])\n idx_perm = idx_perm[:n_samples]\n c_tile = r_tile[idx_perm, :]\n c_mask = r_mask[idx_perm, :]\n x_ref = x[:, :, y_1:y_2, x_1:x_2]\n\n updated = ((1.0 - c_mask) * x_ref) + c_mask * (0.0 * x_ref + 1.0 * c_tile)\n\n n_mask = drop_block2d(c_mask, 0.05, 1)\n updated = (1.0 - n_mask) * x_ref + n_mask * updated\n pert = updated - x_ref\n\n loss = torch.sum(self._get_loss(pert, self.eps), dim=(1, 2, 3))\n min_idx = torch.min(loss, dim=0).indices.item()\n updated = updated[min_idx, :]\n updated = updated[None, :]\n\n else:\n target = bcount_list[0].patch[None, :]\n x_ref = x[batch_idx, :, y_1:y_2, x_1:x_2]\n updated = self._color_projection(target, x_ref, self.eps)\n\n x_adv[batch_idx, :, y_1:y_2, x_1:x_2] = updated\n x_adv = torch.round(x_adv * 255.0) / 255.0\n x_adv = torch.clamp(x_adv, x - 2.5 * self.eps, x + 2.5 * self.eps)\n x_adv = torch.clamp(x_adv, 0.0, 1.0)\n\n x_out = self._assemble(tile_mat, x)\n mask = torch.zeros_like(x_out)\n _, adv_position = self.collector(self.estimator, x_out)\n for pos in adv_position[0]:\n mask[:, :, pos[1] : pos[3], pos[0] : pos[2]] = mask[:, :, pos[1] : pos[3], pos[0] : pos[2]] + 1\n mask = torch.where(mask > 0, torch.ones_like(mask), torch.zeros_like(mask))\n x_adv = mask * x_out + (1.0 - mask) * x\n x_adv = torch.clamp(x_adv, x - self.eps, x + self.eps)\n x_adv = torch.clamp(x_adv, 0.0, 1.0)\n\n return x_adv\n\n def _get_loss(self, pert: \"torch.Tensor\", epsilon: float) -> \"torch.Tensor\": # pylint: disable=R0201\n \"\"\"\n Calculate accumulated distance of the perturbations outside the epsilon ball.\n\n :param pert: Perturbations in the pixel space.\n :param epsilon: The radius of the epsilon bass.\n :return: loss.\n \"\"\"\n import torch\n\n count = torch.where(pert == 0, torch.zeros_like(pert), torch.ones_like(pert))\n pert = torch.where(torch.abs(pert) <= epsilon, torch.zeros_like(pert), pert)\n pert = torch.abs(pert)\n loss = torch.sqrt(pert) / torch.sum(count)\n\n return loss\n\n def _color_projection( # pylint: disable=R0201\n self, tile: \"torch.Tensor\", x_ref: \"torch.Tensor\", epsilon: float\n ) -> \"torch.Tensor\":\n \"\"\"\n Convert statistics information from target to source.\n\n :param tile: The target to convert.\n :param x_ref: The source data.\n :param epsilon: The radius of the epsilon bass.\n :return: The converted tile.\n \"\"\"\n import torch\n\n if len(tile.shape) == 3:\n tile = tile[None, :]\n if len(x_ref.shape) == 3:\n x_ref = x_ref[None, :]\n\n pert = tile - x_ref\n cond = torch.abs(pert) > epsilon\n sign = (torch.rand_like(pert) - 0.5) * 2\n\n u_bound = torch.max(pert, torch.ones_like(pert) * epsilon)\n l_bound = torch.min(pert, torch.ones_like(pert) * -epsilon)\n set1 = torch.where(sign > 0, 0.5 * pert, pert - torch.sign(pert) * epsilon)\n set1 = torch.clamp(set1, l_bound, u_bound)\n set1 = set1 + x_ref\n\n set2 = tile\n mean_s = torch.mean(x_ref, dim=(-2, -1), keepdim=True)\n mean_t = torch.mean(x_ref, dim=(-2, -1), keepdim=True)\n std_s = torch.std(set2, dim=(-2, -1), keepdim=True)\n std_t = torch.std(set2, dim=(-2, -1), keepdim=True)\n scale = std_s / std_t\n set2 = (set2 - mean_t) * scale + mean_s\n set2 = torch.clamp(set2, 0.0, 1.0)\n\n set2 = set2 + sign * epsilon * scale\n set2 = torch.clamp(set2, 0, 1)\n\n updated = torch.where(cond, set1, set2)\n\n return updated\n\n def _assemble(self, tile_mat: dict, x_org: \"torch.Tensor\") -> \"torch.Tensor\": # pylint: disable=R0201\n \"\"\"\n Combine the best patches from each grid into a single image.\n\n :param tile_mat: Internal structure used to store patches for each mesh.\n :param x_org: The original images.\n :return: Perturbed images.\n \"\"\"\n import torch\n\n ans = x_org.clone()\n for obj in tile_mat.values():\n [x_1, y_1, x_2, y_2] = obj.xyxy.type(torch.IntTensor)\n tile = obj.patch_list[0].patch[None, :]\n mask = torch.where(tile != 0, torch.ones_like(tile), torch.zeros_like(tile))\n ans[0, :, y_1:y_2, x_1:x_2] = mask * tile + (1.0 - mask) * ans[0, :, y_1:y_2, x_1:x_2]\n return ans\n\n def _init_guess(\n self, tile_mat: dict, x_init: \"torch.Tensor\", x_org: \"torch.Tensor\", tile_size: int, n_samples: int\n ) -> Tuple[\"torch.Tensor\", dict]:\n \"\"\"\n Generate an initial perturbation for each grid.\n\n :param tile_mat: Internal structure used to store patches for each mesh.\n :param x_init: Perturbed images from previous runs.\n :param x_org: The original images.\n :param tile_size: The size of each tile.\n :return: Guessed images and internal structure.\n \"\"\"\n import torch\n\n TRIAL = 10 # pylint: disable=C0103\n patches = self.candidates\n masks = [None] * len(self.candidates)\n for _ in range(TRIAL):\n x_cand = torch.zeros(\n (n_samples, 3, x_init.shape[-2], x_init.shape[-1]), dtype=x_init.dtype, device=self.estimator.device\n )\n\n # generate tiles\n # To save the computing time, we generate some tiles in advance.\n # partial tiles are updated on-the-fly\n r_tile = torch.zeros((0, 3, tile_size, tile_size), device=self.estimator.device)\n r_mask = torch.zeros((0, 3, tile_size, tile_size), device=self.estimator.device)\n while r_tile.shape[0] < n_samples:\n t_tile, t_mask = generate_tile(patches, masks, tile_size, [1, 2])\n r_tile = torch.cat([r_tile, t_tile], dim=0)\n r_mask = torch.cat([r_mask, t_mask], dim=0)\n\n for _, obj in tile_mat.items():\n # select n_samples\n while r_tile.shape[0] < int(1.5 * n_samples):\n t_tile, t_mask = generate_tile(patches, masks, tile_size, [1, 2])\n r_tile = torch.cat([r_tile, t_tile], dim=0)\n r_mask = torch.cat([r_mask, t_mask], dim=0)\n\n idx_perm = torch.randperm(r_tile.shape[0])\n idx_perm = idx_perm[:n_samples]\n tile_perm = r_tile[idx_perm, :]\n mask_perm = r_mask[idx_perm, :]\n\n # merge tiles\n box_1 = obj.xyxy\n [x_1, y_1, x_2, y_2] = box_1.type(torch.IntTensor)\n x_ref = x_init[:, :, y_1:y_2, x_1:x_2]\n x_new = ((1.0 - mask_perm) * x_ref) + mask_perm * (0.0 * x_ref + 1.0 * tile_perm)\n\n # randomly roll-back\n rand_rb = torch.rand([n_samples, 1, 1, 1], device=self.estimator.device)\n x_new = torch.where(rand_rb < 0.8, x_new, x_ref)\n x_cand[:, :, y_1:y_2, x_1:x_2] = x_new\n\n # spatial drop\n n_mask = drop_block2d(x_cand, 0.05, 3)\n x_cand = (1.0 - n_mask) * x_org + n_mask * x_cand\n # x_cand = smooth_image(x_cand, x_org, epsilon, 10)\n x_cand = torch.round(x_cand * 255.0) / 255.0\n x_cand = torch.clamp(x_cand, x_org - 2.5 * self.eps, x_org + 2.5 * self.eps)\n x_cand = torch.clamp(x_cand, 0.0, 1.0)\n\n # update results\n _, adv_position = self.collector(self.estimator, x_cand)\n for idx in range(n_samples):\n cur_position = adv_position[idx]\n\n for key, obj in tile_mat.items():\n\n idx_i, idx_j = key\n box_1 = obj.xyxy\n obj_threshold = obj.threshold\n [x_1, y_1, x_2, y_2] = box_1.type(torch.IntTensor)\n overlay = bbox_ioa(box_1.type(torch.FloatTensor), cur_position.type(torch.FloatTensor))\n bcount = torch.sum(overlay > 0.0).item()\n\n x_ref = x_org[:, :, y_1:y_2, x_1:x_2]\n x_cur = x_cand[idx, :, y_1:y_2, x_1:x_2].clone()\n\n pert = x_cur - x_ref\n loss = self._get_loss(pert, self.eps)\n eligible = torch.max(torch.abs(pert)) < self.eps and bcount >= obj_threshold\n tpatch_cur = TileObj(tile_size=tile_size, device=self.estimator.device)\n tpatch_cur.update(eligible, bcount, torch.sum(loss), x_cur)\n # insert op\n prev = tile_mat[(idx_i, idx_j)]\n prev.insert(tpatch_cur)\n tile_mat[(idx_i, idx_j)] = prev\n\n # clean non-active regions\n x_out = x_init.clone()\n x_eval = self._assemble(tile_mat, x_org)\n _, adv_position = self.collector(self.estimator, x_eval)\n cur_position = adv_position[0]\n for key, obj in tile_mat.items():\n idx_i, idx_j = key\n box_1 = obj.xyxy\n [x_1, y_1, x_2, y_2] = box_1.type(torch.IntTensor)\n overlay = bbox_ioa(box_1.type(torch.FloatTensor), cur_position.type(torch.FloatTensor))\n bcount = torch.sum(overlay > 0.0).item()\n\n x_ref = x_init[:, :, y_1:y_2, x_1:x_2]\n x_tag = x_eval[:, :, y_1:y_2, x_1:x_2]\n cur_mask = torch.zeros_like(x_ref)\n if bcount > 1:\n bbox = cur_position[overlay > 0.0]\n for box in bbox:\n bx1 = torch.clamp_min(box[0] - x_1, 0)\n by1 = torch.clamp_min(box[1] - y_1, 0)\n bx2 = torch.clamp_max(box[2] - x_1, (x_2 - x_1 - 1).to(self.estimator.device))\n by2 = torch.clamp_max(box[3] - y_1, (y_2 - y_1 - 1).to(self.estimator.device))\n cur_mask[:, :, by1:by2, bx1:bx2] = 1.0\n else:\n prev = tile_mat[(idx_i, idx_j)]\n prev.pop()\n tile_mat[(idx_i, idx_j)] = prev\n\n a_mask = drop_block2d(x_ref, 0.05, 1)\n cur_mask = cur_mask * a_mask\n updated = ((1.0 - cur_mask) * x_ref) + cur_mask * (0.0 * x_ref + 1.0 * x_tag)\n updated = ((1.0 - cur_mask) * x_ref) + cur_mask * (0.0 * x_ref + 1.0 * updated)\n\n x_out[:, :, y_1:y_2, x_1:x_2] = updated\n\n return x_out, tile_mat\n\n def _check_params(self) -> None:\n\n if not isinstance(self.eps, float):\n raise TypeError(\"The eps has to be of type float.\")\n\n if self.eps < 0 or self.eps > 1:\n raise ValueError(\"The eps must be in the range [0, 1].\")\n\n if not isinstance(self.max_iter, int):\n raise TypeError(\"The max_iter has to be of type int.\")\n\n if self.max_iter < 1:\n raise ValueError(\"The number of iterations must be a positive integer.\")\n\n if not isinstance(self.num_grid, int):\n raise TypeError(\"The num_grid has to be of type int.\")\n\n if self.num_grid < 1:\n raise ValueError(\"The number of grid must be a positive integer.\")\n\n if not isinstance(self.candidates, list):\n raise TypeError(\"Candidates must be stored in list.\")\n\n if len(self.candidates) < 1:\n raise ValueError(\"The list of candidates is empty.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/extraction/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing extraction attacks under a common interface.\n\"\"\"\n\nfrom art.attacks.extraction.functionally_equivalent_extraction import FunctionallyEquivalentExtraction\nfrom art.attacks.extraction.copycat_cnn import CopycatCNN\nfrom art.attacks.extraction.knockoff_nets import KnockoffNets\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/extraction/copycat_cnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the copycat cnn attack `CopycatCNN`.\n\n| Paper link: https://arxiv.org/abs/1806.05476\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import ExtractionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import to_categorical\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass CopycatCNN(ExtractionAttack):\n \"\"\"\n Implementation of the Copycat CNN attack from Rodrigues Correia-Silva et al. (2018).\n\n | Paper link: https://arxiv.org/abs/1806.05476\n \"\"\"\n\n attack_params = ExtractionAttack.attack_params + [\n \"batch_size_fit\",\n \"batch_size_query\",\n \"nb_epochs\",\n \"nb_stolen\",\n \"use_probability\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n batch_size_fit: int = 1,\n batch_size_query: int = 1,\n nb_epochs: int = 10,\n nb_stolen: int = 1,\n use_probability: bool = False,\n ) -> None:\n \"\"\"\n Create a Copycat CNN attack instance.\n\n :param classifier: A victim classifier.\n :param batch_size_fit: Size of batches for fitting the thieved classifier.\n :param batch_size_query: Size of batches for querying the victim classifier.\n :param nb_epochs: Number of epochs to use for training.\n :param nb_stolen: Number of queries submitted to the victim classifier to steal it.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.batch_size_fit = batch_size_fit\n self.batch_size_query = batch_size_query\n self.nb_epochs = nb_epochs\n self.nb_stolen = nb_stolen\n self.use_probability = use_probability\n self._check_params()\n\n def extract(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Extract a thieved classifier.\n\n :param x: An array with the source input to the victim classifier.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,). Not used in this attack.\n :param thieved_classifier: A classifier to be stolen, currently always trained on one-hot labels.\n :type thieved_classifier: :class:`.Classifier`\n :return: The stolen classifier.\n \"\"\"\n # Warning to users if y is not None\n if y is not None: # pragma: no cover\n logger.warning(\"This attack does not use the provided label y.\")\n\n # Check the size of the source input vs nb_stolen\n if x.shape[0] < self.nb_stolen: # pragma: no cover\n logger.warning(\n \"The size of the source input is smaller than the expected number of queries submitted \"\n \"to the victim classifier.\"\n )\n\n # Check if there is a thieved classifier provided for training\n thieved_classifier = kwargs[\"thieved_classifier\"]\n if thieved_classifier is None or not isinstance(thieved_classifier, ClassifierMixin): # pragma: no cover\n raise ValueError(\"A thieved classifier is needed.\")\n\n # Select data to attack\n selected_x = self._select_data(x)\n\n # Query the victim classifier\n fake_labels = self._query_label(selected_x)\n\n # Train the thieved classifier\n thieved_classifier.fit( # type: ignore\n x=selected_x,\n y=fake_labels,\n batch_size=self.batch_size_fit,\n nb_epochs=self.nb_epochs,\n )\n\n return thieved_classifier # type: ignore\n\n def _select_data(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Select data to attack.\n\n :param x: An array with the source input to the victim classifier.\n :return: An array with the selected input to the victim classifier.\n \"\"\"\n nb_stolen = np.minimum(self.nb_stolen, x.shape[0])\n rnd_index = np.random.choice(x.shape[0], nb_stolen, replace=False)\n\n return x[rnd_index].astype(ART_NUMPY_DTYPE)\n\n def _query_label(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Query the victim classifier.\n\n :param x: An array with the source input to the victim classifier.\n :return: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n \"\"\"\n labels = self.estimator.predict(x=x, batch_size=self.batch_size_query)\n if not self.use_probability:\n labels = np.argmax(labels, axis=1)\n labels = to_categorical(labels=labels, nb_classes=self.estimator.nb_classes)\n\n return labels\n\n def _check_params(self) -> None:\n if not isinstance(self.batch_size_fit, int) or self.batch_size_fit <= 0:\n raise ValueError(\"The size of batches for fitting the thieved classifier must be a positive integer.\")\n\n if not isinstance(self.batch_size_query, int) or self.batch_size_query <= 0:\n raise ValueError(\"The size of batches for querying the victim classifier must be a positive integer.\")\n\n if not isinstance(self.nb_epochs, int) or self.nb_epochs <= 0:\n raise ValueError(\"The number of epochs must be a positive integer.\")\n\n if not isinstance(self.nb_stolen, int) or self.nb_stolen <= 0:\n raise ValueError(\"The number of queries submitted to the victim classifier must be a positive integer.\")\n\n if not isinstance(self.use_probability, bool):\n raise ValueError(\"The argument `use_probability` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/extraction/functionally_equivalent_extraction.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Functionally Equivalent Extraction attack mainly following Jagielski et al. (2019).\n\nThis module contains en example application for MNIST which can be run as `python functionally_equivalent_extraction.py`\nproducing output like:\n\nTarget model - Test accuracy: 0.9259\nExtracted model - Test accuracy: 0.9259\nExtracted model - Test Fidelity: 0.9977\n\n| Paper link: https://arxiv.org/abs/1909.01838\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport os\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.optimize import least_squares\n\nfrom art.attacks.attack import ExtractionAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.classification.blackbox import BlackBoxClassifier\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nNUMPY_DTYPE = np.float64 # pylint: disable=invalid-name\n\nlogger = logging.getLogger(__name__)\n\n\nclass FunctionallyEquivalentExtraction(ExtractionAttack):\n \"\"\"\n This module implements the Functionally Equivalent Extraction attack for neural networks with two dense layers,\n ReLU activation at the first layer and logits output after the second layer.\n\n | Paper link: https://arxiv.org/abs/1909.01838\n \"\"\"\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\", num_neurons: int | None = None) -> None:\n \"\"\"\n Create a `FunctionallyEquivalentExtraction` instance.\n\n :param classifier: A trained ART classifier.\n :param num_neurons: The number of neurons in the first dense layer.\n \"\"\"\n super().__init__(estimator=classifier)\n self.num_neurons = num_neurons\n self.num_classes = classifier.nb_classes\n self.num_features = int(np.prod(classifier.input_shape))\n\n self.vector_u = np.random.normal(0, 1, (1, self.num_features)).astype(dtype=NUMPY_DTYPE)\n self.vector_v = np.random.normal(0, 1, (1, self.num_features)).astype(dtype=NUMPY_DTYPE)\n\n self.critical_points: list[np.ndarray] = []\n\n self.w_0: np.ndarray | None = None # Weight matrix of first dense layer\n self.b_0: np.ndarray | None = None # Bias vector of first dense layer\n self.w_1: np.ndarray | None = None # Weight matrix of second dense layer\n self.b_1: np.ndarray | None = None # Bias vector of second dense layer\n\n def extract(\n self,\n x: np.ndarray,\n y: np.ndarray | None = None,\n delta_0: float = 0.05,\n fraction_true: float = 0.3,\n rel_diff_slope: float = 0.00001,\n rel_diff_value: float = 0.000001,\n delta_init_value: float = 0.1,\n delta_value_max: int = 50,\n d2_min: float = 0.0004,\n d_step: float = 0.01,\n delta_sign: float = 0.02,\n unit_vector_scale: int = 10000,\n ftol: float = 1e-8,\n **kwargs,\n ) -> BlackBoxClassifier:\n \"\"\"\n Extract the targeted model.\n\n :param x: Samples of input data of shape (num_samples, num_features).\n :param y: Correct labels or target labels for `x`, depending on if the attack is targeted\n or not. This parameter is only used by some of the attacks.\n :param delta_0: Initial step size of binary search.\n :param fraction_true: Fraction of output predictions that have to fulfill criteria for critical point.\n :param rel_diff_slope: Relative slope difference at critical points.\n :param rel_diff_value: Relative value difference at critical points.\n :param delta_init_value: Initial delta of weight value search.\n :param delta_value_max: Maximum delta of weight value search.\n :param d2_min: Minimum acceptable value of sum of absolute second derivatives.\n :param d_step: Step size of delta increase.\n :param delta_sign: Delta of weight sign search.\n :param unit_vector_scale: Multiplicative scale of the unit vector `e_j`.\n :param ftol: Tolerance for termination by the change of the cost function.\n :return: ART :class:`.BlackBoxClassifier` of the extracted model.\n \"\"\"\n self._critical_point_search(\n delta_0=delta_0,\n fraction_true=fraction_true,\n rel_diff_slope=rel_diff_slope,\n rel_diff_value=rel_diff_value,\n )\n self._weight_recovery(\n delta_init_value=delta_init_value,\n delta_value_max=delta_value_max,\n d2_min=d2_min,\n d_step=d_step,\n delta_sign=delta_sign,\n )\n self._sign_recovery(unit_vector_scale=unit_vector_scale, ftol=ftol)\n self._last_layer_extraction(x, ftol)\n\n def predict(x: np.ndarray) -> np.ndarray:\n \"\"\"\n Predict extracted model.\n\n :param x: Samples of input data of shape `(num_samples, num_features)`.\n :return: Predictions with the extracted model of shape `(num_samples, num_classes)`.\n \"\"\"\n layer_0 = np.maximum(np.matmul(self.w_0.T, x.T) + self.b_0, 0.0) # type: ignore\n layer_1 = np.matmul(self.w_1.T, layer_0) + self.b_1 # type: ignore\n return layer_1.T\n\n extracted_classifier = BlackBoxClassifier(\n predict,\n input_shape=self.estimator.input_shape,\n nb_classes=self.estimator.nb_classes,\n clip_values=self.estimator.clip_values,\n preprocessing_defences=self.estimator.preprocessing_defences,\n preprocessing=self.estimator.preprocessing,\n )\n\n return extracted_classifier\n\n def _o_l(self, x: np.ndarray, e_j: np.ndarray | None = None) -> np.ndarray:\n \"\"\"\n Predict the target model.\n\n :param x: Samples of input data of shape `(num_samples, num_features)`.\n :param e_j: Additive delta vector of shape `(1, num_features)`.\n :return: Prediction of the target model of shape `(num_samples, num_classes)`.\n \"\"\"\n if e_j is not None:\n x = x + e_j\n return self.estimator.predict(x).astype(NUMPY_DTYPE)\n\n def _get_x(self, var_t: float) -> np.ndarray:\n \"\"\"\n Get input sample as function of multiplicative factor of random vector.\n\n :param var_t: Multiplicative factor of second random vector for critical point search.\n :return: Input sample of shape `(1, num_features)`.\n \"\"\"\n return self.vector_u + var_t * self.vector_v\n\n def _critical_point_search(\n self,\n delta_0: float,\n fraction_true: float,\n rel_diff_slope: float,\n rel_diff_value: float,\n ) -> None:\n \"\"\"\n Search for critical points.\n\n :param delta_0: Initial step size of binary search.\n :param fraction_true: Fraction of output predictions that have to fulfill criteria for critical point.\n :param rel_diff_slope: Relative slope difference at critical points.\n :param rel_diff_value: Relative value difference at critical points.\n \"\"\"\n logger.info(\"Searching for critical points.\")\n\n if self.num_neurons is None:\n raise ValueError(\"The value of `num_neurons` is required for critical point search.\")\n h_square = self.num_neurons * self.num_neurons\n\n t_current = float(-h_square)\n while t_current < h_square:\n delta = delta_0\n found_critical_point = False\n\n while not found_critical_point:\n epsilon = delta / 10\n\n t_1 = t_current\n t_2 = t_current + delta\n\n x_1 = self._get_x(t_1)\n x_1_p = self._get_x(t_1 + epsilon)\n x_2 = self._get_x(t_2)\n x_2_m = self._get_x(t_2 - epsilon)\n\n m_1 = (self._o_l(x_1_p) - self._o_l(x_1)) / epsilon\n m_2 = (self._o_l(x_2) - self._o_l(x_2_m)) / epsilon\n\n y_1 = self._o_l(x_1)\n y_2 = self._o_l(x_2)\n\n if np.sum(np.abs((m_1 - m_2) / m_1) < rel_diff_slope) > fraction_true * self.num_classes:\n t_current = t_2\n break\n\n t_hat = t_1 + np.divide(y_2 - y_1 - (t_2 - t_1) * m_2, m_1 - m_2)\n y_hat = y_1 + m_1 * np.divide(y_2 - y_1 - (t_2 - t_1) * m_2, m_1 - m_2)\n\n t_mean = np.mean(t_hat[t_hat != -np.inf])\n\n x_mean = self._get_x(t_mean)\n x_mean_p = self._get_x(t_mean + epsilon)\n x_mean_m = self._get_x(t_mean - epsilon)\n\n y = self._o_l(x_mean)\n\n m_x_1 = (self._o_l(x_mean_p) - self._o_l(x_mean)) / epsilon\n m_x_2 = (self._o_l(x_mean) - self._o_l(x_mean_m)) / epsilon\n\n if (\n np.sum(np.abs((y_hat - y) / y) < rel_diff_value) > fraction_true * self.num_classes\n and t_1 < t_mean < t_2\n and np.sum(np.abs((m_x_1 - m_x_2) / m_x_1) > rel_diff_slope) > fraction_true * self.num_classes\n ):\n found_critical_point = True\n self.critical_points.append(x_mean)\n t_current = t_2\n else:\n delta = delta / 2\n\n if len(self.critical_points) != self.num_neurons:\n raise AssertionError(\n f\"The number of critical points found ({len(self.critical_points)}) does not equal the number of \"\n f\"expected neurons in the first layer ({self.num_neurons}).\"\n )\n\n def _weight_recovery(\n self,\n delta_init_value: float,\n delta_value_max: float,\n d2_min: float,\n d_step: float,\n delta_sign: float,\n ) -> None:\n \"\"\"\n Recover the weights and biases of the first layer.\n\n :param delta_init_value: Initial delta of weight value search.\n :param delta_value_max: Maximum delta of weight value search.\n :param d2_min: Minimum acceptable value of sum of absolute second derivatives.\n :param d_step: Step size of delta increase.\n :param delta_sign: Delta of weight sign search.\n \"\"\"\n logger.info(\"Recovering weights of first layer.\")\n\n if self.num_neurons is None:\n raise ValueError(\"The value of `num_neurons` is required for critical point search.\")\n\n # Absolute Value Recovery\n d2_ol_d2ej_xi = np.zeros((self.num_features, self.num_neurons), dtype=NUMPY_DTYPE)\n\n for i in range(self.num_neurons):\n for j in range(self.num_features):\n\n delta = delta_init_value\n e_j = np.zeros((1, self.num_features))\n d2_ol_d2ej_xi_ok = False\n\n while not d2_ol_d2ej_xi_ok:\n\n e_j[0, j] = delta\n\n d_ol_dej_xi_p_cej = (\n self._o_l(self.critical_points[i], e_j=e_j) - self._o_l(self.critical_points[i])\n ) / delta\n d_ol_dej_xi_m_cej = (\n self._o_l(self.critical_points[i]) - self._o_l(self.critical_points[i], e_j=-e_j)\n ) / delta\n\n d2_ol_d2ej_xi[j, i] = np.sum(np.abs(d_ol_dej_xi_p_cej - d_ol_dej_xi_m_cej)) / delta\n\n if d2_ol_d2ej_xi[j, i] < d2_min and delta < delta_value_max:\n delta = delta + d_step\n else:\n d2_ol_d2ej_xi_ok = True\n\n self.a0_pairwise_ratios = np.zeros((self.num_features, self.num_neurons), dtype=NUMPY_DTYPE)\n\n for i in range(self.num_neurons):\n for k in range(self.num_features):\n self.a0_pairwise_ratios[k, i] = d2_ol_d2ej_xi[0, i] / d2_ol_d2ej_xi[k, i]\n\n # Weight Sign Recovery\n\n for i in range(self.num_neurons):\n d2_ol_dejek_xi_0 = None\n for j in range(self.num_features):\n\n e_j = np.zeros((1, self.num_features), dtype=NUMPY_DTYPE)\n\n e_j[0, 0] += delta_sign\n e_j[0, j] += delta_sign\n\n d_ol_dejek_xi_p_cejek = (\n self._o_l(self.critical_points[i], e_j=e_j) - self._o_l(self.critical_points[i])\n ) / delta_sign\n d_ol_dejek_xi_m_cejek = (\n self._o_l(self.critical_points[i]) - self._o_l(self.critical_points[i], e_j=-e_j)\n ) / delta_sign\n\n d2_ol_dejek_xi = d_ol_dejek_xi_p_cejek - d_ol_dejek_xi_m_cejek\n\n if j == 0:\n d2_ol_dejek_xi_0 = d2_ol_dejek_xi / 2.0\n\n co_p = np.sum(np.abs(d2_ol_dejek_xi_0 * (1 + 1 / self.a0_pairwise_ratios[j, i]) - d2_ol_dejek_xi))\n co_m = np.sum(np.abs(d2_ol_dejek_xi_0 * (1 - 1 / self.a0_pairwise_ratios[j, i]) - d2_ol_dejek_xi))\n\n if co_m < co_p * np.max(1 / self.a0_pairwise_ratios[:, i]):\n self.a0_pairwise_ratios[j, i] *= -1\n\n def _sign_recovery(self, unit_vector_scale: int, ftol: float) -> None:\n \"\"\"\n Recover the sign of weights in the first layer.\n\n :param unit_vector_scale: Multiplicative scale of the unit vector e_j.\n :param ftol: Tolerance for termination by the change of the cost function.\n \"\"\"\n logger.info(\"Recover sign of the weights of the first layer.\")\n\n if self.num_neurons is None:\n raise ValueError(\"The value of `num_neurons` is required for critical point search.\")\n\n a0_pairwise_ratios_inverse = 1.0 / self.a0_pairwise_ratios\n self.b_0 = np.zeros((self.num_neurons, 1), dtype=NUMPY_DTYPE)\n\n for i in range(self.num_neurons):\n x_i = self.critical_points[i].flatten()\n self.b_0[i] = -np.matmul(a0_pairwise_ratios_inverse[:, i], x_i)\n\n z_0 = np.random.normal(0, 1, (self.num_features,)).astype(dtype=NUMPY_DTYPE)\n\n def f_z(z_i):\n return np.squeeze(np.matmul(a0_pairwise_ratios_inverse.T, np.expand_dims(z_i, axis=0).T) + self.b_0)\n\n result_z = least_squares(f_z, z_0, ftol=ftol)\n\n for i in range(self.num_neurons):\n e_i = np.zeros((self.num_neurons, 1), dtype=NUMPY_DTYPE)\n e_i[i, 0] = unit_vector_scale\n\n def f_v(v_i):\n # pylint: disable=cell-var-from-loop\n return np.squeeze(np.matmul(-a0_pairwise_ratios_inverse.T, np.expand_dims(v_i, axis=0).T) - e_i)\n\n v_0 = np.random.normal(0, 1, self.num_features)\n result_v_i = least_squares(f_v, v_0, ftol=ftol)\n value_p = np.sum(\n np.abs(\n self._o_l(np.expand_dims(result_z.x, axis=0))\n - (self._o_l(np.expand_dims(result_z.x + result_v_i.x, axis=0)))\n )\n )\n value_m = np.sum(\n np.abs(\n self._o_l(np.expand_dims(result_z.x, axis=0))\n - (self._o_l(np.expand_dims(result_z.x - result_v_i.x, axis=0)))\n )\n )\n\n if value_m < value_p:\n a0_pairwise_ratios_inverse[:, i] *= -1\n self.b_0[i, 0] *= -1\n\n self.w_0 = a0_pairwise_ratios_inverse\n\n def _last_layer_extraction(self, x: np.ndarray, ftol: float) -> None:\n \"\"\"\n Extract weights and biases of the second layer.\n\n :param x: Samples of input data of shape `(num_samples, num_features)`.\n :param ftol: Tolerance for termination by the change of the cost function.\n \"\"\"\n logger.info(\"Extract second layer.\")\n\n if self.num_neurons is None:\n raise ValueError(\"The value of `num_neurons` is required for critical point search.\")\n\n predictions = self._o_l(x)\n w_1_b_1_0 = np.random.normal(0, 1, ((self.num_neurons + 1) * self.num_classes)).astype(dtype=NUMPY_DTYPE)\n\n def f_w_1_b_1(w_1_b_1_i):\n layer_0 = np.maximum(np.matmul(self.w_0.T, x.T) + self.b_0, 0.0)\n\n w_1 = w_1_b_1_i[0 : self.num_neurons * self.num_classes].reshape(self.num_neurons, self.num_classes)\n b_1 = w_1_b_1_i[self.num_neurons * self.num_classes :].reshape(self.num_classes, 1)\n\n layer_1 = np.matmul(w_1.T, layer_0) + b_1\n\n return np.squeeze((layer_1.T - predictions).flatten())\n\n result_a1_b1 = least_squares(f_w_1_b_1, w_1_b_1_0, ftol=ftol)\n\n self.w_1 = result_a1_b1.x[0 : self.num_neurons * self.num_classes].reshape(self.num_neurons, self.num_classes)\n self.b_1 = result_a1_b1.x[self.num_neurons * self.num_classes :].reshape(self.num_classes, 1)\n\n\n# pylint: disable=invalid-name\nif __name__ == \"__main__\":\n import os\n import numpy as np\n import tensorflow as tf\n\n from keras.models import Sequential, load_model\n from keras.layers import Dense, Input\n from keras.losses import CategoricalCrossentropy\n from keras.optimizers import Adam\n from keras.utils import to_categorical\n from keras.datasets import mnist\n\n # Keras 3.10+ runs in eager mode by default (do NOT disable it!)\n tf.keras.backend.set_floatx(\"float64\")\n np.random.seed(1)\n\n # Hyperparameters\n number_neurons = 4\n batch_size = 10\n number_classes = 10\n epochs = 100\n img_rows = 28\n img_cols = 28\n number_channels = 1\n\n # Load and reshape data\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n x_train = x_train.reshape((x_train.shape[0], -1)).astype(\"float64\") # shape = (60000, 784)\n x_test = x_test.reshape((x_test.shape[0], -1)).astype(\"float64\") # shape = (10000, 784)\n\n # Standardize\n mean = np.mean(x_train)\n std = np.std(x_train)\n x_train = (x_train - mean) / std\n x_test = (x_test - mean) / std\n\n # One-hot encode\n y_train = to_categorical(y_train, number_classes)\n y_test = to_categorical(y_test, number_classes)\n\n # Define input shape\n input_shape = (784,)\n\n # Load or create model\n if os.path.isfile(\"./model.keras\"):\n model = load_model(\"./model.keras\", compile=False)\n model.compile(\n loss=CategoricalCrossentropy(from_logits=True), optimizer=Adam(learning_rate=0.0001), metrics=[\"accuracy\"]\n )\n else:\n model = Sequential(\n [\n Input(shape=input_shape),\n Dense(number_neurons, activation=\"relu\"),\n Dense(number_classes, activation=\"linear\"),\n ]\n )\n model.compile(\n loss=CategoricalCrossentropy(from_logits=True), optimizer=Adam(learning_rate=0.001), metrics=[\"accuracy\"]\n )\n model.fit(\n x_train[0:100],\n y_train[0:100],\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test),\n )\n model.save(\"./model.keras\")\n\n # Evaluate target model\n score_target = model.evaluate(x_test, y_test, verbose=0)\n\n # Wrap with ART\n target_classifier = KerasClassifier(model=model, use_logits=True, clip_values=(0, 1))\n\n # Run Functionally Equivalent Extraction\n fee = FunctionallyEquivalentExtraction(classifier=target_classifier, num_neurons=number_neurons) # type: ignore\n bbc = fee.extract(x_test[0:100])\n\n # Predictions\n y_test_predicted_extracted = bbc.predict(x_test)\n y_test_predicted_target = target_classifier.predict(x_test)\n\n # Metrics\n print(\"Target model - Test accuracy:\", score_target[1])\n print(\n \"Extracted model - Test accuracy:\",\n np.mean(np.argmax(y_test_predicted_extracted, axis=1) == np.argmax(y_test, axis=1)),\n )\n print(\n \"Extracted model - Test Fidelity:\",\n np.mean(np.argmax(y_test_predicted_extracted, axis=1) == np.argmax(y_test_predicted_target, axis=1)),\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/extraction/knockoff_nets.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Knockoff Nets attack `KnockoffNets`.\n\n| Paper link: https://arxiv.org/abs/1812.02766\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import ExtractionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import to_categorical\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass KnockoffNets(ExtractionAttack):\n \"\"\"\n Implementation of the Knockoff Nets attack from Orekondy et al. (2018).\n\n | Paper link: https://arxiv.org/abs/1812.02766\n \"\"\"\n\n attack_params = ExtractionAttack.attack_params + [\n \"batch_size_fit\",\n \"batch_size_query\",\n \"nb_epochs\",\n \"nb_stolen\",\n \"sampling_strategy\",\n \"reward\",\n \"verbose\",\n \"use_probability\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n batch_size_fit: int = 1,\n batch_size_query: int = 1,\n nb_epochs: int = 10,\n nb_stolen: int = 1,\n sampling_strategy: str = \"random\",\n reward: str = \"all\",\n verbose: bool = True,\n use_probability: bool = False,\n ) -> None:\n \"\"\"\n Create a KnockoffNets attack instance. Note, it is assumed that both the victim classifier and the thieved\n classifier produce logit outputs.\n\n :param classifier: A victim classifier.\n :param batch_size_fit: Size of batches for fitting the thieved classifier.\n :param batch_size_query: Size of batches for querying the victim classifier.\n :param nb_epochs: Number of epochs to use for training.\n :param nb_stolen: Number of queries submitted to the victim classifier to steal it.\n :param sampling_strategy: Sampling strategy, either `random` or `adaptive`.\n :param reward: Reward type, in ['cert', 'div', 'loss', 'all'].\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.batch_size_fit = batch_size_fit\n self.batch_size_query = batch_size_query\n self.nb_epochs = nb_epochs\n self.nb_stolen = nb_stolen\n self.sampling_strategy = sampling_strategy\n self.reward = reward\n self.verbose = verbose\n self.use_probability = use_probability\n self._check_params()\n\n def extract(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Extract a thieved classifier.\n\n :param x: An array with the source input to the victim classifier.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n `(nb_samples,)`.\n :param thieved_classifier: A thieved classifier to be stolen.\n :return: The stolen classifier.\n \"\"\"\n # Check prerequisite for random strategy\n if self.sampling_strategy == \"random\" and y is not None: # pragma: no cover\n logger.warning(\"This attack with random sampling strategy does not use the provided label y.\")\n\n # Check prerequisite for adaptive strategy\n if self.sampling_strategy == \"adaptive\" and y is None: # pragma: no cover\n raise ValueError(\"This attack with adaptive sampling strategy needs label y.\")\n\n # Check the size of the source input vs nb_stolen\n if x.shape[0] < self.nb_stolen: # pragma: no cover\n logger.warning(\n \"The size of the source input is smaller than the expected number of queries submitted \"\n \"to the victim classifier.\"\n )\n\n # Check if there is a thieved classifier provided for training\n thieved_classifier = kwargs.get(\"thieved_classifier\")\n if thieved_classifier is None or not isinstance(thieved_classifier, ClassifierMixin): # pragma: no cover\n raise ValueError(\"A thieved classifier is needed.\")\n\n # Implement model extractions\n if self.sampling_strategy == \"random\":\n thieved_classifier = self._random_extraction(x, thieved_classifier) # type: ignore\n else:\n thieved_classifier = self._adaptive_extraction(x, y, thieved_classifier) # type: ignore\n\n return thieved_classifier\n\n def _random_extraction(self, x: np.ndarray, thieved_classifier: \"CLASSIFIER_TYPE\") -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Extract with the random sampling strategy.\n\n :param x: An array with the source input to the victim classifier.\n :param thieved_classifier: A thieved classifier to be stolen.\n :return: The stolen classifier.\n \"\"\"\n # Select data to attack\n selected_x = self._select_data(x)\n\n # Query the victim classifier\n fake_labels = self._query_label(selected_x)\n\n # Train the thieved classifier\n thieved_classifier.fit(\n x=selected_x,\n y=fake_labels,\n batch_size=self.batch_size_fit,\n nb_epochs=self.nb_epochs,\n verbose=False,\n )\n\n return thieved_classifier\n\n def _select_data(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Select data to attack.\n\n :param x: An array with the source input to the victim classifier.\n :return: An array with the selected input to the victim classifier.\n \"\"\"\n nb_stolen = np.minimum(self.nb_stolen, x.shape[0])\n rnd_index = np.random.choice(x.shape[0], nb_stolen, replace=False)\n\n return x[rnd_index].astype(ART_NUMPY_DTYPE)\n\n def _query_label(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Query the victim classifier.\n\n :param x: An array with the source input to the victim classifier.\n :return: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.\n \"\"\"\n labels = self.estimator.predict(x=x, batch_size=self.batch_size_query)\n if not self.use_probability:\n labels = np.argmax(labels, axis=1)\n labels = to_categorical(labels=labels, nb_classes=self.estimator.nb_classes)\n\n return labels\n\n def _adaptive_extraction(\n self, x: np.ndarray, y: np.ndarray, thieved_classifier: \"CLASSIFIER_TYPE\"\n ) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Extract with the adaptive sampling strategy.\n\n :param x: An array with the source input to the victim classifier.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param thieved_classifier: A thieved classifier to be stolen.\n :return: The stolen classifier.\n \"\"\"\n # Compute number of actions\n if len(y.shape) == 2:\n nb_actions = len(np.unique(np.argmax(y, axis=1)))\n elif len(y.shape) == 1:\n nb_actions = len(np.unique(y))\n else:\n raise ValueError(\"Target values `y` has a wrong shape.\")\n\n # We need to keep an average version of the victim output\n if self.reward in (\"div\", \"all\"):\n self.y_avg = np.zeros(self.estimator.nb_classes)\n\n # We need to keep an average and variance version of rewards\n if self.reward == \"all\":\n self.reward_avg = np.zeros(3)\n self.reward_var = np.zeros(3)\n\n # Implement the bandit gradients algorithm\n h_func = np.zeros(nb_actions)\n learning_rate = np.zeros(nb_actions)\n probs = np.ones(nb_actions) / nb_actions\n selected_x = []\n queried_labels = []\n\n avg_reward = 0.0\n for iteration in trange(1, self.nb_stolen + 1, desc=\"Knock-off nets\", disable=not self.verbose):\n # Sample an action\n action = np.random.choice(np.arange(0, nb_actions), p=probs)\n\n # Sample data to attack\n sampled_x = self._sample_data(x, y, action)\n selected_x.append(sampled_x)\n\n # Query the victim classifier\n y_output = self.estimator.predict(x=np.array([sampled_x]), batch_size=self.batch_size_query)\n fake_label = np.argmax(y_output, axis=1)\n fake_label = to_categorical(labels=fake_label, nb_classes=self.estimator.nb_classes)\n queried_labels.append(fake_label[0])\n\n # Train the thieved classifier\n thieved_classifier.fit(\n x=np.array([sampled_x]),\n y=fake_label,\n batch_size=self.batch_size_fit,\n nb_epochs=1,\n verbose=False,\n )\n\n # Test new labels\n y_hat = thieved_classifier.predict(x=np.array([sampled_x]), batch_size=self.batch_size_query)\n\n # Compute rewards\n reward = self._reward(y_output, y_hat, iteration)\n avg_reward = avg_reward + (1.0 / iteration) * (reward - avg_reward)\n\n # Update learning rate\n learning_rate[action] += 1\n\n # Update H function\n for i_action in range(nb_actions):\n if i_action != action:\n h_func[i_action] = (\n h_func[i_action] - 1.0 / learning_rate[action] * (reward - avg_reward) * probs[i_action]\n )\n else:\n h_func[i_action] = h_func[i_action] + 1.0 / learning_rate[action] * (reward - avg_reward) * (\n 1 - probs[i_action]\n )\n\n # Update probs\n aux_exp = np.exp(h_func)\n probs = aux_exp / np.sum(aux_exp)\n\n # Train the thieved classifier the final time\n thieved_classifier.fit(\n x=np.array(selected_x),\n y=np.array(queried_labels),\n batch_size=self.batch_size_fit,\n nb_epochs=self.nb_epochs,\n )\n\n return thieved_classifier\n\n @staticmethod\n def _sample_data(x: np.ndarray, y: np.ndarray, action: int) -> np.ndarray:\n \"\"\"\n Sample data with a specific action.\n\n :param x: An array with the source input to the victim classifier.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param action: The action index returned from the action sampling.\n :return: An array with one input to the victim classifier.\n \"\"\"\n if len(y.shape) == 2:\n y_index = np.argmax(y, axis=1)\n else:\n y_index = y\n\n x_index = x[y_index == action]\n rnd_idx = np.random.choice(len(x_index))\n\n return x_index[rnd_idx]\n\n def _reward(self, y_output: np.ndarray, y_hat: np.ndarray, n: int) -> float | np.ndarray:\n \"\"\"\n Compute reward value.\n\n :param y_output: Output of the victim classifier.\n :param y_hat: Output of the thieved classifier.\n :param n: Current iteration.\n :return: Reward value.\n \"\"\"\n if self.reward == \"cert\":\n return self._reward_cert(y_output)\n if self.reward == \"div\":\n return self._reward_div(y_output, n)\n if self.reward == \"loss\":\n return self._reward_loss(y_output, y_hat)\n return self._reward_all(y_output, y_hat, n)\n\n @staticmethod\n def _reward_cert(y_output: np.ndarray) -> float:\n \"\"\"\n Compute `cert` reward value.\n\n :param y_output: Output of the victim classifier.\n :return: Reward value.\n \"\"\"\n largests = np.partition(y_output.flatten(), -2)[-2:]\n reward = largests[1] - largests[0]\n\n return reward\n\n def _reward_div(self, y_output: np.ndarray, n: int) -> float:\n \"\"\"\n Compute `div` reward value.\n\n :param y_output: Output of the victim classifier.\n :param n: Current iteration.\n :return: Reward value.\n \"\"\"\n # First update y_avg\n self.y_avg = self.y_avg + (1.0 / n) * (y_output[0] - self.y_avg)\n\n # Then compute reward\n reward = 0\n for k in range(self.estimator.nb_classes):\n reward += np.maximum(0, y_output[0][k] - self.y_avg[k])\n\n return reward\n\n def _reward_loss(self, y_output: np.ndarray, y_hat: np.ndarray) -> float:\n \"\"\"\n Compute `loss` reward value.\n\n :param y_output: Output of the victim classifier.\n :param y_hat: Output of the thieved classifier.\n :return: Reward value.\n \"\"\"\n # Compute victim probs\n aux_exp = np.exp(y_output[0])\n probs_output = aux_exp / np.sum(aux_exp)\n\n # Compute thieved probs\n aux_exp = np.exp(y_hat[0])\n probs_hat = aux_exp / np.sum(aux_exp)\n\n # Compute reward\n reward = 0\n for k in range(self.estimator.nb_classes):\n reward += -probs_output[k] * np.log(probs_hat[k])\n\n return reward\n\n def _reward_all(self, y_output: np.ndarray, y_hat: np.ndarray, n: int) -> float:\n \"\"\"\n Compute `all` reward value.\n\n :param y_output: Output of the victim classifier.\n :param y_hat: Output of the thieved classifier.\n :param n: Current iteration.\n :return: Reward value.\n \"\"\"\n reward_cert = self._reward_cert(y_output)\n reward_div = self._reward_div(y_output, n)\n reward_loss = self._reward_loss(y_output, y_hat)\n reward = [reward_cert, reward_div, reward_loss]\n self.reward_avg = self.reward_avg + (1.0 / n) * (reward - self.reward_avg)\n self.reward_var = self.reward_var + (1.0 / n) * ((reward - self.reward_avg) ** 2 - self.reward_var)\n\n # Normalize rewards\n if n > 1:\n reward = (reward - self.reward_avg) / np.sqrt(self.reward_var)\n else:\n reward = [max(min(r, 1), 0) for r in reward]\n\n return float(np.mean(reward))\n\n def _check_params(self) -> None:\n if not isinstance(self.batch_size_fit, int) or self.batch_size_fit <= 0:\n raise ValueError(\"The size of batches for fitting the thieved classifier must be a positive integer.\")\n\n if not isinstance(self.batch_size_query, int) or self.batch_size_query <= 0:\n raise ValueError(\"The size of batches for querying the victim classifier must be a positive integer.\")\n\n if not isinstance(self.nb_epochs, int) or self.nb_epochs <= 0:\n raise ValueError(\"The number of epochs must be a positive integer.\")\n\n if not isinstance(self.nb_stolen, int) or self.nb_stolen <= 0:\n raise ValueError(\"The number of queries submitted to the victim classifier must be a positive integer.\")\n\n if self.sampling_strategy not in [\"random\", \"adaptive\"]:\n raise ValueError(\"Sampling strategy must be either `random` or `adaptive`.\")\n\n if self.reward not in [\"cert\", \"div\", \"loss\", \"all\"]:\n raise ValueError(\"Reward type must be in ['cert', 'div', 'loss', 'all'].\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n if not isinstance(self.use_probability, bool):\n raise ValueError(\"The argument `use_probability` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing inference attacks.\n\"\"\"\n\nfrom art.attacks.inference import attribute_inference\nfrom art.attacks.inference import membership_inference\nfrom art.attacks.inference import model_inversion\nfrom art.attacks.inference import reconstruction\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing attribute inference attacks.\n\"\"\"\n\nfrom art.attacks.inference.attribute_inference.black_box import AttributeInferenceBlackBox\nfrom art.attacks.inference.attribute_inference.baseline import AttributeInferenceBaseline\nfrom art.attacks.inference.attribute_inference.true_label_baseline import AttributeInferenceBaselineTrueLabel\nfrom art.attacks.inference.attribute_inference.white_box_decision_tree import AttributeInferenceWhiteBoxDecisionTree\nfrom art.attacks.inference.attribute_inference.white_box_lifestyle_decision_tree import (\n AttributeInferenceWhiteBoxLifestyleDecisionTree,\n)\nfrom art.attacks.inference.attribute_inference.meminf_based import AttributeInferenceMembership\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/baseline.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attribute inference attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.svm import SVC, SVR\nfrom sklearn.preprocessing import OneHotEncoder, OrdinalEncoder\nfrom sklearn.compose import ColumnTransformer\n\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.regression import RegressorMixin\nfrom art.attacks.attack import AttributeInferenceAttack\nfrom art.utils import (\n check_and_transform_label_format,\n float_to_categorical,\n floats_to_one_hot,\n get_feature_values,\n remove_attacked_feature,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, REGRESSOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AttributeInferenceBaseline(AttributeInferenceAttack):\n \"\"\"\n Implementation of a baseline attribute inference, not using a model.\n\n The idea is to train a simple neural network to learn the attacked feature from the rest of the features. Should\n be used to compare with other attribute inference results.\n \"\"\"\n\n attack_params = AttributeInferenceAttack.attack_params + [\n \"attack_model_type\",\n \"is_continuous\",\n \"non_numerical_features\",\n \"encoder\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n attack_model_type: str = \"nn\",\n attack_model: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\" | None = None,\n attack_feature: int | slice = 0,\n is_continuous: bool | None = False,\n non_numerical_features: list[int] | None = None,\n encoder: OrdinalEncoder | OneHotEncoder | ColumnTransformer = None,\n nn_model_epochs: int = 100,\n nn_model_batch_size: int = 100,\n nn_model_learning_rate: float = 0.0001,\n ):\n \"\"\"\n Create an AttributeInferenceBaseline attack instance.\n\n :param attack_model_type: the type of default attack model to train, optional. Should be one of:\n `nn` (neural network, default),\n `rf` (random forest),\n `gb` (gradient boosting),\n `lr` (logistic/linear regression),\n `dt` (decision tree),\n `knn` (k nearest neighbors),\n `svm` (support vector machine).\n If `attack_model` is supplied, this option will be ignored.\n :param attack_model: The attack model to train, optional. If none is provided, a default model will be created.\n :param attack_feature: The index of the feature to be attacked or a slice representing multiple indexes in\n case of a one-hot encoded feature.\n :param is_continuous: Whether the attacked feature is continuous. Default is False (which means categorical).\n :param non_numerical_features: a list of feature indexes that require encoding in order to feed into an ML model\n (i.e., strings), not including the attacked feature. Should only be supplied if\n non-numeric features exist in the input data not including the attacked feature,\n and an encoder is not supplied.\n :param encoder: An already fit encoder that can be applied to the model's input features without the attacked\n feature (i.e., should be fit for n-1 features).\n :param nn_model_epochs: the number of epochs to use when training a nn attack model\n :param nn_model_batch_size: the batch size to use when training a nn attack model\n :param nn_model_learning_rate: the learning rate to use when training a nn attack model\n \"\"\"\n super().__init__(estimator=None, attack_feature=attack_feature)\n\n self._values: list = []\n self._encoder = encoder\n self._non_numerical_features = non_numerical_features\n self._is_continuous = is_continuous\n self._attack_model_type: str | None = attack_model_type\n self.attack_model: Any | None = None\n self.epochs = nn_model_epochs\n self.batch_size = nn_model_batch_size\n self.learning_rate = nn_model_learning_rate\n\n if attack_model:\n if self._is_continuous:\n if RegressorMixin not in type(attack_model).__mro__:\n raise ValueError(\"When attacking a continuous feature the attack model must be of type Regressor.\")\n elif ClassifierMixin not in type(attack_model).__mro__:\n raise ValueError(\"When attacking a categorical feature the attack model must be of type Classifier.\")\n self.attack_model = attack_model\n elif attack_model_type == \"rf\":\n if self._is_continuous:\n self.attack_model = RandomForestRegressor()\n else:\n self.attack_model = RandomForestClassifier()\n elif attack_model_type == \"gb\":\n if self._is_continuous:\n self.attack_model = GradientBoostingRegressor()\n else:\n self.attack_model = GradientBoostingClassifier()\n elif attack_model_type == \"lr\":\n if self._is_continuous:\n self.attack_model = LinearRegression()\n else:\n self.attack_model = LogisticRegression()\n elif attack_model_type == \"dt\":\n if self._is_continuous:\n self.attack_model = DecisionTreeRegressor()\n else:\n self.attack_model = DecisionTreeClassifier()\n elif attack_model_type == \"knn\":\n if self._is_continuous:\n self.attack_model = KNeighborsRegressor()\n else:\n self.attack_model = KNeighborsClassifier()\n elif attack_model_type == \"svm\":\n if self._is_continuous:\n self.attack_model = SVR()\n else:\n self.attack_model = SVC(probability=True)\n elif attack_model_type != \"nn\":\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n self._check_params()\n remove_attacked_feature(self.attack_feature, self._non_numerical_features)\n\n def fit(self, x: np.ndarray) -> None:\n \"\"\"\n Train the attack model.\n\n :param x: Input to training process. Includes all features used to train the original model.\n \"\"\"\n\n # Checks:\n if isinstance(self.attack_feature, int) and self.attack_feature >= x.shape[1]:\n raise ValueError(\"attack_feature must be a valid index to a feature in x\")\n\n # get vector of attacked feature\n y = x[:, self.attack_feature]\n y_ready = y\n if not self._is_continuous:\n self._values = get_feature_values(y, isinstance(self.attack_feature, int))\n # number of values in case of single column, number of columns in case of multi-column feature\n nb_classes = len(self._values)\n if isinstance(self.attack_feature, int):\n y_one_hot = float_to_categorical(y)\n else:\n y_one_hot = floats_to_one_hot(y)\n y_ready = check_and_transform_label_format(y_one_hot, nb_classes=nb_classes, return_one_hot=True)\n if y_ready is None:\n raise ValueError(\"None value detected.\")\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n y_ready = np.argmax(y_ready, axis=1)\n\n # create training set for attack model\n x_train = np.delete(x, self.attack_feature, 1)\n\n if self._non_numerical_features and self._encoder is None:\n if isinstance(self.attack_feature, int):\n compare_index = self.attack_feature\n size = 1\n else:\n compare_index = self.attack_feature.start\n size = (self.attack_feature.stop - self.attack_feature.start) // self.attack_feature.step\n new_indexes = [(f - size) if f > compare_index else f for f in self._non_numerical_features]\n categorical_transformer = OrdinalEncoder()\n self._encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, new_indexes),\n ],\n remainder=\"passthrough\",\n )\n self._encoder.fit(x_train)\n\n # train attack model\n if self._encoder is not None:\n x_train = self._encoder.transform(x_train)\n x_train = x_train.astype(np.float32)\n\n if self._attack_model_type == \"nn\":\n import torch\n from torch import nn\n from torch import optim\n from torch.utils.data import DataLoader\n from art.utils import to_cuda\n\n if self._is_continuous:\n\n class MembershipInferenceAttackModelRegression(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning a membership inference attack.\n\n The features used are probabilities/logits or losses for the attack training data along with\n its true labels.\n \"\"\"\n\n def __init__(self, num_features):\n\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, 1),\n )\n\n def forward(self, x):\n \"\"\"Forward the model.\"\"\"\n return self.features(x)\n\n self.attack_model = MembershipInferenceAttackModelRegression(x_train.shape[1])\n loss_fn: Any = nn.MSELoss()\n else:\n\n class MembershipInferenceAttackModel(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning an attribute inference attack.\n\n The features used are the remaining n-1 features of the attack training data along with\n the model's predictions.\n \"\"\"\n\n def __init__(self, num_features, num_classes):\n\n self.num_classes = num_classes\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 512),\n nn.ReLU(),\n nn.Linear(512, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, num_classes),\n )\n\n self.output = nn.Softmax()\n\n def forward(self, x):\n \"\"\"Forward the model.\"\"\"\n out = self.features(x)\n return self.output(out)\n\n self.attack_model = MembershipInferenceAttackModel(x_train.shape[1], len(self._values))\n loss_fn = nn.CrossEntropyLoss()\n\n optimizer = optim.Adam(self.attack_model.parameters(), lr=self.learning_rate) # type: ignore\n\n attack_train_set = self._get_attack_dataset(feature=x_train, label=y_ready)\n train_loader = DataLoader(attack_train_set, batch_size=self.batch_size, shuffle=True, num_workers=0)\n\n self.attack_model = to_cuda(self.attack_model) # type: ignore\n self.attack_model.train() # type: ignore\n\n for _ in range(self.epochs):\n for input1, targets in train_loader:\n input1, targets = to_cuda(input1), to_cuda(targets)\n _, targets = torch.autograd.Variable(input1), torch.autograd.Variable(targets)\n\n optimizer.zero_grad()\n outputs = self.attack_model(input1) # type: ignore\n loss = loss_fn(outputs, targets)\n loss.backward()\n optimizer.step()\n elif self.attack_model is not None:\n self.attack_model.fit(x_train, y_ready)\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer the attacked feature.\n\n :param x: Input to attack. Includes all features except the attacked feature.\n :param y: Not used in this attack.\n :param values: Possible values for attacked feature. For a single column feature this should be a simple list\n containing all possible values, in increasing order (the smallest value in the 0 index and so\n on). For a multi-column feature (for example 1-hot encoded and then scaled), this should be a\n list of lists, where each internal list represents a column (in increasing order) and the values\n represent the possible values for that column (in increasing order).\n :type values: list\n :return: The inferred feature values.\n \"\"\"\n values = kwargs.get(\"values\")\n\n # if provided, override the values computed in fit()\n if values is not None:\n self._values = values\n\n x_test = x\n if self._encoder is not None:\n x_test = self._encoder.transform(x)\n x_test = x_test.astype(np.float32)\n\n if self._attack_model_type == \"nn\":\n from torch.utils.data import DataLoader\n from art.utils import to_cuda, from_cuda\n\n self.attack_model.eval() # type: ignore\n predictions: np.ndarray = np.array([])\n test_set = self._get_attack_dataset(feature=x_test)\n test_loader = DataLoader(test_set, batch_size=self.batch_size, shuffle=False, num_workers=0)\n for input1, _ in test_loader:\n input1 = to_cuda(input1)\n outputs = self.attack_model(input1) # type: ignore\n predicted = from_cuda(outputs)\n\n if np.size(predictions) == 0:\n predictions = predicted.detach().numpy()\n else:\n predictions = np.vstack((predictions, predicted.detach().numpy()))\n if not self._is_continuous:\n idx = np.argmax(predictions, axis=-1)\n predictions = np.zeros(predictions.shape)\n predictions[np.arange(predictions.shape[0]), idx] = 1\n elif self.attack_model is not None:\n predictions = self.attack_model.predict(x_test)\n if predictions is not None:\n predictions = predictions.astype(np.float32)\n\n if not self._is_continuous and self._values:\n if isinstance(self.attack_feature, int):\n # replace 1-hot encoded prediction with correct single feature value\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n indexes = predictions\n else:\n indexes = np.argmax(predictions, axis=1)\n predictions = np.array([self._values[int(index)] for index in indexes])\n else:\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n predictions = check_and_transform_label_format(\n predictions, nb_classes=len(self._values), return_one_hot=True\n )\n i = 0\n # replace 1-hot encoded prediction with multi-column feature value\n for column in predictions.T:\n # possible values for ith column\n for index in range(len(self._values[i])):\n np.place(column, [column == index], self._values[i][index])\n i += 1\n return np.array(predictions)\n\n def _get_attack_dataset(self, feature, label=None):\n from torch.utils.data.dataset import Dataset\n\n class AttackDataset(Dataset):\n \"\"\"\n Implementation of a pytorch dataset for membership inference attack.\n\n The features are probabilities/logits or losses for the attack training data (`x_1`) along with\n its true labels (`x_2`). The labels (`y`) are a boolean representing whether this is a member.\n \"\"\"\n\n def __init__(self, x, y=None):\n import torch\n\n self.x = torch.from_numpy(x.astype(np.float64)).type(torch.FloatTensor)\n\n if y is not None:\n self.y = torch.from_numpy(y.astype(np.float32)).type(torch.FloatTensor)\n else:\n self.y = torch.zeros(x.shape[0])\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, idx):\n if idx >= len(self.x): # pragma: no cover\n raise IndexError(\"Invalid Index\")\n\n return self.x[idx], self.y[idx]\n\n return AttackDataset(x=feature, y=label)\n\n def _check_params(self) -> None:\n\n super()._check_params()\n\n if not isinstance(self._is_continuous, bool):\n raise ValueError(\"is_continuous must be a boolean.\")\n\n if self._attack_model_type not in [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"]:\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n if self._non_numerical_features and (\n (not isinstance(self._non_numerical_features, list))\n or (not all(isinstance(item, int) for item in self._non_numerical_features))\n ):\n raise ValueError(\"non_numerical_features must be a list of int.\")\n\n if self._encoder is not None and (\n not isinstance(self._encoder, OrdinalEncoder)\n and not isinstance(self._encoder, OneHotEncoder)\n and not isinstance(self._encoder, ColumnTransformer)\n ):\n raise ValueError(\"encoder must be a OneHotEncoder, OrdinalEncoder or ColumnTransformer object.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/black_box.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attribute inference attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.svm import SVC, SVR\nfrom sklearn.preprocessing import minmax_scale, OneHotEncoder, OrdinalEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\n\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.attack import AttributeInferenceAttack\nfrom art.estimators.regression import RegressorMixin\nfrom art.utils import (\n check_and_transform_label_format,\n float_to_categorical,\n floats_to_one_hot,\n get_feature_values,\n remove_attacked_feature,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, REGRESSOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AttributeInferenceBlackBox(AttributeInferenceAttack):\n \"\"\"\n Implementation of a simple black-box attribute inference attack.\n\n The idea is to train a simple neural network to learn the attacked feature from the rest of the features and the\n model's predictions. Assumes the availability of the attacked model's predictions for the samples under attack,\n in addition to the rest of the feature values. If this is not available, the true class label of the samples may be\n used as a proxy.\n \"\"\"\n\n attack_params = AttributeInferenceAttack.attack_params + [\n \"prediction_normal_factor\",\n \"scale_range\",\n \"attack_model_type\",\n \"is_continuous\",\n \"non_numerical_features\",\n \"encoder\",\n ]\n _estimator_requirements = (BaseEstimator, (ClassifierMixin, RegressorMixin))\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\",\n attack_model_type: str = \"nn\",\n attack_model: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\" | None = None,\n attack_feature: int | slice = 0,\n is_continuous: bool | None = False,\n scale_range: tuple[float, float] | None = None,\n prediction_normal_factor: float | None = 1,\n scaler_type: str | None = \"standard\",\n non_numerical_features: list[int] | None = None,\n encoder: OrdinalEncoder | OneHotEncoder | ColumnTransformer | None = None,\n nn_model_epochs: int = 100,\n nn_model_batch_size: int = 100,\n nn_model_learning_rate: float = 0.0001,\n ):\n \"\"\"\n Create an AttributeInferenceBlackBox attack instance.\n\n :param estimator: Target estimator.\n :param attack_model_type: the type of default attack model to train, optional. Should be one of:\n `nn` (neural network, default),\n `rf` (random forest),\n `gb` (gradient boosting),\n `lr` (logistic/linear regression),\n `dt` (decision tree),\n `knn` (k nearest neighbors),\n `svm` (support vector machine).\n If `attack_model` is supplied, this option will be ignored.\n :param attack_model: The attack model to train, optional. If the attacked feature is continuous, this should\n be a regression model, and if the attacked feature is categorical it should be a\n classifier.If none is provided, a default model will be created.\n :param attack_feature: The index of the feature to be attacked or a slice representing multiple indexes in\n case of a one-hot encoded feature.\n :param is_continuous: Whether the attacked feature is continuous. Default is False (which means categorical).\n :param scale_range: If supplied, the class labels (both true and predicted) will be scaled to the given range.\n Only applicable when `estimator` is a regressor.\n :param prediction_normal_factor: If supplied, the class labels (both true and predicted) are multiplied by the\n factor when used as inputs to the attack-model. Only applicable when\n `estimator` is a regressor and if `scale_range` is not supplied.\n :param scaler_type: The type of scaling to apply to all input features to the attack. Can be one of: \"standard\",\n \"minmax\", \"robust\" or None. If not None, the appropriate scaler from scikit-learn will be\n applied. If None, no scaling will be applied. This is in addition to any specific scaling\n performed on the class labels based on the params scale_range or prediction_normal_factor.\n :param non_numerical_features: a list of feature indexes that require encoding in order to feed into an ML model\n (i.e., strings), not including the attacked feature. Should only be supplied if\n non-numeric features exist in the input data not including the attacked feature,\n and an encoder is not supplied.\n :param encoder: An already fit encoder that can be applied to the model's input features without the attacked\n feature (i.e., should be fit for n-1 features).\n :param nn_model_epochs: the number of epochs to use when training a nn attack model\n :param nn_model_batch_size: the batch size to use when training a nn attack model\n :param nn_model_learning_rate: the learning rate to use when training a nn attack model\n \"\"\"\n super().__init__(estimator=estimator, attack_feature=attack_feature)\n\n self._values: list = []\n self._attack_model_type: str | None = attack_model_type\n self._encoder = encoder\n self._non_numerical_features = non_numerical_features\n self._is_continuous = is_continuous\n self.attack_model: Any | None = None\n self.prediction_normal_factor = prediction_normal_factor\n self.scale_range = scale_range\n self.scaler_type = scaler_type\n self.scaler: Any | None = None\n self.epochs = nn_model_epochs\n self.batch_size = nn_model_batch_size\n self.learning_rate = nn_model_learning_rate\n\n self._check_params()\n\n if attack_model:\n if self._is_continuous:\n if RegressorMixin not in type(attack_model).__mro__:\n raise ValueError(\"When attacking a continuous feature the attack model must be of type Regressor.\")\n elif ClassifierMixin not in type(attack_model).__mro__:\n raise ValueError(\"When attacking a categorical feature the attack model must be of type Classifier.\")\n self.attack_model = attack_model\n self._attack_model_type = None\n elif attack_model_type == \"rf\":\n if self._is_continuous:\n self.attack_model = RandomForestRegressor()\n else:\n self.attack_model = RandomForestClassifier()\n elif attack_model_type == \"gb\":\n if self._is_continuous:\n self.attack_model = GradientBoostingRegressor()\n else:\n self.attack_model = GradientBoostingClassifier()\n elif attack_model_type == \"lr\":\n if self._is_continuous:\n self.attack_model = LinearRegression()\n else:\n self.attack_model = LogisticRegression()\n elif attack_model_type == \"dt\":\n if self._is_continuous:\n self.attack_model = DecisionTreeRegressor()\n else:\n self.attack_model = DecisionTreeClassifier()\n elif attack_model_type == \"knn\":\n if self._is_continuous:\n self.attack_model = KNeighborsRegressor()\n else:\n self.attack_model = KNeighborsClassifier()\n elif attack_model_type == \"svm\":\n if self._is_continuous:\n self.attack_model = SVR()\n else:\n self.attack_model = SVC(probability=True)\n elif attack_model_type != \"nn\":\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n remove_attacked_feature(self.attack_feature, self._non_numerical_features)\n\n def fit(self, x: np.ndarray, y: np.ndarray | None = None) -> None:\n \"\"\"\n Train the attack model.\n\n :param x: Input to training process. Includes all features used to train the original model.\n :param y: True labels for x.\n \"\"\"\n\n # Checks:\n if self.estimator.input_shape is not None:\n if self.estimator.input_shape[0] != x.shape[1]:\n raise ValueError(\"Shape of x does not match input_shape of model\")\n if isinstance(self.attack_feature, int) and self.attack_feature >= x.shape[1]:\n raise ValueError(\"`attack_feature` must be a valid index to a feature in x\")\n\n # get model's predictions for x\n if ClassifierMixin in type(self.estimator).__mro__:\n predictions = np.array([np.argmax(arr) for arr in self.estimator.predict(x)]).reshape(-1, 1)\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=True)\n else: # Regression model\n if self.scale_range is not None:\n predictions = minmax_scale(self.estimator.predict(x).reshape(-1, 1), feature_range=self.scale_range)\n if y is not None:\n y = minmax_scale(y, feature_range=self.scale_range)\n else:\n predictions = self.estimator.predict(x).reshape(-1, 1) * self.prediction_normal_factor\n if y is not None:\n y = y * self.prediction_normal_factor\n if y is not None:\n y = y.reshape(-1, 1)\n\n # get vector of attacked feature\n y_attack = x[:, self.attack_feature]\n y_attack_ready = y_attack\n if not self._is_continuous:\n self._values = get_feature_values(y_attack, isinstance(self.attack_feature, int))\n nb_classes = len(self._values)\n if isinstance(self.attack_feature, int):\n y_one_hot = float_to_categorical(y_attack)\n else:\n y_one_hot = floats_to_one_hot(y_attack)\n y_attack_ready = check_and_transform_label_format(y_one_hot, nb_classes=nb_classes, return_one_hot=True)\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n y_attack_ready = np.argmax(y_attack_ready, axis=1)\n\n # create training set for attack model\n x_train = np.delete(x, self.attack_feature, 1)\n\n if self._non_numerical_features and self._encoder is None:\n if isinstance(self.attack_feature, int):\n compare_index = self.attack_feature\n size = 1\n else:\n compare_index = self.attack_feature.start\n size = (self.attack_feature.stop - self.attack_feature.start) // self.attack_feature.step\n new_indexes = [(f - size) if f > compare_index else f for f in self._non_numerical_features]\n categorical_transformer = OrdinalEncoder()\n self._encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, new_indexes),\n ],\n remainder=\"passthrough\",\n )\n self._encoder.fit(x_train)\n\n if self._encoder is not None:\n x_train = self._encoder.transform(x_train)\n x_train = np.concatenate((x_train, predictions), axis=1).astype(np.float32)\n\n if y is not None:\n x_train = np.concatenate((x_train, y), axis=1)\n\n if self.scaler_type:\n if self.scaler_type == \"standard\":\n self.scaler = StandardScaler()\n elif self.scaler_type == \"minmax\":\n self.scaler = MinMaxScaler()\n elif self.scaler_type == \"robust\":\n self.scaler = RobustScaler()\n else:\n raise ValueError(\"Illegal scaler_type: \", self.scaler_type)\n if self.scaler:\n self.scaler.fit(x_train)\n x_train = self.scaler.transform(x_train)\n\n # train attack model\n if self._attack_model_type == \"nn\":\n import torch\n from torch import nn\n from torch import optim\n from torch.utils.data import DataLoader\n from art.utils import to_cuda\n\n if self._is_continuous:\n\n class MembershipInferenceAttackModelRegression(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning a membership inference attack.\n\n The features used are probabilities/logits or losses for the attack training data along with\n its true labels.\n \"\"\"\n\n def __init__(self, num_features):\n\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, 1),\n )\n\n def forward(self, x):\n \"\"\"Forward the model.\"\"\"\n return self.features(x)\n\n self.attack_model = MembershipInferenceAttackModelRegression(x_train.shape[1])\n loss_fn: Any = nn.MSELoss()\n else:\n\n class MembershipInferenceAttackModel(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning an attribute inference attack.\n\n The features used are the remaining n-1 features of the attack training data along with\n the model's predictions.\n \"\"\"\n\n def __init__(self, num_features, num_classes):\n\n self.num_classes = num_classes\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 512),\n nn.ReLU(),\n nn.Linear(512, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, num_classes),\n )\n\n self.output = nn.Softmax()\n\n def forward(self, x):\n \"\"\"Forward the model.\"\"\"\n out = self.features(x)\n return self.output(out)\n\n self.attack_model = MembershipInferenceAttackModel(x_train.shape[1], len(self._values))\n loss_fn = nn.CrossEntropyLoss()\n\n optimizer = optim.Adam(self.attack_model.parameters(), lr=self.learning_rate) # type: ignore\n\n attack_train_set = self._get_attack_dataset(feature=x_train, label=y_attack_ready)\n train_loader = DataLoader(attack_train_set, batch_size=self.batch_size, shuffle=True, num_workers=0)\n\n self.attack_model = to_cuda(self.attack_model) # type: ignore\n self.attack_model.train() # type: ignore\n\n for _ in range(self.epochs):\n for input1, targets in train_loader:\n input1, targets = to_cuda(input1), to_cuda(targets)\n _, targets = torch.autograd.Variable(input1), torch.autograd.Variable(targets)\n\n optimizer.zero_grad()\n outputs = self.attack_model(input1) # type: ignore\n loss = loss_fn(outputs, targets)\n loss.backward()\n optimizer.step()\n elif self.attack_model is not None:\n self.attack_model.fit(x_train, y_attack_ready)\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer the attacked feature.\n\n :param x: Input to attack. Includes all features except the attacked feature.\n :param y: True labels for x.\n :param pred: Original model's predictions for x.\n :type pred: `np.ndarray`\n :param values: Possible values for attacked feature. For a single column feature this should be a simple list\n containing all possible values, in increasing order (the smallest value in the 0 index and so\n on). For a multi-column feature (for example 1-hot encoded and then scaled), this should be a\n list of lists, where each internal list represents a column (in increasing order) and the values\n represent the possible values for that column (in increasing order). If not provided, is\n computed from the training data when calling `fit`. Only relevant for categorical features.\n :type values: list, optional\n :return: The inferred feature values.\n \"\"\"\n values: list | None = kwargs.get(\"values\")\n\n # if provided, override the values computed in fit()\n if values is not None:\n self._values = values\n\n pred: np.ndarray | None = kwargs.get(\"pred\")\n\n if pred is None:\n raise ValueError(\"Please provide param `pred` of model predictions.\")\n\n if pred.shape[0] != x.shape[0]:\n raise ValueError(\"Number of rows in x and y do not match\")\n if self.estimator.input_shape is not None:\n if isinstance(self.attack_feature, int) and self.estimator.input_shape[0] != x.shape[1] + 1:\n raise ValueError(\"Number of features in x + 1 does not match input_shape of model\")\n\n x_test = x\n if self._encoder is not None:\n x_test = self._encoder.transform(x)\n\n if RegressorMixin in type(self.estimator).__mro__:\n if self.scale_range is not None:\n x_test = np.concatenate((x_test, minmax_scale(pred, feature_range=self.scale_range)), axis=1).astype(\n np.float32\n )\n if y is not None:\n y = minmax_scale(y, feature_range=self.scale_range)\n else:\n x_test = np.concatenate((x_test, pred * self.prediction_normal_factor), axis=1).astype(np.float32)\n if y is not None:\n y = y * self.prediction_normal_factor\n if y is not None:\n y = y.reshape(-1, 1)\n else:\n x_test = np.concatenate((x_test, pred), axis=1).astype(np.float32)\n if y is not None:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=True)\n\n if y is not None:\n x_test = np.concatenate((x_test, y), axis=1)\n\n if self.scaler:\n x_test = self.scaler.transform(x_test)\n\n if self._attack_model_type == \"nn\":\n from torch.utils.data import DataLoader\n from art.utils import to_cuda, from_cuda\n\n self.attack_model.eval() # type: ignore\n predictions: np.ndarray = np.array([])\n test_set = self._get_attack_dataset(feature=x_test)\n test_loader = DataLoader(test_set, batch_size=self.batch_size, shuffle=False, num_workers=0)\n for input1, _ in test_loader:\n input1 = to_cuda(input1)\n outputs = self.attack_model(input1) # type: ignore\n predicted = from_cuda(outputs)\n\n if np.size(predictions) == 0:\n predictions = predicted.detach().numpy()\n else:\n predictions = np.vstack((predictions, predicted.detach().numpy()))\n if not self._is_continuous:\n idx = np.argmax(predictions, axis=-1)\n predictions = np.zeros(predictions.shape)\n predictions[np.arange(predictions.shape[0]), idx] = 1\n elif self.attack_model is not None:\n predictions = self.attack_model.predict(x_test)\n if predictions is not None:\n predictions = predictions.astype(np.float32)\n\n if not self._is_continuous and self._values:\n if isinstance(self.attack_feature, int):\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n indexes = predictions\n else:\n indexes = np.argmax(predictions, axis=1)\n predictions = np.array([self._values[int(index)] for index in indexes])\n else:\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n predictions = check_and_transform_label_format(\n predictions, nb_classes=len(self._values), return_one_hot=True\n )\n i = 0\n for column in predictions.T:\n for index in range(len(self._values[i])):\n np.place(column, [column == index], self._values[i][index])\n i += 1\n return np.array(predictions)\n\n def _get_attack_dataset(self, feature, label=None):\n from torch.utils.data.dataset import Dataset\n\n class AttackDataset(Dataset):\n \"\"\"\n Implementation of a pytorch dataset for membership inference attack.\n\n The features are probabilities/logits or losses for the attack training data (`x_1`) along with\n its true labels (`x_2`). The labels (`y`) are a boolean representing whether this is a member.\n \"\"\"\n\n def __init__(self, x, y=None):\n import torch\n\n self.x = torch.from_numpy(x.astype(np.float64)).type(torch.FloatTensor)\n\n if y is not None:\n self.y = torch.from_numpy(y.astype(np.float32)).type(torch.FloatTensor)\n else:\n self.y = torch.zeros(x.shape[0])\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, idx):\n if idx >= len(self.x): # pragma: no cover\n raise IndexError(\"Invalid Index\")\n\n return self.x[idx], self.y[idx]\n\n return AttackDataset(x=feature, y=label)\n\n def _check_params(self) -> None:\n\n super()._check_params()\n\n if not isinstance(self._is_continuous, bool):\n raise ValueError(\"is_continuous must be a boolean.\")\n\n if self._attack_model_type not in [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"]:\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n if RegressorMixin not in type(self.estimator).__mro__:\n if self.prediction_normal_factor != 1:\n raise ValueError(\"Prediction normal factor is only applicable to regressor models.\")\n\n if self._non_numerical_features and (\n (not isinstance(self._non_numerical_features, list))\n or (not all(isinstance(item, int) for item in self._non_numerical_features))\n ):\n raise ValueError(\"non_numerical_features must be a list of int.\")\n\n if self._encoder is not None and (\n not isinstance(self._encoder, OrdinalEncoder)\n and not isinstance(self._encoder, OneHotEncoder)\n and not isinstance(self._encoder, ColumnTransformer)\n ):\n raise ValueError(\"encoder must be a OneHotEncoder, OrdinalEncoder or ColumnTransformer object.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/meminf_based.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attribute inference attacks using membership inference attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.attack import AttributeInferenceAttack, MembershipInferenceAttack\nfrom art.estimators.regression import RegressorMixin\nfrom art.exceptions import EstimatorError\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, REGRESSOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AttributeInferenceMembership(AttributeInferenceAttack):\n \"\"\"\n Implementation of an attribute inference attack that utilizes a membership inference attack.\n\n The idea is to find the target feature value that causes the membership inference attack to classify the sample\n as a member with the highest confidence.\n \"\"\"\n\n _estimator_requirements = (BaseEstimator, (ClassifierMixin, RegressorMixin))\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\",\n membership_attack: MembershipInferenceAttack,\n attack_feature: int | slice = 0,\n ):\n \"\"\"\n Create an AttributeInferenceMembership attack instance.\n\n :param estimator: Target estimator.\n :param membership_attack: The membership inference attack to use. Should be fit/calibrated in advance, and\n should support returning probabilities. Should also support the target estimator.\n :param attack_feature: The index of the feature to be attacked or a slice representing multiple indexes in\n case of a one-hot encoded feature.\n \"\"\"\n super().__init__(estimator=estimator, attack_feature=attack_feature)\n if not membership_attack.is_estimator_valid(estimator, estimator_requirements=self.estimator_requirements):\n raise EstimatorError(membership_attack.__class__, membership_attack.estimator_requirements, estimator)\n\n self.membership_attack = membership_attack\n self._check_params()\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer the attacked feature.\n\n :param x: Input to attack. Includes all features except the attacked feature.\n :param y: The labels expected by the membership attack.\n :param values: Possible values for attacked feature. For a single column feature this should be a simple list\n containing all possible values, in increasing order (the smallest value in the 0 index and so\n on). For a multi-column feature (for example 1-hot encoded and then scaled), this should be a\n list of lists, where each internal list represents a column (in increasing order) and the values\n represent the possible values for that column (in increasing order).\n :type values: list\n :return: The inferred feature values.\n \"\"\"\n if self.estimator.input_shape is not None:\n if isinstance(self.attack_feature, int) and self.estimator.input_shape[0] != x.shape[1] + 1:\n raise ValueError(\"Number of features in x + 1 does not match input_shape of the estimator\")\n\n if \"values\" not in kwargs:\n raise ValueError(\"Missing parameter `values`.\")\n values: list | None = kwargs.get(\"values\")\n if not values:\n raise ValueError(\"`values` cannot be None or empty\")\n\n if y is not None:\n if y.shape[0] != x.shape[0]:\n raise ValueError(\"Number of rows in x and y do not match\")\n\n # single index\n if isinstance(self.attack_feature, int):\n first = True\n for value in values:\n v_full = np.full((x.shape[0], 1), value).astype(x.dtype)\n x_value = np.concatenate((x[:, : self.attack_feature], v_full), axis=1)\n x_value = np.concatenate((x_value, x[:, self.attack_feature :]), axis=1)\n predicted = self.membership_attack.infer(x_value, y, probabilities=True)\n if first:\n probabilities = predicted\n first = False\n else:\n probabilities = np.hstack((probabilities, predicted))\n\n # needs to be of type float, so that we can later replace back the actual values\n value_indexes = np.argmax(probabilities, axis=1).astype(x.dtype)\n pred_values = np.zeros_like(value_indexes)\n for index, value in enumerate(values):\n pred_values[value_indexes == index] = value\n else: # 1-hot encoded feature. Can also be scaled.\n first = True\n # assumes that the second value is the \"positive\" value and that there can only be one positive column\n for index, value in enumerate(values):\n curr_value = np.zeros((x.shape[0], len(values)))\n curr_value[:, index] = value[1]\n for not_index, not_value in enumerate(values):\n if not_index != index:\n curr_value[:, not_index] = not_value[0]\n x_value = np.concatenate((x[:, : self.attack_feature.start], curr_value), axis=1)\n x_value = np.concatenate((x_value, x[:, self.attack_feature.start :]), axis=1)\n\n predicted = self.membership_attack.infer(x_value, y, probabilities=True)\n if first:\n probabilities = predicted\n else:\n probabilities = np.hstack((probabilities, predicted))\n first = False\n value_indexes = np.argmax(probabilities, axis=1).astype(x.dtype)\n pred_values = np.zeros_like(probabilities)\n for index, value in enumerate(values):\n curr_value = np.zeros(len(values))\n curr_value[index] = value[1]\n for not_index, not_value in enumerate(values):\n if not_index != index:\n curr_value[not_index] = not_value[0]\n pred_values[value_indexes == index] = curr_value\n return pred_values\n\n def _check_params(self) -> None:\n super()._check_params()\n\n if not isinstance(self.membership_attack, MembershipInferenceAttack):\n raise ValueError(\"membership_attack should be a sub-class of MembershipInferenceAttack\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/true_label_baseline.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attribute inference attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.svm import SVC, SVR\nfrom sklearn.preprocessing import minmax_scale, OneHotEncoder, OrdinalEncoder\nfrom sklearn.compose import ColumnTransformer\n\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.regression import RegressorMixin\nfrom art.attacks.attack import AttributeInferenceAttack\nfrom art.utils import (\n check_and_transform_label_format,\n float_to_categorical,\n floats_to_one_hot,\n get_feature_values,\n remove_attacked_feature,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, REGRESSOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AttributeInferenceBaselineTrueLabel(AttributeInferenceAttack):\n \"\"\"\n Implementation of a baseline attribute inference, not using a model.\n\n The idea is to train a simple neural network to learn the attacked feature from the rest of the features, and the\n true label. Should be used to compare with other attribute inference results.\n \"\"\"\n\n attack_params = AttributeInferenceAttack.attack_params + [\n \"prediction_normal_factor\",\n \"scale_range\",\n \"attack_model_type\",\n \"is_continuous\",\n \"is_regression\",\n \"non_numerical_features\",\n \"encoder\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n attack_model_type: str = \"nn\",\n attack_model: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\" | None = None,\n attack_feature: int | slice = 0,\n is_continuous: bool | None = False,\n is_regression: bool | None = False,\n scale_range: tuple[float, float] | None = None,\n prediction_normal_factor: float = 1,\n non_numerical_features: list[int] | None = None,\n encoder: OrdinalEncoder | OneHotEncoder | ColumnTransformer | None = None,\n nn_model_epochs: int = 100,\n nn_model_batch_size: int = 100,\n nn_model_learning_rate: float = 0.0001,\n ):\n \"\"\"\n Create an AttributeInferenceBaseline attack instance.\n\n :param attack_model_type: the type of default attack model to train, optional. Should be one of:\n `nn` (neural network, default),\n `rf` (random forest),\n `gb` (gradient boosting),\n `lr` (logistic/linear regression),\n `dt` (decision tree),\n `knn` (k nearest neighbors),\n `svm` (support vector machine).\n If `attack_model` is supplied, this option will be ignored.\n :param attack_model: The attack model to train, optional. If none is provided, a default model will be created.\n :param attack_feature: The index of the feature to be attacked or a slice representing multiple indexes in\n case of a one-hot encoded feature.\n :param is_continuous: Whether the attacked feature is continuous. Default is False (which means categorical).\n :param is_regression: Whether the model is a regression model. Default is False (classification).\n :param scale_range: If supplied, the class labels (both true and predicted) will be scaled to the given range.\n Only applicable when `is_regression` is True.\n :param prediction_normal_factor: If supplied, the class labels (both true and predicted) are multiplied by the\n factor when used as inputs to the attack-model. Only applicable when\n `is_regression` is True and if `scale_range` is not supplied.\n :param non_numerical_features: a list of feature indexes that require encoding in order to feed into an ML model\n (i.e., strings), not including the attacked feature. Should only be supplied if\n non-numeric features exist in the input data not including the attacked feature,\n and an encoder is not supplied.\n :param encoder: An already fit encoder that can be applied to the model's input features without the attacked\n feature (i.e., should be fit for n-1 features).\n :param nn_model_epochs: the number of epochs to use when training a nn attack model\n :param nn_model_batch_size: the batch size to use when training a nn attack model\n :param nn_model_learning_rate: the learning rate to use when training a nn attack model\n \"\"\"\n super().__init__(estimator=None, attack_feature=attack_feature)\n\n self._values: list = []\n self._encoder = encoder\n self._non_numerical_features = non_numerical_features\n self._is_continuous = is_continuous\n self._attack_model_type: str | None = attack_model_type\n self.attack_model: Any | None = None\n self.epochs = nn_model_epochs\n self.batch_size = nn_model_batch_size\n self.learning_rate = nn_model_learning_rate\n\n if attack_model:\n if self._is_continuous:\n if RegressorMixin not in type(attack_model).__mro__:\n raise ValueError(\"When attacking a continuous feature the attack model must be of type Regressor.\")\n elif ClassifierMixin not in type(attack_model).__mro__:\n raise ValueError(\"When attacking a categorical feature the attack model must be of type Classifier.\")\n self.attack_model = attack_model\n elif attack_model_type == \"rf\":\n if self._is_continuous:\n self.attack_model = RandomForestRegressor()\n else:\n self.attack_model = RandomForestClassifier()\n elif attack_model_type == \"gb\":\n if self._is_continuous:\n self.attack_model = GradientBoostingRegressor()\n else:\n self.attack_model = GradientBoostingClassifier()\n elif attack_model_type == \"lr\":\n if self._is_continuous:\n self.attack_model = LinearRegression()\n else:\n self.attack_model = LogisticRegression()\n elif attack_model_type == \"dt\":\n if self._is_continuous:\n self.attack_model = DecisionTreeRegressor()\n else:\n self.attack_model = DecisionTreeClassifier()\n elif attack_model_type == \"knn\":\n if self._is_continuous:\n self.attack_model = KNeighborsRegressor()\n else:\n self.attack_model = KNeighborsClassifier()\n elif attack_model_type == \"svm\":\n if self._is_continuous:\n self.attack_model = SVR()\n else:\n self.attack_model = SVC(probability=True)\n elif attack_model_type != \"nn\":\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n self.prediction_normal_factor = prediction_normal_factor\n self.scale_range = scale_range\n self.is_regression = is_regression\n self._check_params()\n remove_attacked_feature(self.attack_feature, self._non_numerical_features)\n\n def fit(self, x: np.ndarray, y: np.ndarray) -> None:\n \"\"\"\n Train the attack model.\n\n :param x: Input to training process. Includes all features used to train the original model.\n :param y: True labels of the features.\n \"\"\"\n\n # Checks:\n if isinstance(self.attack_feature, int) and self.attack_feature >= x.shape[1]:\n raise ValueError(\"attack_feature must be a valid index to a feature in x\")\n\n # get vector of attacked feature\n attacked_feature = x[:, self.attack_feature]\n y_ready = attacked_feature\n if not self._is_continuous:\n self._values = get_feature_values(attacked_feature, isinstance(self.attack_feature, int))\n nb_classes = len(self._values)\n if isinstance(self.attack_feature, int):\n y_one_hot = float_to_categorical(attacked_feature)\n else:\n y_one_hot = floats_to_one_hot(attacked_feature)\n y_ready = check_and_transform_label_format(y_one_hot, nb_classes=nb_classes, return_one_hot=True)\n if y_ready is None:\n raise ValueError(\"None value detected.\")\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n y_ready = np.argmax(y_ready, axis=1)\n\n # create training set for attack model\n if self.is_regression:\n if self.scale_range is not None:\n normalized_labels = minmax_scale(y, feature_range=self.scale_range)\n else:\n normalized_labels = y * self.prediction_normal_factor\n normalized_labels = normalized_labels.reshape(-1, 1)\n else:\n normalized_labels = check_and_transform_label_format(y, nb_classes=None, return_one_hot=True)\n\n x_train = np.delete(x, self.attack_feature, 1)\n\n if self._non_numerical_features and self._encoder is None:\n if isinstance(self.attack_feature, int):\n compare_index = self.attack_feature\n size = 1\n else:\n compare_index = self.attack_feature.start\n size = (self.attack_feature.stop - self.attack_feature.start) // self.attack_feature.step\n new_indexes = [(f - size) if f > compare_index else f for f in self._non_numerical_features]\n categorical_transformer = OrdinalEncoder()\n self._encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, new_indexes),\n ],\n remainder=\"passthrough\",\n )\n self._encoder.fit(x_train)\n\n # train attack model\n if self._encoder is not None:\n x_train = self._encoder.transform(x_train)\n x_train = np.concatenate((x_train, normalized_labels), axis=1).astype(np.float32)\n\n if self._attack_model_type == \"nn\":\n import torch\n from torch import nn\n from torch import optim\n from torch.utils.data import DataLoader\n from art.utils import to_cuda\n\n self.epochs = 100\n self.batch_size = 100\n self.learning_rate = 0.0001\n\n if self._is_continuous:\n\n class MembershipInferenceAttackModelRegression(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning a membership inference attack.\n\n The features used are probabilities/logits or losses for the attack training data along with\n its true labels.\n \"\"\"\n\n def __init__(self, num_features):\n\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, 1),\n )\n\n def forward(self, x):\n \"\"\"Forward the model.\"\"\"\n return self.features(x)\n\n self.attack_model = MembershipInferenceAttackModelRegression(x_train.shape[1])\n loss_fn: Any = nn.MSELoss()\n else:\n\n class MembershipInferenceAttackModel(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning an attribute inference attack.\n\n The features used are the remaining n-1 features of the attack training data along with\n the model's predictions.\n \"\"\"\n\n def __init__(self, num_features, num_classes):\n\n self.num_classes = num_classes\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 512),\n nn.ReLU(),\n nn.Linear(512, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, num_classes),\n )\n\n self.output = nn.Softmax()\n\n def forward(self, x):\n \"\"\"Forward the model.\"\"\"\n out = self.features(x)\n return self.output(out)\n\n self.attack_model = MembershipInferenceAttackModel(x_train.shape[1], len(self._values))\n loss_fn = nn.CrossEntropyLoss()\n\n optimizer = optim.Adam(self.attack_model.parameters(), lr=self.learning_rate) # type: ignore\n\n attack_train_set = self._get_attack_dataset(feature=x_train, label=y_ready)\n train_loader = DataLoader(attack_train_set, batch_size=self.batch_size, shuffle=True, num_workers=0)\n\n self.attack_model = to_cuda(self.attack_model) # type: ignore\n self.attack_model.train() # type: ignore\n\n for _ in range(self.epochs):\n for input1, targets in train_loader:\n input1, targets = to_cuda(input1), to_cuda(targets)\n _, targets = torch.autograd.Variable(input1), torch.autograd.Variable(targets)\n\n optimizer.zero_grad()\n outputs = self.attack_model(input1) # type: ignore\n loss = loss_fn(outputs, targets)\n loss.backward()\n optimizer.step()\n elif self.attack_model is not None:\n self.attack_model.fit(x_train, y_ready)\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer the attacked feature.\n\n :param x: Input to attack. Includes all features except the attacked feature.\n :param y: True labels of the features.\n :param values: Possible values for attacked feature. For a single column feature this should be a simple list\n containing all possible values, in increasing order (the smallest value in the 0 index and so\n on). For a multi-column feature (for example 1-hot encoded and then scaled), this should be a\n list of lists, where each internal list represents a column (in increasing order) and the values\n represent the possible values for that column (in increasing order).\n :type values: list\n :return: The inferred feature values.\n \"\"\"\n if y is None:\n raise ValueError(\"True labels are required\")\n\n values = kwargs.get(\"values\")\n\n # if provided, override the values computed in fit()\n if values is not None:\n self._values = values\n\n if self.is_regression:\n if self.scale_range is not None:\n normalized_labels = minmax_scale(y, feature_range=self.scale_range)\n else:\n normalized_labels = y * self.prediction_normal_factor\n normalized_labels = normalized_labels.reshape(-1, 1)\n else:\n normalized_labels = check_and_transform_label_format(y, nb_classes=None, return_one_hot=True)\n\n x_test = x\n if self._encoder is not None:\n x_test = self._encoder.transform(x)\n x_test = np.concatenate((x_test, normalized_labels), axis=1).astype(np.float32)\n\n if self._attack_model_type == \"nn\":\n from torch.utils.data import DataLoader\n from art.utils import to_cuda, from_cuda\n\n self.attack_model.eval() # type: ignore\n predictions: np.ndarray = np.array([])\n test_set = self._get_attack_dataset(feature=x_test)\n test_loader = DataLoader(test_set, batch_size=self.batch_size, shuffle=False, num_workers=0)\n for input1, _ in test_loader:\n input1 = to_cuda(input1)\n outputs = self.attack_model(input1) # type: ignore\n predicted = from_cuda(outputs)\n\n if np.size(predictions) == 0:\n predictions = predicted.detach().numpy()\n else:\n predictions = np.vstack((predictions, predicted.detach().numpy()))\n if not self._is_continuous:\n idx = np.argmax(predictions, axis=-1)\n predictions = np.zeros(predictions.shape)\n predictions[np.arange(predictions.shape[0]), idx] = 1\n elif self.attack_model is not None:\n predictions = self.attack_model.predict(x_test)\n if predictions is not None:\n predictions = predictions.astype(np.float32)\n\n if not self._is_continuous and self._values:\n if isinstance(self.attack_feature, int):\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n indexes = predictions\n else:\n indexes = np.argmax(predictions, axis=1)\n predictions = np.array([self._values[int(index)] for index in indexes])\n else:\n if self._attack_model_type in (\"gb\", \"lr\", \"svm\"):\n predictions = check_and_transform_label_format(\n predictions, nb_classes=len(self._values), return_one_hot=True\n )\n i = 0\n for column in predictions.T:\n for index in range(len(self._values[i])):\n np.place(column, [column == index], self._values[i][index])\n i += 1\n return np.array(predictions)\n\n def _get_attack_dataset(self, feature, label=None):\n from torch.utils.data.dataset import Dataset\n\n class AttackDataset(Dataset):\n \"\"\"\n Implementation of a pytorch dataset for membership inference attack.\n\n The features are probabilities/logits or losses for the attack training data (`x_1`) along with\n its true labels (`x_2`). The labels (`y`) are a boolean representing whether this is a member.\n \"\"\"\n\n def __init__(self, x, y=None):\n import torch\n\n self.x = torch.from_numpy(x.astype(np.float64)).type(torch.FloatTensor)\n\n if y is not None:\n self.y = torch.from_numpy(y.astype(np.float32)).type(torch.FloatTensor)\n else:\n self.y = torch.zeros(x.shape[0])\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, idx):\n if idx >= len(self.x): # pragma: no cover\n raise IndexError(\"Invalid Index\")\n\n return self.x[idx], self.y[idx]\n\n return AttackDataset(x=feature, y=label)\n\n def _check_params(self) -> None:\n super()._check_params()\n\n if not isinstance(self._is_continuous, bool):\n raise ValueError(\"is_continuous must be a boolean.\")\n\n if self._attack_model_type not in [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"]:\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n if self._non_numerical_features and (\n (not isinstance(self._non_numerical_features, list))\n or (not all(isinstance(item, int) for item in self._non_numerical_features))\n ):\n raise ValueError(\"non_numerical_features must be a list of int.\")\n\n if self._encoder is not None and (\n not isinstance(self._encoder, OrdinalEncoder)\n and not isinstance(self._encoder, OneHotEncoder)\n and not isinstance(self._encoder, ColumnTransformer)\n ):\n raise ValueError(\"encoder must be a OneHotEncoder, OrdinalEncoder or ColumnTransformer object.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/white_box_decision_tree.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attribute inference attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\n\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\nfrom art.attacks.attack import AttributeInferenceAttack\n\nlogger = logging.getLogger(__name__)\n\n\nclass AttributeInferenceWhiteBoxDecisionTree(AttributeInferenceAttack):\n \"\"\"\n A variation of the method proposed by of Fredrikson et al. in:\n https://dl.acm.org/doi/10.1145/2810103.2813677\n\n Assumes the availability of the attacked model's predictions for the samples under attack, in addition to access to\n the model itself and the rest of the feature values. If this is not available, the true class label of the samples\n may be used as a proxy. Also assumes that the attacked feature is discrete or categorical, with limited number of\n possible values. For example: a boolean feature.\n\n | Paper link: https://dl.acm.org/doi/10.1145/2810103.2813677\n \"\"\"\n\n _estimator_requirements = (ScikitlearnDecisionTreeClassifier,)\n\n def __init__(self, classifier: ScikitlearnDecisionTreeClassifier, attack_feature: int = 0):\n \"\"\"\n Create an AttributeInferenceWhiteBox attack instance.\n\n :param classifier: Target classifier.\n :param attack_feature: The index of the feature to be attacked.\n \"\"\"\n super().__init__(estimator=classifier, attack_feature=attack_feature)\n self.attack_feature: int\n self._check_params()\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer the attacked feature.\n\n If the model's prediction coincides with the real prediction for the sample for a single value, choose it as the\n predicted value. If not, fall back to the Fredrikson method (without phi)\n\n :param x: Input to attack. Includes all features except the attacked feature.\n :param y: Original model's predictions for x.\n :param values: Possible values for attacked feature.\n :type values: list\n :param priors: Prior distributions of attacked feature values. Same size array as `values`.\n :type priors: list\n :return: The inferred feature values.\n \"\"\"\n if \"priors\" not in kwargs: # pragma: no cover\n raise ValueError(\"Missing parameter `priors`.\")\n if \"values\" not in kwargs: # pragma: no cover\n raise ValueError(\"Missing parameter `values`.\")\n priors: list | None = kwargs.get(\"priors\")\n values: list | None = kwargs.get(\"values\")\n\n if self.estimator.input_shape[0] != x.shape[1] + 1: # pragma: no cover\n raise ValueError(\"Number of features in x + 1 does not match input_shape of classifier\")\n if priors is None or values is None: # pragma: no cover\n raise ValueError(\"`priors` and `values` are required as inputs.\")\n if len(priors) != len(values): # pragma: no cover\n raise ValueError(\"Number of priors does not match number of values\")\n if y is not None and y.shape[0] != x.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in x and y do not match\")\n if self.attack_feature >= x.shape[1]: # pragma: no cover\n raise ValueError(\"attack_feature must be a valid index to a feature in x\")\n\n n_values = len(values)\n n_samples = x.shape[0]\n\n # Will contain the model's predictions for each value\n pred_values = []\n # Will contain the probability of each value\n prob_values = []\n\n for i, value in enumerate(values):\n # prepare data with the given value in the attacked feature\n v_full = np.full((n_samples, 1), value).astype(x.dtype)\n x_value = np.concatenate((x[:, : self.attack_feature], v_full), axis=1)\n x_value = np.concatenate((x_value, x[:, self.attack_feature :]), axis=1)\n\n # Obtain the model's prediction for each possible value of the attacked feature\n pred_value = [np.argmax(arr) for arr in self.estimator.predict(x_value)]\n pred_values.append(pred_value)\n\n # find the relative probability of this value for all samples being attacked\n prob_value = [\n (\n (self.estimator.get_samples_at_node(self.estimator.get_decision_path([row])[-1]) / n_samples)\n * priors[i]\n )\n for row in x_value\n ]\n prob_values.append(prob_value)\n\n # Find the single value that coincides with the real prediction for the sample (if it exists)\n pred_rows = zip(*pred_values)\n predicted_pred = []\n for row_index, row in enumerate(pred_rows):\n if y is not None:\n matches = [1 if row[value_index] == y[row_index] else 0 for value_index in range(n_values)]\n match_values = [\n values[value_index] if row[value_index] == y[row_index] else 0 for value_index in range(n_values)\n ]\n else:\n matches = [0 for _ in range(n_values)]\n match_values = [0 for _ in range(n_values)]\n predicted_pred.append(sum(match_values) if sum(matches) == 1 else None)\n\n # Choose the value with the highest probability for each sample\n predicted_prob = [np.argmax(list(prob)) for prob in zip(*prob_values)]\n\n return np.array(\n [\n value if value is not None else values[predicted_prob[index]]\n for index, value in enumerate(predicted_pred)\n ]\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/attribute_inference/white_box_lifestyle_decision_tree.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements attribute inference attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import AttributeInferenceAttack\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\nfrom art.estimators.regression.scikitlearn import ScikitlearnDecisionTreeRegressor\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, REGRESSOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass AttributeInferenceWhiteBoxLifestyleDecisionTree(AttributeInferenceAttack):\n \"\"\"\n Implementation of Fredrikson et al. white box inference attack for decision trees.\n\n Assumes that the attacked feature is discrete or categorical, with limited number of possible values. For example:\n a boolean feature.\n\n | Paper link: https://dl.acm.org/doi/10.1145/2810103.2813677\n \"\"\"\n\n _estimator_requirements = ((ScikitlearnDecisionTreeClassifier, ScikitlearnDecisionTreeRegressor),)\n\n def __init__(self, estimator: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\", attack_feature: int = 0):\n \"\"\"\n Create an AttributeInferenceWhiteBoxLifestyle attack instance.\n\n :param estimator: Target estimator.\n :param attack_feature: The index of the feature to be attacked.\n \"\"\"\n super().__init__(estimator=estimator, attack_feature=attack_feature)\n self.attack_feature: int\n self._check_params()\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer the attacked feature.\n\n :param x: Input to attack. Includes all features except the attacked feature.\n :param y: Not used.\n :param values: Possible values for attacked feature.\n :type values: list\n :param priors: Prior distributions of attacked feature values. Same size array as `values`.\n :type priors: list\n :return: The inferred feature values.\n :rtype: `np.ndarray`\n \"\"\"\n priors: list | None = kwargs.get(\"priors\")\n values: list | None = kwargs.get(\"values\")\n\n # Checks:\n if self.estimator.input_shape[0] != x.shape[1] + 1: # pragma: no cover\n raise ValueError(\"Number of features in x + 1 does not match input_shape of classifier\")\n if priors is None or values is None: # pragma: no cover\n raise ValueError(\"`priors` and `values` are required as inputs.\")\n if len(priors) != len(values): # pragma: no cover\n raise ValueError(\"Number of priors does not match number of values\")\n if self.attack_feature >= x.shape[1]: # pragma: no cover\n raise ValueError(\"attack_feature must be a valid index to a feature in x\")\n\n n_samples = x.shape[0]\n\n # Calculate phi for each possible value of the attacked feature\n # phi is the total number of samples in all tree leaves corresponding to this value\n phi = self._calculate_phi(x, values, n_samples)\n\n # Will contain the probability of each value\n prob_values = []\n\n for i, value in enumerate(values):\n # prepare data with the given value in the attacked feature\n v_full = np.full((n_samples, 1), value).astype(x.dtype)\n x_value = np.concatenate((x[:, : self.attack_feature], v_full), axis=1)\n x_value = np.concatenate((x_value, x[:, self.attack_feature :]), axis=1)\n\n # find the relative probability of this value for all samples being attacked\n prob_value = [\n (\n (self.estimator.get_samples_at_node(self.estimator.get_decision_path([row])[-1]) / n_samples)\n * priors[i]\n / phi[i]\n )\n for row in x_value\n ]\n prob_values.append(prob_value)\n\n # Choose the value with the highest probability for each sample\n return np.array([values[np.argmax(list(prob))] for prob in zip(*prob_values)])\n\n def _calculate_phi(self, x, values, n_samples):\n phi = []\n for value in values:\n v_full = np.full((n_samples, 1), value).astype(x.dtype)\n x_value = np.concatenate((x[:, : self.attack_feature], v_full), axis=1)\n x_value = np.concatenate((x_value, x[:, self.attack_feature :]), axis=1)\n nodes_value = {}\n\n for row in x_value:\n # get leaf ids (no duplicates)\n node_id = self.estimator.get_decision_path([row])[-1]\n nodes_value[node_id] = self.estimator.get_samples_at_node(node_id)\n # sum sample numbers\n num_value = sum(nodes_value.values()) / n_samples\n phi.append(num_value)\n\n return phi\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/membership_inference/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing membership inference attacks.\n\"\"\"\n\nfrom art.attacks.inference.membership_inference.black_box import MembershipInferenceBlackBox\nfrom art.attacks.inference.membership_inference.black_box_rule_based import MembershipInferenceBlackBoxRuleBased\nfrom art.attacks.inference.membership_inference.label_only_gap_attack import LabelOnlyGapAttack\nfrom art.attacks.inference.membership_inference.label_only_boundary_distance import LabelOnlyDecisionBoundary\nfrom art.attacks.inference.membership_inference.shadow_models import ShadowModels\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/membership_inference/black_box.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nThis module implements membership inference attacks.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\n\nfrom art.attacks.attack import MembershipInferenceAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.regression import RegressorMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, REGRESSOR_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass MembershipInferenceBlackBox(MembershipInferenceAttack):\n \"\"\"\n Implementation of a learned black-box membership inference attack.\n\n This implementation can use as input to the learning process probabilities/logits or losses,\n depending on the type of model and provided configuration.\n \"\"\"\n\n attack_params = MembershipInferenceAttack.attack_params + [\n \"input_type\",\n \"attack_model_type\",\n \"attack_model\",\n \"scaler_type\",\n \"nn_model_epochs\",\n \"nn_model_batch_size\",\n \"nn_model_learning_rate\",\n ]\n _estimator_requirements = (BaseEstimator, (ClassifierMixin, RegressorMixin))\n\n def __init__(\n self,\n estimator: \"CLASSIFIER_TYPE\" | \"REGRESSOR_TYPE\",\n input_type: str = \"prediction\",\n attack_model_type: str = \"nn\",\n attack_model: Any | None = None,\n scaler_type: str | None = \"standard\",\n nn_model_epochs: int = 100,\n nn_model_batch_size: int = 100,\n nn_model_learning_rate: float = 0.0001,\n ):\n \"\"\"\n Create a MembershipInferenceBlackBox attack instance.\n\n :param estimator: Target estimator.\n :param input_type: the type of input to train the attack on. Can be one of: 'prediction' or 'loss'. Default is\n `prediction`. Predictions can be either probabilities or logits, depending on the return type\n of the model. If the model is a regressor, only `loss` can be used.\n :param attack_model_type: the type of default attack model to train, optional. Should be one of:\n `nn` (neural network, default),\n `rf` (random forest),\n `gb` (gradient boosting),\n `lr` (logistic regression),\n `dt` (decision tree),\n `knn` (k nearest neighbors),\n `svm` (support vector machine).\n If `attack_model` is supplied, this option will be ignored.\n :param attack_model: The attack model to train, optional. If none is provided, a default model will be created.\n :param scaler_type: The type of scaling to apply to the input features to the attack. Can be one of: \"standard\",\n \"minmax\", \"robust\" or None. If not None, the appropriate scaler from scikit-learn will be\n applied. If None, no scaling will be applied.\n :param nn_model_epochs: the number of epochs to use when training a nn attack model\n :param nn_model_batch_size: the batch size to use when training a nn attack model\n :param nn_model_learning_rate: the learning rate to use when training a nn attack model\n \"\"\"\n\n super().__init__(estimator=estimator)\n self.input_type = input_type\n self.attack_model_type = attack_model_type\n self.attack_model = attack_model\n self.scaler_type = scaler_type\n self.scaler: Any | None = None\n self.epochs = nn_model_epochs\n self.batch_size = nn_model_batch_size\n self.learning_rate = nn_model_learning_rate\n self.use_label = True\n\n self._regressor_model = RegressorMixin in type(self.estimator).__mro__\n\n self._check_params()\n\n if self.attack_model:\n self.default_model = False\n self.attack_model_type = \"None\"\n else:\n self.default_model = True\n\n if self.attack_model_type == \"rf\":\n self.attack_model = RandomForestClassifier()\n elif self.attack_model_type == \"gb\":\n self.attack_model = GradientBoostingClassifier()\n elif self.attack_model_type == \"lr\":\n self.attack_model = LogisticRegression()\n elif self.attack_model_type == \"dt\":\n self.attack_model = DecisionTreeClassifier()\n elif self.attack_model_type == \"knn\":\n self.attack_model = KNeighborsClassifier()\n elif self.attack_model_type == \"svm\":\n self.attack_model = SVC(probability=True)\n elif attack_model_type != \"nn\":\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n def fit(\n self,\n x: np.ndarray | None = None,\n y: np.ndarray | None = None,\n test_x: np.ndarray | None = None,\n test_y: np.ndarray | None = None,\n pred: np.ndarray | None = None,\n test_pred: np.ndarray | None = None,\n **kwargs,\n ):\n \"\"\"\n Train the attack model.\n\n :param x: Records that were used in training the target estimator. Can be None if supplying `pred`.\n :param y: True labels for `x`. If not supplied, attack will be based solely on model predictions.\n :param test_x: Records that were not used in training the target estimator. Can be None if supplying\n `test_pred`.\n :param test_y: True labels for `test_x`. If not supplied, attack will be based solely on model predictions.\n :param pred: Estimator predictions for the records, if not supplied will be generated by calling the estimators'\n `predict` function. Only relevant for input_type='prediction'.\n :param test_pred: Estimator predictions for the test records, if not supplied will be generated by calling the\n estimators' `predict` function. Only relevant for input_type='prediction'.\n :return: An array holding the inferred membership status, 1 indicates a member and 0 indicates non-member.\n \"\"\"\n if x is None and pred is None:\n raise ValueError(\"Must supply either x or pred\")\n if test_x is None and test_pred is None:\n raise ValueError(\"Must supply either test_x or test_pred\")\n\n if self.estimator.input_shape is not None:\n if x is not None and self.estimator.input_shape[0] != x.shape[1]: # pragma: no cover\n raise ValueError(\"Shape of x does not match input_shape of estimator\")\n if test_x is not None and self.estimator.input_shape[0] != test_x.shape[1]: # pragma: no cover\n raise ValueError(\"Shape of test_x does not match input_shape of estimator\")\n\n if y is not None and test_y is not None and not self._regressor_model:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=True)\n test_y = check_and_transform_label_format(test_y, nb_classes=self.estimator.nb_classes, return_one_hot=True)\n\n if x is not None and y is not None and y.shape[0] != x.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in x and y do not match\")\n if pred is not None and y is not None and y.shape[0] != pred.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in pred and y do not match\")\n if test_x is not None and test_y is not None and test_y.shape[0] != test_x.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in test_x and test_y do not match\")\n if test_pred is not None and test_y is not None and test_y.shape[0] != test_pred.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in test_pred and test_y do not match\")\n\n # Create attack dataset\n # uses final probabilities/logits\n x_len = 0\n test_len = 0\n if pred is None and x is not None:\n x_len = x.shape[0]\n elif pred is not None:\n x_len = pred.shape[0]\n if test_pred is None and test_x is not None:\n test_len = test_x.shape[0]\n elif test_pred is not None:\n test_len = test_pred.shape[0]\n\n if self.input_type == \"prediction\":\n # members\n if pred is None:\n features = self.estimator.predict(x).astype(np.float32)\n else:\n features = pred.astype(np.float32)\n # non-members\n if test_pred is None:\n test_features = self.estimator.predict(test_x).astype(np.float32)\n else:\n test_features = test_pred.astype(np.float32)\n # only for models with loss\n elif self.input_type == \"loss\":\n if y is None:\n raise ValueError(\"Cannot compute loss values without y.\")\n if x is not None:\n # members\n features = self.estimator.compute_loss(x, y).astype(np.float32).reshape(-1, 1)\n else:\n try:\n features = self.estimator.compute_loss_from_predictions(pred, y).astype(np.float32).reshape(-1, 1)\n except NotImplementedError as err:\n raise ValueError(\n \"For loss input type and no x, the estimator must implement 'compute_loss_from_predictions' \"\n \"method\"\n ) from err\n if test_x is not None:\n # non-members\n test_features = self.estimator.compute_loss(test_x, test_y).astype(np.float32).reshape(-1, 1)\n else:\n try:\n test_features = (\n self.estimator.compute_loss_from_predictions(test_pred, test_y)\n .astype(np.float32)\n .reshape(-1, 1)\n )\n except NotImplementedError as err:\n raise ValueError(\n \"For loss input type and no test_x, the estimator must implement \"\n \"'compute_loss_from_predictions' method\"\n ) from err\n else: # pragma: no cover\n raise ValueError(\"Illegal value for parameter `input_type`.\")\n\n # members\n labels = np.ones(x_len)\n # non-members\n test_labels = np.zeros(test_len)\n\n x_1 = np.concatenate((features, test_features))\n x_2: np.ndarray | None = None\n if y is not None and test_y is not None:\n x_2 = np.concatenate((y, test_y))\n if self._regressor_model and x_2 is not None:\n x_2 = x_2.astype(np.float32).reshape(-1, 1)\n y_new = np.concatenate((labels, test_labels))\n if x_2 is None:\n self.use_label = False\n\n if self.scaler_type:\n if self.scaler_type == \"standard\":\n self.scaler = StandardScaler()\n elif self.scaler_type == \"minmax\":\n self.scaler = MinMaxScaler()\n elif self.scaler_type == \"robust\":\n self.scaler = RobustScaler()\n else:\n raise ValueError(\"Illegal scaler_type: \", self.scaler_type)\n\n if self.default_model and self.attack_model_type == \"nn\":\n import torch\n from torch import nn\n from torch import optim\n from torch.utils.data import DataLoader\n from art.utils import to_cuda\n\n if self.scaler:\n self.scaler.fit(x_1)\n x_1 = self.scaler.transform(x_1)\n\n if x_2 is not None:\n\n class MembershipInferenceAttackModel(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning a membership inference attack.\n\n The features used are probabilities/logits or losses for the attack training data along with\n its true labels.\n \"\"\"\n\n def __init__(self, num_classes, num_features=None):\n\n self.num_classes = num_classes\n if num_features:\n self.num_features = num_features\n else:\n self.num_features = num_classes\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 512),\n nn.ReLU(),\n nn.Linear(512, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n )\n\n self.labels = nn.Sequential(\n nn.Linear(self.num_classes, 256),\n nn.ReLU(),\n nn.Linear(256, 64),\n nn.ReLU(),\n )\n\n self.combine = nn.Sequential(\n nn.Linear(64 * 2, 1),\n )\n\n self.output = nn.Sigmoid()\n\n def forward(self, x_1, label):\n \"\"\"Forward the model.\"\"\"\n out_x1 = self.features(x_1)\n out_l = self.labels(label)\n is_member = self.combine(torch.cat((out_x1, out_l), 1))\n return self.output(is_member)\n\n if self.input_type == \"prediction\":\n num_classes = self.estimator.nb_classes # type: ignore\n self.attack_model = MembershipInferenceAttackModel(num_classes)\n else: # loss\n if self._regressor_model:\n self.attack_model = MembershipInferenceAttackModel(1, num_features=1)\n else:\n num_classes = self.estimator.nb_classes # type: ignore\n self.attack_model = MembershipInferenceAttackModel(num_classes, num_features=1)\n\n loss_fn = nn.BCELoss()\n optimizer = optim.Adam(self.attack_model.parameters(), lr=self.learning_rate) # type: ignore\n\n attack_train_set = self._get_attack_dataset(f_1=x_1, f_2=x_2, label=y_new)\n train_loader = DataLoader(attack_train_set, batch_size=self.batch_size, shuffle=True, num_workers=0)\n\n self.attack_model = to_cuda(self.attack_model) # type: ignore\n self.attack_model.train() # type: ignore\n\n for _ in range(self.epochs):\n for input1, input2, targets in train_loader:\n input1, input2, targets = to_cuda(input1), to_cuda(input2), to_cuda(targets)\n _, input2 = torch.autograd.Variable(input1), torch.autograd.Variable(input2)\n targets = torch.autograd.Variable(targets)\n\n optimizer.zero_grad()\n outputs = self.attack_model(input1, input2) # type: ignore\n loss = loss_fn(outputs, targets.unsqueeze(1))\n\n loss.backward()\n optimizer.step()\n else: # no label\n\n class MembershipInferenceAttackModelNoLabel(nn.Module):\n \"\"\"\n Implementation of a pytorch model for learning a membership inference attack.\n\n The features used are probabilities/logits or losses for the attack training data along with\n its true labels.\n \"\"\"\n\n def __init__(self, num_features):\n\n self.num_features = num_features\n\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(self.num_features, 512),\n nn.ReLU(),\n nn.Linear(512, 100),\n nn.ReLU(),\n nn.Linear(100, 64),\n nn.ReLU(),\n nn.Linear(64, 1),\n )\n\n self.output = nn.Sigmoid()\n\n def forward(self, x_1):\n \"\"\"Forward the model.\"\"\"\n out_x1 = self.features(x_1)\n return self.output(out_x1)\n\n num_classes = self.estimator.nb_classes # type: ignore\n self.attack_model = MembershipInferenceAttackModelNoLabel(num_classes)\n\n loss_fn = nn.BCELoss()\n optimizer = optim.Adam(self.attack_model.parameters(), lr=self.learning_rate) # type: ignore\n\n attack_train_set = self._get_attack_dataset_no_label(f_1=x_1, label=y_new)\n train_loader = DataLoader(attack_train_set, batch_size=self.batch_size, shuffle=True, num_workers=0)\n\n self.attack_model = to_cuda(self.attack_model) # type: ignore\n self.attack_model.train() # type: ignore\n\n for _ in range(self.epochs):\n for input1, targets in train_loader:\n input1, targets = to_cuda(input1), to_cuda(targets)\n input1 = torch.autograd.Variable(input1)\n targets = torch.autograd.Variable(targets)\n\n optimizer.zero_grad()\n outputs = self.attack_model(input1) # type: ignore\n loss = loss_fn(outputs, targets.unsqueeze(1))\n\n loss.backward()\n optimizer.step()\n\n else: # not nn\n y_ready = check_and_transform_label_format(y_new, nb_classes=2, return_one_hot=False)\n if x_2 is not None:\n x = np.c_[x_1, x_2]\n if self.scaler:\n self.scaler.fit(x)\n x = self.scaler.transform(x)\n self.attack_model.fit(x, y_ready.ravel()) # type: ignore\n else:\n if self.scaler:\n self.scaler.fit(x_1)\n x_1 = self.scaler.transform(x_1)\n self.attack_model.fit(x_1, y_ready.ravel()) # type: ignore\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer membership in the training set of the target estimator.\n\n :param x: Input records to attack. Can be None if supplying `pred`.\n :param y: True labels for `x`. If not supplied, attack will be based solely on model predictions.\n :param pred: Estimator predictions for the records, if not supplied will be generated by calling the estimators'\n `predict` function. Only relevant for input_type='prediction'.\n :param probabilities: a boolean indicating whether to return the predicted probabilities per class, or just\n the predicted class.\n :return: An array holding the inferred membership status, 1 indicates a member and 0 indicates non-member,\n or class probabilities.\n \"\"\"\n if \"pred\" in kwargs:\n pred = kwargs.get(\"pred\")\n else:\n pred = None\n\n if \"probabilities\" in kwargs:\n probabilities = kwargs.get(\"probabilities\")\n else:\n probabilities = False\n\n if x is None and pred is None:\n raise ValueError(\"Must supply either x or pred\")\n\n if y is None and self.use_label:\n raise ValueError(\"y must be provided\")\n\n if self.estimator.input_shape is not None and x is not None: # pragma: no cover\n if self.estimator.input_shape[0] != x.shape[1]:\n raise ValueError(\"Shape of x does not match input_shape of estimator\")\n\n if y is not None and not self._regressor_model:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes, return_one_hot=True)\n\n if x is not None and y is not None and y.shape[0] != x.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in x and y do not match\")\n if pred is not None and y is not None and y.shape[0] != pred.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in pred and y do not match\")\n\n if self.input_type == \"prediction\":\n if pred is None:\n features = self.estimator.predict(x).astype(np.float32)\n else:\n features = pred.astype(np.float32)\n elif self.input_type == \"loss\":\n if y is None:\n raise ValueError(\"Cannot compute loss values without y.\")\n if x is not None:\n features = self.estimator.compute_loss(x, y).astype(np.float32).reshape(-1, 1)\n else:\n try:\n features = self.estimator.compute_loss_from_predictions(pred, y).astype(np.float32).reshape(-1, 1)\n except NotImplementedError as err:\n raise ValueError(\n \"For loss input type and no x, the estimator must implement 'compute_loss_from_predictions' \"\n \"method\"\n ) from err\n else:\n raise ValueError(\"Value of `input_type` not recognized.\")\n\n if y is not None and self._regressor_model:\n y = y.astype(np.float32).reshape(-1, 1)\n\n if self.default_model and self.attack_model_type == \"nn\":\n import torch\n from torch.utils.data import DataLoader\n from art.utils import to_cuda, from_cuda\n\n if self.scaler:\n features = self.scaler.transform(features)\n\n self.attack_model.eval() # type: ignore\n predictions: np.ndarray | None = None\n\n if y is not None and self.use_label:\n test_set = self._get_attack_dataset(f_1=features, f_2=y)\n test_loader = DataLoader(test_set, batch_size=self.batch_size, shuffle=False, num_workers=0)\n for input1, input2, _ in test_loader:\n input1, input2 = to_cuda(input1), to_cuda(input2)\n outputs = self.attack_model(input1, input2) # type: ignore\n if not probabilities:\n predicted = torch.round(outputs)\n else:\n predicted = outputs\n predicted = from_cuda(predicted)\n\n if predictions is None:\n predictions = predicted.detach().numpy()\n else:\n predictions = np.vstack((predictions, predicted.detach().numpy()))\n else:\n test_set = self._get_attack_dataset_no_label(f_1=features)\n test_loader = DataLoader(test_set, batch_size=self.batch_size, shuffle=False, num_workers=0)\n for input1, _ in test_loader:\n input1 = to_cuda(input1)\n outputs = self.attack_model(input1) # type: ignore\n if not probabilities:\n predicted = torch.round(outputs)\n else:\n predicted = outputs\n predicted = from_cuda(predicted)\n\n if predictions is None:\n predictions = predicted.detach().numpy()\n else:\n predictions = np.vstack((predictions, predicted.detach().numpy()))\n if predictions is not None:\n if not probabilities:\n inferred_return = np.round(predictions)\n else:\n inferred_return = predictions\n else: # pragma: no cover\n raise ValueError(\"No data available.\")\n elif not self.default_model:\n # assumes the predict method of the supplied model returns probabilities\n if y is not None and self.use_label:\n features = np.c_[features, y]\n if self.scaler:\n features = self.scaler.transform(features)\n inferred = self.attack_model.predict(features) # type: ignore\n else:\n if self.scaler:\n features = self.scaler.transform(features)\n inferred = self.attack_model.predict(features) # type: ignore\n if probabilities:\n inferred_return = inferred\n else:\n inferred_return = np.round(inferred)\n else:\n if y is not None and self.use_label:\n features = np.c_[features, y]\n if self.scaler:\n features = self.scaler.transform(features)\n inferred = self.attack_model.predict_proba(features) # type: ignore\n else:\n if self.scaler:\n features = self.scaler.transform(features)\n inferred = self.attack_model.predict_proba(features) # type: ignore\n if probabilities:\n inferred_return = inferred[:, [1]]\n else:\n inferred_return = np.round(inferred[:, [1]])\n\n return inferred_return\n\n def _get_attack_dataset(self, f_1, f_2, label=None):\n from torch.utils.data.dataset import Dataset\n\n class AttackDataset(Dataset):\n \"\"\"\n Implementation of a pytorch dataset for membership inference attack.\n\n The features are probabilities/logits or losses for the attack training data (`x_1`) along with\n its true labels (`x_2`). The labels (`y`) are a boolean representing whether this is a member.\n \"\"\"\n\n def __init__(self, x_1, x_2, y=None):\n import torch\n\n self.x_1 = torch.from_numpy(x_1.astype(np.float64)).type(torch.FloatTensor)\n self.x_2 = torch.from_numpy(x_2.astype(np.int32)).type(torch.FloatTensor)\n\n if y is not None:\n self.y = torch.from_numpy(y.astype(np.int8)).type(torch.FloatTensor)\n else:\n self.y = torch.zeros(x_1.shape[0])\n\n def __len__(self):\n return len(self.x_1)\n\n def __getitem__(self, idx):\n if idx >= len(self.x_1): # pragma: no cover\n raise IndexError(\"Invalid Index\")\n\n return self.x_1[idx], self.x_2[idx], self.y[idx]\n\n return AttackDataset(x_1=f_1, x_2=f_2, y=label)\n\n def _get_attack_dataset_no_label(self, f_1, label=None):\n from torch.utils.data.dataset import Dataset\n\n class AttackDataset(Dataset):\n \"\"\"\n Implementation of a pytorch dataset for membership inference attack.\n\n The features are probabilities/logits or losses for the attack training data (`x_1`) along with\n its true labels (`x_2`). The labels (`y`) are a boolean representing whether this is a member.\n \"\"\"\n\n def __init__(self, x_1, y=None):\n import torch\n\n self.x_1 = torch.from_numpy(x_1.astype(np.float64)).type(torch.FloatTensor)\n\n if y is not None:\n self.y = torch.from_numpy(y.astype(np.int8)).type(torch.FloatTensor)\n else:\n self.y = torch.zeros(x_1.shape[0])\n\n def __len__(self):\n return len(self.x_1)\n\n def __getitem__(self, idx):\n if idx >= len(self.x_1): # pragma: no cover\n raise IndexError(\"Invalid Index\")\n\n return self.x_1[idx], self.y[idx]\n\n return AttackDataset(x_1=f_1, y=label)\n\n def _check_params(self) -> None:\n if self.input_type not in [\"prediction\", \"loss\"]:\n raise ValueError(\"Illegal value for parameter `input_type`.\")\n\n if self._regressor_model:\n if self.input_type != \"loss\":\n raise ValueError(\"Illegal value for parameter `input_type` when estimator is a regressor.\")\n\n if self.attack_model_type not in [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"]:\n raise ValueError(\"Illegal value for parameter `attack_model_type`.\")\n\n if self.attack_model:\n if ClassifierMixin not in type(self.attack_model).__mro__:\n raise TypeError(\"Attack model must be of type Classifier.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/membership_inference/black_box_rule_based.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements membership inference attacks.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import MembershipInferenceAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass MembershipInferenceBlackBoxRuleBased(MembershipInferenceAttack):\n \"\"\"\n Implementation of a simple, rule-based black-box membership inference attack.\n\n This implementation uses the simple rule: if the model's prediction for a sample is correct, then it is a\n member. Otherwise, it is not a member.\n \"\"\"\n\n attack_params = MembershipInferenceAttack.attack_params\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\"):\n \"\"\"\n Create a MembershipInferenceBlackBoxRuleBased attack instance.\n\n :param classifier: Target classifier.\n \"\"\"\n super().__init__(estimator=classifier)\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer membership in the training set of the target estimator.\n\n :param x: Input records to attack.\n :param y: True labels for `x`.\n :param probabilities: a boolean indicating whether to return the predicted probabilities per class, or just\n the predicted class.\n :return: An array holding the inferred membership status, 1 indicates a member and 0 indicates non-member,\n or class probabilities.\n \"\"\"\n if y is None: # pragma: no cover\n raise ValueError(\"MembershipInferenceBlackBoxRuleBased requires true labels `y`.\")\n\n if self.estimator.input_shape is not None: # pragma: no cover\n if self.estimator.input_shape[0] != x.shape[1]:\n raise ValueError(\"Shape of x does not match input_shape of classifier\")\n\n if \"probabilities\" in kwargs:\n probabilities = kwargs.get(\"probabilities\")\n else:\n probabilities = False\n\n y = check_and_transform_label_format(y, nb_classes=len(np.unique(y)), return_one_hot=True)\n if y is None:\n raise ValueError(\"None value detected.\")\n if y.shape[0] != x.shape[0]: # pragma: no cover\n raise ValueError(\"Number of rows in x and y do not match\")\n\n # get model's predictions for x\n y_pred = self.estimator.predict(x=x)\n predicted_class = (np.argmax(y, axis=1) == np.argmax(y_pred, axis=1)).astype(int)\n if probabilities:\n # use y_pred as the probability if binary classification, otherwise just use 1\n if y_pred.shape[1] == 2:\n pred_prob = np.max(y_pred, axis=1)\n prob = np.zeros((predicted_class.shape[0], 2))\n prob[:, predicted_class] = pred_prob\n prob[:, np.ones_like(predicted_class) - predicted_class] = np.ones_like(pred_prob) - pred_prob\n else:\n # simply returns probability 1 for the predicted class and 0 for the other class\n prob_none = check_and_transform_label_format(predicted_class, nb_classes=2, return_one_hot=True)\n if prob_none is not None:\n prob = prob_none\n return prob\n return predicted_class\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/membership_inference/label_only_boundary_distance.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Label-Only Inference Attack based on Decision Boundary.\n\n| Paper link: https://arxiv.org/abs/2007.14321 (Choquette-Choo et al.)\n| Paper link: https://arxiv.org/abs/2007.15528 (Li and Zhang)\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import MembershipInferenceAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass LabelOnlyDecisionBoundary(MembershipInferenceAttack):\n \"\"\"\n Implementation of Label-Only Inference Attack based on Decision Boundary.\n\n You only need to call ONE of the calibrate methods, depending on which attack you want to launch.\n\n | Paper link: https://arxiv.org/abs/2007.14321 (Choquette-Choo et al.)\n | Paper link: https://arxiv.org/abs/2007.15528 (Li and Zhang)\n \"\"\"\n\n attack_params = MembershipInferenceAttack.attack_params + [\n \"distance_threshold_tau\",\n ]\n _estimator_requirements = (BaseEstimator, ClassifierMixin)\n\n def __init__(self, estimator: \"CLASSIFIER_TYPE\", distance_threshold_tau: float | None = None):\n \"\"\"\n Create a `LabelOnlyDecisionBoundary` instance for Label-Only Inference Attack based on Decision Boundary.\n\n :param estimator: A trained classification estimator.\n :param distance_threshold_tau: Threshold distance for decision boundary. Samples with boundary distances larger\n than threshold are considered members of the training dataset.\n \"\"\"\n super().__init__(estimator=estimator)\n self.distance_threshold_tau = distance_threshold_tau\n self.threshold_bins: list = []\n self._check_params()\n\n def infer(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Infer membership of input `x` in estimator's training data.\n\n :param x: Input data.\n :param y: True labels for `x`.\n :param probabilities: a boolean indicating whether to return the predicted probabilities per class, or just\n the predicted class\n\n :Keyword Arguments for HopSkipJump:\n * *norm*: Order of the norm. Possible values: \"inf\", np.inf or 2.\n * *max_iter*: Maximum number of iterations.\n * *max_eval*: Maximum number of evaluations for estimating gradient.\n * *init_eval*: Initial number of evaluations for estimating gradient.\n * *init_size*: Maximum number of trials for initial generation of adversarial examples.\n * *verbose*: Show progress bars.\n\n :return: An array holding the inferred membership status, 1 indicates a member and 0 indicates non-member,\n or class probabilities.\n \"\"\"\n from art.attacks.evasion.hop_skip_jump import HopSkipJump\n\n if y is None: # pragma: no cover\n raise ValueError(\"Argument `y` is None, but this attack requires true labels `y` to be provided.\")\n\n if self.distance_threshold_tau is None: # pragma: no cover\n raise ValueError(\n \"No value for distance threshold `distance_threshold_tau` provided. Please set\"\n \"`distance_threshold_tau` or run method `calibrate_distance_threshold` on known training and test\"\n \"dataset.\"\n )\n\n if \"probabilities\" in kwargs:\n probabilities = kwargs.get(\"probabilities\")\n del kwargs[\"probabilities\"]\n else:\n probabilities = False\n\n if \"classifier\" in kwargs: # pragma: no cover\n raise ValueError(\"Keyword `classifier` in kwargs is not supported.\")\n\n if \"targeted\" in kwargs: # pragma: no cover\n raise ValueError(\"Keyword `targeted` in kwargs is not supported.\")\n\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n hsj = HopSkipJump(classifier=self.estimator, targeted=False, **kwargs)\n x_adv = hsj.generate(x=x, y=y)\n\n distance = np.linalg.norm((x_adv - x).reshape((x.shape[0], -1)), ord=2, axis=1)\n\n y_pred = self.estimator.predict(x=x)\n\n distance[np.argmax(y_pred, axis=1) != np.argmax(y, axis=1)] = 0 # type: ignore\n predicted_class = np.where(distance > self.distance_threshold_tau, 1, 0)\n if probabilities:\n prob_1 = np.zeros_like(distance)\n if self.threshold_bins:\n # bin accuracy is the probability of being a member\n for t_bin in self.threshold_bins:\n prob_1[distance > t_bin[0]] = t_bin[1]\n else:\n # use sigmoid on distance from threshold\n dist_threshold = distance - self.distance_threshold_tau\n prob_1 = 1 / (1 + np.exp(-dist_threshold))\n prob_0 = np.ones_like(prob_1) - prob_1\n return np.stack((prob_0, prob_1), axis=1)\n return predicted_class\n\n def calibrate_distance_threshold(\n self, x_train: np.ndarray, y_train: np.ndarray, x_test: np.ndarray, y_test: np.ndarray, **kwargs\n ):\n \"\"\"\n Calibrate distance threshold maximising the membership inference accuracy on `x_train` and `x_test`.\n\n | Paper link: https://arxiv.org/abs/2007.14321\n\n :param x_train: Training data.\n :param y_train: Labels of training data `x_train`.\n :param x_test: Test data.\n :param y_test: Labels of test data `x_test`.\n\n :Keyword Arguments for HopSkipJump:\n * *norm*: Order of the norm. Possible values: \"inf\", np.inf or 2.\n * *max_iter*: Maximum number of iterations.\n * *max_eval*: Maximum number of evaluations for estimating gradient.\n * *init_eval*: Initial number of evaluations for estimating gradient.\n * *init_size*: Maximum number of trials for initial generation of adversarial examples.\n * *verbose*: Show progress bars.\n \"\"\"\n from art.attacks.evasion.hop_skip_jump import HopSkipJump\n\n if \"classifier\" in kwargs: # pragma: no cover\n raise ValueError(\"Keyword `classifier` in kwargs is not supported.\")\n\n if \"targeted\" in kwargs: # pragma: no cover\n raise ValueError(\"Keyword `targeted` in kwargs is not supported.\")\n\n y_train_onehot = check_and_transform_label_format(y_train, nb_classes=self.estimator.nb_classes)\n if y_train_onehot is None:\n raise ValueError(\"None value detected.\")\n y_test_onehot = check_and_transform_label_format(y_test, nb_classes=self.estimator.nb_classes)\n if y_test_onehot is None:\n raise ValueError(\"None value detected.\")\n\n hsj = HopSkipJump(classifier=self.estimator, targeted=False, **kwargs)\n\n x_train_adv = hsj.generate(x=x_train, y=y_train_onehot)\n x_test_adv = hsj.generate(x=x_test, y=y_test_onehot)\n\n distance_train = np.linalg.norm((x_train_adv - x_train).reshape((x_train.shape[0], -1)), ord=2, axis=1)\n distance_test = np.linalg.norm((x_test_adv - x_test).reshape((x_test.shape[0], -1)), ord=2, axis=1)\n\n y_train_pred = self.estimator.predict(x=x_train)\n y_test_pred = self.estimator.predict(x=x_test)\n\n distance_train[np.argmax(y_train_pred, axis=1) != np.argmax(y_train_onehot, axis=1)] = 0\n distance_test[np.argmax(y_test_pred, axis=1) != np.argmax(y_test_onehot, axis=1)] = 0\n\n num_increments = 100\n tau_increment = np.amax([np.amax(distance_train), np.amax(distance_test)]) / num_increments\n\n acc_max = 0.0\n distance_threshold_tau = 0.0\n self.threshold_bins = []\n for i_tau in range(1, num_increments):\n # searching for threshold that yields the best accuracy in separating between members and non-members\n is_member_train = np.where(distance_train > i_tau * tau_increment, 1, 0)\n is_member_test = np.where(distance_test > i_tau * tau_increment, 1, 0)\n\n acc = (np.sum(is_member_train) + (is_member_test.shape[0] - np.sum(is_member_test))) / (\n is_member_train.shape[0] + is_member_test.shape[0]\n )\n new_threshold_tau = i_tau * tau_increment\n self.threshold_bins.append((new_threshold_tau, acc))\n if acc > acc_max:\n distance_threshold_tau = new_threshold_tau\n acc_max = acc\n\n self.distance_threshold_tau = distance_threshold_tau\n\n def calibrate_distance_threshold_unsupervised(\n self, top_t: int = 50, num_samples: int = 100, max_queries: int = 1, **kwargs\n ):\n \"\"\"\n Calibrate distance threshold on randomly generated samples, choosing the top-t percentile of the noise needed\n to change the classifier's initial prediction. This method requires the model's clip_values to be set.\n\n | Paper link: https://arxiv.org/abs/2007.15528\n\n :param top_t: Top-t percentile.\n :param num_samples: Number of random samples to generate.\n :param max_queries: Maximum number of queries. Maximum number of HSJ iterations on a single sample will be\n max_queries * max_iter.\n :Keyword Arguments for HopSkipJump:\n * *norm*: Order of the norm. Possible values: \"inf\", np.inf or 2.\n * *max_iter*: Maximum number of iterations.\n * *max_eval*: Maximum number of evaluations for estimating gradient.\n * *init_eval*: Initial number of evaluations for estimating gradient.\n * *init_size*: Maximum number of trials for initial generation of adversarial examples.\n * *verbose*: Show progress bars.\n \"\"\"\n from art.attacks.evasion.hop_skip_jump import HopSkipJump\n\n if self.estimator.clip_values is not None:\n x_min, x_max = self.estimator.clip_values\n else: # pragma: no cover\n raise RuntimeError(\n \"You need to set the estimator's clip_values in order to calibrate the distance threshold.\"\n )\n\n x_rand = np.random.rand(*(num_samples,) + self.estimator.input_shape).astype(np.float32)\n x_rand *= x_max - x_min # scale\n x_rand += x_min # shift\n\n y_rand = self.estimator.predict(x=x_rand)\n y_rand = check_and_transform_label_format(y_rand, nb_classes=self.estimator.nb_classes)\n\n hsj = HopSkipJump(classifier=self.estimator, targeted=False, **kwargs)\n\n distances = []\n\n i = 0\n while len(x_rand) != 0 and i < max_queries:\n x_adv = hsj.generate(x=x_rand, y=y_rand)\n\n distance = np.linalg.norm((x_adv - x_rand).reshape((x_rand.shape[0], -1)), ord=2, axis=1)\n\n y_pred = self.estimator.predict(x=x_adv)\n\n changed_predictions = np.argmax(y_pred, axis=1) != np.argmax(y_rand, axis=1)\n\n distances.extend(distance[changed_predictions])\n\n x_rand, y_rand = x_adv[~changed_predictions], y_rand[~changed_predictions]\n\n i += 1\n\n if len(distances) == 0: # pragma: no cover\n raise RuntimeWarning(\n \"No successful adversarial examples were generated - no distances were obtained.\"\n \"Distance threshold will not be set.\"\n )\n self.distance_threshold_tau = np.percentile(distances, top_t)\n\n def _check_params(self) -> None:\n if self.distance_threshold_tau is not None and (\n not isinstance(self.distance_threshold_tau, (int, float)) or self.distance_threshold_tau <= 0.0\n ):\n raise ValueError(\"The distance threshold `distance_threshold_tau` needs to be a positive float.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/membership_inference/label_only_gap_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Label Only Gap Attack `.\n\n| Paper link: https://arxiv.org/abs/2007.14321\n\"\"\"\nimport logging\n\nfrom art.attacks.inference.membership_inference.black_box_rule_based import MembershipInferenceBlackBoxRuleBased\n\n\nlogger = logging.getLogger(__name__)\n\n\nLabelOnlyGapAttack = MembershipInferenceBlackBoxRuleBased\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/membership_inference/shadow_models.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nThis module implements membership inference attacks.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable, Sequence\nimport math\nfrom functools import reduce\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, CLONABLE\n\n\nclass ShadowModels:\n \"\"\"\n Utility for training shadow models and generating shadow-datasets for membership inference attacks in scikit-learn,\n PyTorch and TensorFlow v2.\n \"\"\"\n\n def __init__(\n self,\n shadow_model_template: \"CLONABLE\",\n num_shadow_models: int = 3,\n disjoint_datasets=False,\n random_state=None,\n ):\n \"\"\"\n Initializes shadow models using the provided template.\n\n :param shadow_model_template: Untrained classifier model to be used as a template for shadow models. Should be\n as similar as possible to the target model. Must implement clone_for_refitting\n method.\n :param num_shadow_models: How many shadow models to train to generate the shadow dataset.\n :param disjoint_datasets: A boolean indicating whether the datasets used to train each shadow model should be\n disjoint. Default is False.\n :param random_state: Seed for the numpy default random number generator.\n \"\"\"\n\n self._shadow_models = [shadow_model_template.clone_for_refitting() for _ in range(num_shadow_models)]\n self._shadow_models_train_sets: list[tuple[np.ndarray, np.ndarray] | None] = [None] * num_shadow_models\n self._input_shape = shadow_model_template.input_shape\n self._rng = np.random.default_rng(seed=random_state)\n self._disjoint_datasets = disjoint_datasets\n\n def generate_shadow_dataset(\n self,\n x: np.ndarray,\n y: np.ndarray,\n member_ratio: float = 0.5,\n ) -> tuple[tuple[np.ndarray, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray, np.ndarray]]:\n \"\"\"\n Generates a shadow dataset (member and nonmember samples and their corresponding model predictions) by splitting\n the dataset into training and testing samples, and then training the shadow models on the result.\n\n :param x: The samples used to train the shadow models.\n :param y: True labels for the dataset samples (as expected by the estimator's fit method).\n :param member_ratio: Percentage of the data that should be used to train the shadow models. Must be between 0\n and 1.\n :return: The shadow dataset generated. The shape is `((member_samples, true_label, model_prediction),\n (nonmember_samples, true_label, model_prediction))`.\n \"\"\"\n\n if len(x) != len(y):\n raise ValueError(\"Number of samples in dataset does not match number of labels\")\n\n # Shuffle data set\n random_indices = self._rng.permutation(len(x))\n x, y = x[random_indices], y[random_indices]\n\n if self._disjoint_datasets:\n shadow_dataset_size = len(x) // len(self._shadow_models)\n else:\n shadow_dataset_size = len(x)\n\n member_samples = []\n member_true_label = []\n member_prediction = []\n nonmember_samples = []\n nonmember_true_label = []\n nonmember_prediction = []\n\n # Train and create predictions for every model\n for i, shadow_model in enumerate(self._shadow_models):\n if self._disjoint_datasets:\n shadow_x = x[shadow_dataset_size * i : shadow_dataset_size * (i + 1)]\n shadow_y = y[shadow_dataset_size * i : shadow_dataset_size * (i + 1)]\n\n shadow_x_train = shadow_x[: int(member_ratio * shadow_dataset_size)]\n shadow_y_train = shadow_y[: int(member_ratio * shadow_dataset_size)]\n shadow_x_test = shadow_x[int(member_ratio * shadow_dataset_size) :]\n shadow_y_test = shadow_y[int(member_ratio * shadow_dataset_size) :]\n else:\n member_indexes = self._rng.choice(len(x) - 1, int(len(x) * member_ratio), replace=False)\n non_member_indexes = np.setdiff1d(range(len(x) - 1), member_indexes, assume_unique=True)\n shadow_x_train = x[member_indexes]\n shadow_y_train = y[member_indexes]\n shadow_x_test = x[non_member_indexes]\n shadow_y_test = y[non_member_indexes]\n\n self._shadow_models_train_sets[i] = (shadow_x_train, shadow_y_train)\n\n shadow_model.fit(shadow_x_train, shadow_y_train)\n\n member_samples.append(shadow_x_train)\n member_true_label.append(shadow_y_train)\n member_prediction.append(shadow_model.predict(shadow_x_train))\n\n nonmember_samples.append(shadow_x_test)\n nonmember_true_label.append(shadow_y_test)\n nonmember_prediction.append(shadow_model.predict(shadow_x_test))\n\n def concat(first: np.ndarray, second: np.ndarray) -> np.ndarray:\n return np.concatenate((first, second))\n\n # Concatenate the results of all the shadow models\n all_member_samples = reduce(concat, member_samples)\n all_member_true_label = reduce(concat, member_true_label)\n all_member_prediction = reduce(concat, member_prediction)\n all_nonmember_samples = reduce(concat, nonmember_samples)\n all_nonmember_true_label = reduce(concat, nonmember_true_label)\n all_nonmember_prediction = reduce(concat, nonmember_prediction)\n\n return (\n (all_member_samples, all_member_true_label, all_member_prediction),\n (all_nonmember_samples, all_nonmember_true_label, all_nonmember_prediction),\n )\n\n def _default_random_record(self) -> np.ndarray:\n return self._rng.random(self._input_shape)\n\n def _default_randomize_features(self, record: np.ndarray, num_features: int) -> np.ndarray:\n new_record = record.copy()\n for _ in range(num_features):\n new_record[self._rng.integers(0, self._input_shape)] = self._rng.random()\n return new_record\n\n def _hill_climbing_synthesis(\n self,\n target_classifier: \"CLASSIFIER_TYPE\",\n target_class: int,\n min_confidence: float,\n max_features_randomized: int | None,\n max_iterations: int = 40,\n max_rejections: int = 3,\n min_features_randomized: int = 1,\n random_record_fn: Callable[[], np.ndarray] | None = None,\n randomize_features_fn: Callable[[np.ndarray, int], np.ndarray] | None = None,\n ) -> np.ndarray:\n \"\"\"\n This method implements the hill climbing algorithm from R. Shokri et al. (2017)\n\n Paper Link: https://arxiv.org/abs/1610.05820\n\n :param target_classifier: The classifier to synthesize data from.\n :param target_class: The class the synthesized record will have.\n :param min_confidence: The minimum confidence the classifier assigns the target class for the record to be\n accepted (i.e. the hill-climbing algorithm is finished).\n :param max_features_randomized: The initial amount of features to randomize in each climbing step. A good\n default value is one half of the number of features.\n :param max_iterations: The maximum amount of iterations to try and improve the classifier's confidence in the\n generated record. This is essentially the maximum number of hill-climbing steps.\n :param max_rejections: The maximum amount of rejections (i.e. a step which did not improve the confidence)\n before starting to fine-tune the record (i.e. making smaller steps).\n :param min_features_randomized: The minimum amount of features to randomize when fine-tuning.\n :param random_record_fn: Callback that returns a single random record (numpy array), i.e. all feature values are\n random. If None, random records are generated by treating each column in the input\n shape as a feature and choosing uniform values [0, 1) for each feature. This default\n behaviour is not correct for one-hot-encoded features, and a custom callback which\n provides a random record with random one-hot-encoded values should be used instead.\n :param randomize_features_fn: Callback that accepts an existing record (numpy array) and an int which is the\n number of features to randomize. The callback should return a new record, where\n the specified number of features have been randomized. If None, records are\n randomized by treating each column in the input shape as a feature, and choosing\n uniform values [0, 1) for each randomized feature. This default behaviour is not\n correct for one-hot-encoded features, and a custom callback which randomizes\n one-hot-encoded features should be used instead.\n :return: Synthesized record.\n \"\"\"\n\n if random_record_fn is None:\n random_record_fn = self._default_random_record\n if randomize_features_fn is None:\n randomize_features_fn = self._default_randomize_features\n\n best_x = None\n best_class_confidence = 0\n num_rejections = 0\n\n x = random_record_fn()\n\n if max_features_randomized is None:\n k_features_randomized = x.reshape(1, -1).shape[1] // 2\n else:\n k_features_randomized = max_features_randomized\n\n for _ in range(max_iterations):\n y = target_classifier.predict(x.reshape(1, -1))[0]\n class_confidence = y[target_class]\n\n if class_confidence >= best_class_confidence:\n # Record accepted, sample randomly\n if class_confidence > min_confidence and np.argmax(y) == target_class:\n if self._rng.random() < class_confidence:\n return x\n\n best_x = x\n best_class_confidence = class_confidence\n num_rejections = 0\n else:\n num_rejections += 1\n if num_rejections > max_rejections:\n # Rejected too many times, we are probably making changes which are too large\n half_current_features = math.ceil(k_features_randomized / 2)\n k_features_randomized = max(min_features_randomized, half_current_features) # type: ignore\n num_rejections = 0\n\n x = randomize_features_fn(best_x, k_features_randomized) # type: ignore\n\n raise RuntimeError(\"Failed to synthesize data record\")\n\n def generate_synthetic_shadow_dataset(\n self,\n target_classifier: \"CLASSIFIER_TYPE\",\n dataset_size: int,\n max_features_randomized: int | None,\n member_ratio: float = 0.5,\n min_confidence: float = 0.4,\n max_retries: int = 6,\n random_record_fn: Callable[[], np.ndarray] | None = None,\n randomize_features_fn: Callable[[np.ndarray, int], np.ndarray] | None = None,\n ) -> tuple[tuple[np.ndarray, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray, np.ndarray]]:\n \"\"\"\n Generates a shadow dataset (member and nonmember samples and their corresponding model predictions) by training\n the shadow models on a synthetic dataset generated from the target classifier using the hill climbing algorithm\n from R. Shokri et al. (2017)\n\n Paper Link: https://arxiv.org/abs/1610.05820\n\n :param target_classifier: The classifier to synthesize data from.\n :param dataset_size: How many records to synthesize.\n :param max_features_randomized: The initial amount of features to randomize before fine-tuning. If None, half of\n record features will be used, which will not work well for one-hot encoded data.\n :param member_ratio: Percentage of the data that should be used to train the shadow models. Must be between 0\n and 1.\n :param min_confidence: The minimum confidence the classifier assigns the target class for the record to be\n accepted (i.e. the hill-climbing algorithm is finished).\n :param max_retries: The maximum amount of record-generation retries. The initial random pick of a record for the\n hill-climbing algorithm might result in failing to optimize the target-class confidence, and\n so a new random record will be retried.\n :param random_record_fn: Callback that returns a single random record (numpy array), i.e. all feature values are\n random. If None, random records are generated by treating each column in the input\n shape as a feature and choosing uniform values [0, 1) for each feature. This default\n behaviour is not correct for one-hot-encoded features, and a custom callback which\n provides a random record with random one-hot-encoded values should be used instead.\n :param randomize_features_fn: Callback that accepts an existing record (numpy array) and an int which is the\n number of features to randomize. The callback should return a new record, where\n the specified number of features have been randomized. If None, records are\n randomized by treating each column in the input shape as a feature, and choosing\n uniform values [0, 1) for each randomized feature. This default behaviour is not\n correct for one-hot-encoded features, and a custom callback which randomizes\n one-hot-encoded features should be used instead.\n :return: The shadow dataset generated. The shape is `((member_samples, true_label, model_prediction),\n (nonmember_samples, true_label, model_prediction))`.\n \"\"\"\n x = []\n y = []\n\n records_per_class = dataset_size // target_classifier.nb_classes\n\n # Generate samples for each classification class\n for target_class in range(target_classifier.nb_classes):\n one_hot_label = np.zeros(target_classifier.nb_classes)\n one_hot_label[target_class] = 1.0\n\n for _ in range(records_per_class):\n for tries in range(max_retries):\n try:\n random_record = self._hill_climbing_synthesis(\n target_classifier,\n target_class,\n min_confidence,\n max_features_randomized=max_features_randomized,\n random_record_fn=random_record_fn,\n randomize_features_fn=randomize_features_fn,\n )\n break\n except RuntimeError as err:\n if tries == max_retries - 1:\n raise err\n\n x.append(random_record)\n y.append(one_hot_label)\n\n return self.generate_shadow_dataset(np.array(x), np.array(y), member_ratio)\n\n def get_shadow_models(\n self,\n ) -> Sequence[\"CLONABLE\"]:\n \"\"\"\n Returns the list of shadow models. `generate_shadow_dataset` or `generate_synthetic_shadow_dataset` must be\n called for the shadow models to be trained.\n \"\"\"\n return self._shadow_models\n\n def get_shadow_models_train_sets(self) -> list[tuple[np.ndarray, np.ndarray] | None]:\n \"\"\"\n Returns a list of tuples the form (shadow_x_train, shadow_y_train) for each shadow model.\n `generate_shadow_dataset` or `generate_synthetic_shadow_dataset` must be called before, or a list of Nones will\n be returned.\n \"\"\"\n return self._shadow_models_train_sets\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/model_inversion/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing model inversion attacks.\n\"\"\"\n\nfrom art.attacks.inference.model_inversion.mi_face import MIFace\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/model_inversion/mi_face.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements model inversion attacks.\n\n| Paper link: https://dl.acm.org/doi/10.1145/2810103.2813677\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.classification.classifier import ClassifierMixin, ClassGradientsMixin\nfrom art.estimators.estimator import BaseEstimator\nfrom art.attacks.attack import InferenceAttack\nfrom art.utils import get_labels_np_array, check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass MIFace(InferenceAttack):\n \"\"\"\n Implementation of the MIFace algorithm from Fredrikson et al. (2015). While in that paper the attack is demonstrated\n specifically against face recognition models, it is applicable more broadly to classifiers with continuous features\n which expose class gradients.\n\n | Paper link: https://dl.acm.org/doi/10.1145/2810103.2813677\n \"\"\"\n\n attack_params = InferenceAttack.attack_params + [\n \"max_iter\",\n \"window_length\",\n \"threshold\",\n \"learning_rate\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin, ClassGradientsMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n max_iter: int = 10000,\n window_length: int = 100,\n threshold: float = 0.99,\n learning_rate: float = 0.1,\n batch_size: int = 1,\n verbose: bool = True,\n ):\n \"\"\"\n Create an MIFace attack instance.\n\n :param classifier: Target classifier.\n :param max_iter: Maximum number of gradient descent iterations for the model inversion.\n :param window_length: Length of window for checking whether descent should be aborted.\n :param threshold: Threshold for descent stopping criterion.\n :param batch_size: Size of internal batches.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(estimator=classifier)\n\n self.max_iter = max_iter\n self.window_length = window_length\n self.threshold = threshold\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def infer(self, x: np.ndarray | None, y: np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Extract a thieved classifier.\n\n :param x: An array with the initial input to the victim classifier. If `None`, then initial input will be\n initialized as zero array.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :return: The inferred training samples.\n \"\"\"\n if x is None and y is None:\n raise ValueError(\"Either `x` or `y` should be provided.\")\n\n if y is None:\n y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))\n else:\n y = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n if x is None:\n x = np.zeros((len(y),) + self.estimator.input_shape)\n\n x_infer = x.astype(ART_NUMPY_DTYPE)\n\n # Compute inversions with implicit batching\n for batch_id in trange(\n int(np.ceil(x.shape[0] / float(self.batch_size))), desc=\"Model inversion\", disable=not self.verbose\n ):\n batch_index_1, batch_index_2 = batch_id * self.batch_size, (batch_id + 1) * self.batch_size\n batch = x_infer[batch_index_1:batch_index_2]\n batch_labels = y[batch_index_1:batch_index_2]\n\n active = np.array([True] * len(batch))\n window = np.inf * np.ones((len(batch), self.window_length))\n\n i = 0\n\n while i < self.max_iter and sum(active) > 0:\n grads = self.estimator.class_gradient(batch[active], np.argmax(batch_labels[active], axis=1))\n grads = np.reshape(grads, (grads.shape[0],) + grads.shape[2:])\n batch[active] = batch[active] + self.learning_rate * grads\n\n if self.estimator.clip_values is not None:\n clip_min, clip_max = self.estimator.clip_values\n batch[active] = np.clip(batch[active], clip_min, clip_max)\n\n cost = 1 - self.estimator.predict(batch)[np.arange(len(batch)), np.argmax(batch_labels, axis=1)]\n active = (cost <= self.threshold) + (cost >= np.max(window, axis=1))\n\n i_window = i % self.window_length\n window[::, i_window] = cost\n\n i = i + 1\n\n x_infer[batch_index_1:batch_index_2] = batch\n\n return x_infer\n\n def _check_params(self) -> None:\n if not isinstance(self.max_iter, int) or self.max_iter < 0:\n raise ValueError(\"The number of iterations must be a non-negative integer.\")\n\n if not isinstance(self.window_length, int) or self.window_length < 0:\n raise ValueError(\"The window length must be a non-negative integer.\")\n\n if not isinstance(self.threshold, float) or self.threshold < 0.0:\n raise ValueError(\"The threshold must be a non-negative float.\")\n\n if not isinstance(self.learning_rate, float) or self.learning_rate < 0.0:\n raise ValueError(\"The learning rate must be a non-negative float.\")\n\n if not isinstance(self.batch_size, int) or self.batch_size < 0:\n raise ValueError(\"The batch size must be a non-negative integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/reconstruction/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing model inversion attacks.\n\"\"\"\n\nfrom art.attacks.inference.reconstruction.white_box import DatabaseReconstruction\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/inference/reconstruction/white_box.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements reconstruction attacks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\nimport numpy as np\nimport sklearn\nfrom scipy.optimize import fmin_l_bfgs_b\n\nfrom art.attacks.attack import ReconstructionAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.scikitlearn import ScikitlearnEstimator\n\nlogger = logging.getLogger(__name__)\n\n\nclass DatabaseReconstruction(ReconstructionAttack):\n \"\"\"\n Implementation of a database reconstruction attack. In this case, the adversary is assumed to have in his/her\n possession a model trained on a dataset, and all but one row of that training dataset. This attack attempts to\n reconstruct the missing row.\n \"\"\"\n\n _estimator_requirements = (BaseEstimator, ClassifierMixin, ScikitlearnEstimator)\n\n def __init__(self, estimator):\n \"\"\"\n Create a DatabaseReconstruction instance.\n\n :param estimator: Trained target estimator.\n \"\"\"\n super().__init__(estimator=estimator)\n\n self.params = self.estimator.get_trainable_attribute_names()\n\n @staticmethod\n def objective(x, y, x_train, y_train, private_estimator, parent_model, params):\n \"\"\"Objective function which we seek to minimise\"\"\"\n\n model = sklearn.base.clone(parent_model.model, safe=True)\n model.fit(np.vstack((x_train, x)), np.hstack((y_train, y)))\n\n residual = 0.0\n\n for param in params:\n residual += np.sum((model.__getattribute__(param) - private_estimator.model.__getattribute__(param)) ** 2)\n\n return residual\n\n def reconstruct(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Infer the missing row from x, y with which `estimator` was trained with.\n\n :param x: Known records of the training set of `estimator`.\n :param y: Known labels of the training set of `estimator`.\n \"\"\"\n if y is None:\n y = self.estimator.predict(x=x)\n\n if y.ndim == 2:\n y = np.argmax(y, axis=1)\n\n tol = float(\"inf\")\n x_0 = x[0, :]\n x_guess: np.ndarray | None = None\n y_guess: int\n\n for _y in range(self.estimator.nb_classes):\n args = (_y, x, y, self._estimator, self.estimator, self.params)\n _x, _tol, _ = fmin_l_bfgs_b(\n self.objective, x_0, args=args, approx_grad=True, factr=100, pgtol=1e-10, bounds=None\n )\n\n if _tol < tol:\n tol = _tol\n x_guess = _x\n y_guess = _y\n\n if x_guess is None:\n raise ValueError(\"Guessed values are None.\")\n\n x_reconstructed = np.expand_dims(x_guess, axis=0)\n y_reconstructed = np.zeros(shape=(1, self.estimator.nb_classes))\n y_reconstructed[0, y_guess] = 1\n\n return x_reconstructed, y_reconstructed\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing poisoning attacks under a common interface.\n\"\"\"\n\nfrom art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_red import BackdoorAttackDGMReDTensorFlowV2\nfrom art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_trail import BackdoorAttackDGMTrailTensorFlowV2\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.attacks.poisoning.bad_det.bad_det_rma import BadDetRegionalMisclassificationAttack\nfrom art.attacks.poisoning.bad_det.bad_det_gma import BadDetGlobalMisclassificationAttack\nfrom art.attacks.poisoning.bad_det.bad_det_oga import BadDetObjectGenerationAttack\nfrom art.attacks.poisoning.bad_det.bad_det_oda import BadDetObjectDisappearanceAttack\nfrom art.attacks.poisoning.poisoning_attack_svm import PoisoningAttackSVM\nfrom art.attacks.poisoning.feature_collision_attack import FeatureCollisionAttack\nfrom art.attacks.poisoning.adversarial_embedding_attack import PoisoningAttackAdversarialEmbedding\nfrom art.attacks.poisoning.clean_label_backdoor_attack import PoisoningAttackCleanLabelBackdoor\nfrom art.attacks.poisoning.bullseye_polytope_attack import BullseyePolytopeAttackPyTorch\nfrom art.attacks.poisoning.gradient_matching_attack import GradientMatchingAttack\nfrom art.attacks.poisoning.hidden_trigger_backdoor.hidden_trigger_backdoor import HiddenTriggerBackdoor\nfrom art.attacks.poisoning.hidden_trigger_backdoor.hidden_trigger_backdoor_pytorch import HiddenTriggerBackdoorPyTorch\nfrom art.attacks.poisoning.hidden_trigger_backdoor.hidden_trigger_backdoor_keras import HiddenTriggerBackdoorKeras\nfrom art.attacks.poisoning.sleeper_agent_attack import SleeperAgentAttack\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/adversarial_embedding_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements clean-label attacks on Neural Networks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import PoisoningAttackTransformer\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.estimators.classification.keras import KerasClassifier\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass PoisoningAttackAdversarialEmbedding(PoisoningAttackTransformer):\n \"\"\"\n Implementation of Adversarial Embedding attack by Tan, Shokri (2019).\n \"Bypassing Backdoor Detection Algorithms in Deep Learning\"\n\n This attack trains a classifier with an additional discriminator and loss function that aims\n to create non-differentiable latent representations between backdoored and benign examples.\n\n | Paper link: https://arxiv.org/abs/1905.13409\n \"\"\"\n\n attack_params = PoisoningAttackTransformer.attack_params + [\n \"backdoor\",\n \"feature_layer\",\n \"target\",\n \"pp_poison\",\n \"discriminator_layer_1\",\n \"discriminator_layer_2\",\n \"regularization\",\n \"learning_rate\",\n ]\n\n _estimator_requirements = (KerasClassifier,)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n backdoor: PoisoningAttackBackdoor,\n feature_layer: int | str,\n target: np.ndarray | list[tuple[np.ndarray, np.ndarray]],\n pp_poison: float | list[float] = 0.05,\n discriminator_layer_1: int = 256,\n discriminator_layer_2: int = 128,\n regularization: float = 10,\n learning_rate: float = 1e-4,\n clone=True,\n ):\n \"\"\"\n Initialize a Feature Collision Clean-Label poisoning attack\n\n :param classifier: A neural network classifier.\n :param backdoor: The backdoor attack used to poison samples\n :param feature_layer: The layer of the original network to extract features from\n :param target: The target label to poison\n :param pp_poison: The percentage of training data to poison\n :param discriminator_layer_1: The size of the first discriminator layer\n :param discriminator_layer_2: The size of the second discriminator layer\n :param regularization: The regularization constant for the backdoor recognition part of the loss function\n :param learning_rate: The learning rate of clean-label attack optimization.\n :param clone: Whether to clone the model or apply the attack on the original model\n \"\"\"\n super().__init__(classifier=classifier)\n self.backdoor = backdoor\n self.feature_layer = feature_layer\n self.target = target\n if isinstance(pp_poison, float):\n self.pp_poison = [pp_poison]\n else:\n self.pp_poison = pp_poison\n self.discriminator_layer_1 = discriminator_layer_1\n self.discriminator_layer_2 = discriminator_layer_2\n self.regularization = regularization\n self.train_data: np.ndarray | None = None\n self.train_labels: np.ndarray | None = None\n self.is_backdoor: np.ndarray | None = None\n self.learning_rate = learning_rate\n self._check_params()\n\n if isinstance(self.estimator, KerasClassifier):\n\n from keras.models import Model, clone_model\n from keras.layers import (\n GaussianNoise,\n Dense,\n BatchNormalization,\n LeakyReLU,\n Input,\n Flatten,\n )\n from keras.optimizers import Adam\n import keras\n\n opt = Adam(learning_rate=self.learning_rate)\n\n # Clone and build model\n if clone:\n self.orig_model = clone_model(self.estimator.model)\n self.orig_model.set_weights(self.estimator.model.get_weights())\n else:\n self.orig_model = self.estimator.model\n\n # Ensure model is built (important for Sequential models)\n if not self.orig_model.built:\n # Provide a dummy input shape based on the estimator input\n dummy_input_shape = (None,) + self.estimator.input_shape[1:]\n self.orig_model.build(dummy_input_shape)\n\n # Access model input/output (safe for Functional & Sequential)\n model_input = self.orig_model.inputs\n init_model_output = self.orig_model(model_input)\n\n # Extract feature layer output\n if isinstance(self.feature_layer, int):\n feature_layer_tensor = self.orig_model.layers[self.feature_layer].output\n else:\n feature_layer_tensor = self.orig_model.get_layer(name=self.feature_layer).output\n\n feature_extractor = Model(inputs=model_input, outputs=feature_layer_tensor)\n\n # Discriminator architecture\n discriminator_input = feature_extractor(model_input)\n if len(discriminator_input.shape) > 2:\n discriminator_input = Flatten()(discriminator_input)\n\n discriminator_input = GaussianNoise(stddev=1.0)(discriminator_input)\n\n x = Dense(self.discriminator_layer_1)(discriminator_input)\n x = BatchNormalization()(x)\n x = LeakyReLU(alpha=0.2)(x)\n\n x = Dense(self.discriminator_layer_2)(x)\n x = BatchNormalization()(x)\n x = LeakyReLU(alpha=0.2)(x)\n\n backdoor_detect = Dense(2, activation=\"softmax\", name=\"backdoor_detect\")(x)\n\n # Final embedded model\n self.embed_model = Model(inputs=model_input, outputs=[init_model_output, backdoor_detect])\n\n # Add backdoor detection loss\n model_name = self.orig_model.name\n model_loss = self.estimator.model.loss\n loss_name = \"backdoor_detect\"\n loss_type = \"binary_crossentropy\"\n if isinstance(model_loss, str):\n losses = {model_name: model_loss, loss_name: loss_type}\n loss_weights = {model_name: 1.0, loss_name: -self.regularization}\n elif isinstance(model_loss, dict):\n losses = model_loss\n losses[loss_name] = loss_type\n loss_weights = self.orig_model.loss_weights\n loss_weights[loss_name] = -self.regularization\n else:\n raise TypeError(f\"Cannot read model loss value of type {type(model_loss)}\")\n\n self.embed_model.compile(\n optimizer=opt, loss=losses, loss_weights=loss_weights, metrics=[\"accuracy\", \"accuracy\"]\n )\n else:\n raise NotImplementedError(\"This attack currently only supports Keras.\")\n\n def poison(\n self, x: np.ndarray, y: np.ndarray | None = None, broadcast=False, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calls perturbation function on input x and target labels y\n\n :param x: An array with the points that initialize attack points.\n :param y: The target labels for the attack.\n :param broadcast: Whether to broadcast single target label\n :return: An tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n return self.backdoor.poison(x, y, broadcast=broadcast)\n\n def poison_estimator(\n self, x: np.ndarray, y: np.ndarray, batch_size: int = 64, nb_epochs: int = 10, **kwargs\n ) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Train a poisoned model and return it\n :param x: Training data\n :param y: Training labels\n :param batch_size: The size of the batches used for training\n :param nb_epochs: The number of epochs to train for\n :return: A classifier with embedded backdoors\n \"\"\"\n train_data = np.copy(x)\n train_labels = np.copy(y)\n\n # Select indices to poison\n selected_indices = np.zeros(len(x)).astype(bool)\n\n if len(self.pp_poison) == 1:\n if isinstance(self.target, np.ndarray):\n not_target = np.logical_not(np.all(y == self.target, axis=1))\n selected_indices[not_target] = np.random.uniform(size=sum(not_target)) < self.pp_poison[0]\n else:\n for src, _ in self.target:\n all_src = np.all(y == src, axis=1)\n selected_indices[all_src] = np.random.uniform(size=sum(all_src)) < self.pp_poison[0]\n else:\n for p_p, (src, _) in zip(self.pp_poison, self.target):\n all_src = np.all(y == src, axis=1)\n selected_indices[all_src] = np.random.uniform(size=sum(all_src)) < p_p\n\n # Poison selected indices\n if isinstance(self.target, np.ndarray):\n to_be_poisoned = train_data[selected_indices]\n poison_data, poison_labels = self.poison(to_be_poisoned, y=self.target, broadcast=True)\n\n poison_idxs = np.arange(len(x))[selected_indices]\n for i, idx in enumerate(poison_idxs):\n train_data[idx] = poison_data[i]\n train_labels[idx] = poison_labels[i]\n else:\n for src, tgt in self.target:\n poison_mask = np.logical_and(selected_indices, np.all(y == src, axis=1))\n to_be_poisoned = train_data[poison_mask]\n src_poison_data, src_poison_labels = self.poison(to_be_poisoned, y=shape_labels(tgt), broadcast=True)\n train_data[poison_mask] = src_poison_data\n train_labels[poison_mask] = src_poison_labels\n\n # label 1 if is backdoor 0 otherwise\n is_backdoor = selected_indices.astype(int)\n\n # convert to one-hot\n is_backdoor = np.fromfunction(lambda b_idx: np.eye(2)[is_backdoor[b_idx]], shape=(len(x),), dtype=int)\n\n # Save current training data\n self.train_data = train_data\n self.train_labels = train_labels\n self.is_backdoor = is_backdoor\n\n if isinstance(self.estimator, KerasClassifier):\n # Call fit with both y and is_backdoor labels\n self.embed_model.fit(\n train_data, y=[train_labels, is_backdoor], batch_size=batch_size, epochs=nb_epochs, **kwargs\n )\n params = self.estimator.get_params()\n del params[\"model\"]\n del params[\"nb_classes\"]\n return KerasClassifier(self.orig_model, **params)\n\n raise NotImplementedError(\"Currently only Keras is supported\")\n\n def get_training_data(self) -> tuple[np.ndarray, np.ndarray | None, np.ndarray | None] | None:\n \"\"\"\n Returns the training data generated from the last call to fit\n\n :return: If fit has been called, return the last data, labels, and backdoor labels used to train model\n otherwise return None\n \"\"\"\n if self.train_data is not None:\n return self.train_data, self.train_labels, self.is_backdoor\n\n return None\n\n def _check_params(self) -> None:\n if isinstance(self.feature_layer, str):\n layer_names = {layer.name for layer in self.estimator.model.layers}\n if self.feature_layer not in layer_names:\n raise ValueError(f\"Layer {self.feature_layer} not found in model\")\n elif isinstance(self.feature_layer, int):\n num_layers = len(self.estimator.model.layers)\n if num_layers <= int(self.feature_layer) or int(self.feature_layer) < 0:\n raise ValueError(\n f\"Feature layer {self.feature_layer} is out of range. Network only has {num_layers} layers\"\n )\n\n if isinstance(self.target, np.ndarray):\n self._check_valid_label_shape(self.target)\n else:\n for source, target in self.target:\n self._check_valid_label_shape(shape_labels(source))\n self._check_valid_label_shape(shape_labels(target))\n\n if len(self.pp_poison) == 1:\n _check_pp_poison(self.pp_poison[0])\n else: # pragma: no cover\n if not isinstance(self.target, list):\n raise ValueError(\"Target should be list of source label pairs\")\n if len(self.pp_poison) != len(self.target):\n raise ValueError(\"pp_poison and target lists should be the same length\")\n for p_p in self.pp_poison:\n _check_pp_poison(p_p)\n\n if self.regularization <= 0:\n raise ValueError(\"Regularization constant must be positive\")\n\n if self.discriminator_layer_1 <= 0 or self.discriminator_layer_2 <= 0:\n raise ValueError(\"Discriminator layer size must be positive\")\n\n def _check_valid_label_shape(self, label: np.ndarray) -> None:\n if label.shape != self.estimator.model.output_shape[1:]:\n raise ValueError(\n f\"Invalid shape for target array. Should be {self.estimator.model.output_shape[1:]} \"\n f\"received {label.shape}\"\n )\n\n\ndef _check_pp_poison(pp_poison: float) -> None:\n \"\"\"\n Return an error when a poison value is invalid\n \"\"\"\n if not 0 <= pp_poison <= 1:\n raise ValueError(\"pp_poison must be between 0 and 1\")\n\n\ndef shape_labels(lbl: np.ndarray) -> np.ndarray:\n \"\"\"\n Reshape a labels array\n\n :param lbl: a label array\n :return:\n \"\"\"\n if lbl.shape[0] == 1:\n return lbl.squeeze(axis=0)\n return lbl\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/backdoor_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Backdoor Attacks to poison data used in ML models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\n\nimport numpy as np\n\nfrom art.attacks.attack import PoisoningAttackBlackBox\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PoisoningAttackBackdoor(PoisoningAttackBlackBox):\n \"\"\"\n Implementation of backdoor attacks introduced in Gu et al., 2017.\n\n Applies a number of backdoor perturbation functions and switches label to target label\n\n | Paper link: https://arxiv.org/abs/1708.06733\n \"\"\"\n\n attack_params = PoisoningAttackBlackBox.attack_params + [\"perturbation\"]\n _estimator_requirements = ()\n\n def __init__(self, perturbation: Callable | list[Callable]) -> None:\n \"\"\"\n Initialize a backdoor poisoning attack.\n\n :param perturbation: A single perturbation function or list of perturbation functions that modify input.\n \"\"\"\n super().__init__()\n self.perturbation = perturbation\n self._check_params()\n\n def poison(\n self, x: np.ndarray, y: np.ndarray | None = None, broadcast=False, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calls perturbation function on input x and returns the perturbed input and poison labels for the data.\n\n :param x: An array with the points that initialize attack points.\n :param y: The target labels for the attack.\n :param broadcast: Whether to broadcast single target label\n :return: An tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n if y is None: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n if broadcast:\n y_attack = np.broadcast_to(y, (x.shape[0], y.shape[0]))\n else:\n y_attack = np.copy(y)\n\n num_poison = len(x)\n if num_poison == 0: # pragma: no cover\n raise ValueError(\"Must input at least one poison point.\")\n poisoned = np.copy(x)\n\n if callable(self.perturbation):\n return self.perturbation(poisoned), y_attack\n\n for perturb in self.perturbation:\n poisoned = perturb(poisoned)\n\n return poisoned, y_attack\n\n def _check_params(self) -> None:\n if not (callable(self.perturbation) or all((callable(perturb) for perturb in self.perturbation))):\n raise ValueError(\"Perturbation must be a function or a list of functions.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/bullseye_polytope_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Bullseye Polytope clean-label attacks on Neural Networks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport time\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import PoisoningAttackWhiteBox\nfrom art.estimators import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.pytorch import PyTorchClassifier\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass BullseyePolytopeAttackPyTorch(PoisoningAttackWhiteBox):\n \"\"\"\n Implementation of Bullseye Polytope Attack by Aghakhani et al. (2020).\n \"Bullseye Polytope: A Scalable Clean-Label Poisoning Attack with Improved Transferability\"\n\n This implementation is based on UCSB's original code here: https://github.com/ucsb-seclab/BullseyePoison\n\n | Paper link: https://arxiv.org/abs/2005.00191\n \"\"\"\n\n attack_params = PoisoningAttackWhiteBox.attack_params + [\n \"target\",\n \"feature_layer\",\n \"opt\",\n \"max_iter\",\n \"learning_rate\",\n \"momentum\",\n \"decay_iter\",\n \"decay_coeff\",\n \"epsilon\",\n \"norm\",\n \"dropout\",\n \"endtoend\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin, PyTorchClassifier)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\" | list[\"CLASSIFIER_NEURALNETWORK_TYPE\"],\n target: np.ndarray,\n feature_layer: str | int | list[str | int],\n opt: str = \"adam\",\n max_iter: int = 4000,\n learning_rate: float = 4e-2,\n momentum: float = 0.9,\n decay_iter: int | list[int] = 10000,\n decay_coeff: float = 0.5,\n epsilon: float = 0.1,\n dropout: float = 0.3,\n net_repeat: int = 1,\n endtoend: bool = True,\n batch_size: int = 128,\n verbose: bool = True,\n ):\n \"\"\"\n Initialize a Feature Collision Clean-Label poisoning attack\n\n :param classifier: The proxy classifiers used for the attack. Can be a single classifier or list of classifiers\n with varying architectures.\n :param target: The target input(s) of shape (N, W, H, C) to misclassify at test time. Multiple targets will be\n averaged.\n :param feature_layer: The name(s) of the feature representation layer(s).\n :param opt: The optimizer to use for the attack. Can be 'adam' or 'sgd'\n :param max_iter: The maximum number of iterations for the attack.\n :param learning_rate: The learning rate of clean-label attack optimization.\n :param momentum: The momentum of clean-label attack optimization.\n :param decay_iter: Which iterations to decay the learning rate.\n Can be an integer (every N iterations) or list of integers [0, 500, 1500]\n :param decay_coeff: The decay coefficient of the learning rate.\n :param epsilon: The perturbation budget\n :param dropout: Dropout to apply while training\n :param net_repeat: The number of times to repeat prediction on each network\n :param endtoend: True for end-to-end training. False for transfer learning.\n :param batch_size: Batch size.\n :param verbose: Show progress bars.\n \"\"\"\n self.subsistute_networks: list[\"CLASSIFIER_NEURALNETWORK_TYPE\"] = (\n [classifier] if not isinstance(classifier, list) else classifier\n )\n\n super().__init__(classifier=self.subsistute_networks[0]) # type: ignore\n self.target = target\n self.opt = opt\n self.momentum = momentum\n self.decay_iter = decay_iter\n self.epsilon = epsilon\n self.dropout = dropout\n self.net_repeat = net_repeat\n self.endtoend = endtoend\n self.feature_layer = feature_layer\n self.learning_rate = learning_rate\n self.decay_coeff = decay_coeff\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.verbose = verbose\n self._check_params()\n\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Iteratively finds optimal attack points starting at values at x\n\n :param x: The base images to begin the poison process.\n :param y: Target label\n :return: An tuple holding the (poisoning examples, poisoning labels).\n \"\"\"\n import torch\n\n class PoisonBatch(torch.nn.Module):\n \"\"\"\n Implementing this to work with PyTorch optimizers.\n \"\"\"\n\n def __init__(self, base_list):\n super().__init__()\n base_batch = torch.stack(base_list, 0)\n self.poison = torch.nn.Parameter(base_batch.clone())\n\n def forward(self):\n \"\"\"Forward method.\"\"\"\n return self.poison\n\n base_tensor_list = [torch.from_numpy(sample).to(self.estimator.device) for sample in x]\n poison_batch = PoisonBatch([torch.from_numpy(np.copy(sample)).to(self.estimator.device) for sample in x])\n opt_method = self.opt.lower()\n\n if opt_method == \"sgd\": # pragma: no cover\n logger.info(\"Using SGD to craft poison samples\")\n optimizer = torch.optim.SGD(poison_batch.parameters(), lr=self.learning_rate, momentum=self.momentum)\n elif opt_method == \"adam\":\n logger.info(\"Using Adam to craft poison samples\")\n optimizer = torch.optim.Adam( # type: ignore\n poison_batch.parameters(), lr=self.learning_rate, betas=(self.momentum, 0.999)\n )\n\n base_tensor_batch = torch.stack(base_tensor_list, 0)\n base_range01_batch = base_tensor_batch\n\n # Because we have turned on DP for the substitute networks,\n # the target image's feature becomes random.\n # We can try enforcing the convex polytope in one of the multiple realizations of the feature,\n # but empirically one realization is enough.\n target_feat_list = []\n # Coefficients for the convex combination.\n # Initializing from the coefficients of last step gives faster convergence.\n s_init_coeff_list = []\n n_poisons = len(x)\n s_coeff: \"torch.Tensor\" | list[\"torch.Tensor\"]\n for _, net in enumerate(self.subsistute_networks):\n # End to end training\n if self.endtoend:\n if isinstance(self.feature_layer, list):\n block_feats = []\n for layer in self.feature_layer:\n activations = net.get_activations(x, layer=layer, batch_size=self.batch_size, framework=True)\n if activations is not None:\n block_feats += [torch.stack([feat.detach() for feat in activations], 0)]\n else: # pragma: no cover\n raise ValueError(\"Activations are None.\")\n else:\n layer_2: int | str = self.feature_layer\n activations = net.get_activations(x, layer=layer_2, batch_size=self.batch_size, framework=True)\n if activations is not None:\n block_feats = [feat.detach() for feat in activations]\n else: # pragma: no cover\n raise ValueError(\"Activations are None.\")\n target_feat_list.append(block_feats)\n s_coeff = [\n torch.ones(n_poisons, 1).to(self.estimator.device) / n_poisons for _ in range(len(block_feats))\n ]\n else: # pragma: no cover\n if isinstance(self.feature_layer, list):\n raise NotImplementedError\n layer_3: int | str = self.feature_layer\n activations = net.get_activations(x, layer=layer_3, batch_size=self.batch_size, framework=True)\n if activations is not None:\n target_feat_list.append(activations.detach()) # type: ignore\n else:\n raise ValueError(\"Activations are None.\")\n s_coeff = torch.ones(n_poisons, 1).to(self.estimator.device) / n_poisons\n\n s_init_coeff_list.append(s_coeff)\n\n for ite in trange(self.max_iter):\n if ite % self.decay_iter == 0 and ite != 0:\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] *= self.decay_coeff\n print(f\"{time.strftime('%Y-%m-%d %H:%M:%S')} Iteration {ite}, Adjusted lr to {self.learning_rate:.2e}\")\n\n poison_batch.zero_grad()\n total_loss = loss_from_center(\n self.subsistute_networks,\n target_feat_list,\n poison_batch,\n self.net_repeat,\n self.endtoend,\n self.feature_layer,\n )\n total_loss.backward()\n optimizer.step()\n\n # clip the perturbations into the range\n perturb_range01 = torch.clamp((poison_batch.poison.data - base_tensor_batch), -self.epsilon, self.epsilon)\n perturbed_range01 = torch.clamp(\n base_range01_batch.data + perturb_range01.data,\n self.estimator.clip_values[0],\n self.estimator.clip_values[1],\n )\n poison_batch.poison.data = perturbed_range01\n\n if y is None: # pragma: no cover\n raise ValueError(\"You must pass in the target label as y\")\n\n return get_poison_tuples(poison_batch, y)\n\n def _check_params(self) -> None:\n if self.learning_rate <= 0:\n raise ValueError(\"Learning rate must be strictly positive\")\n\n if self.max_iter < 1:\n raise ValueError(\"Value of max_iter at least 1\")\n\n if not isinstance(self.feature_layer, (str, int, list)):\n raise TypeError(\"Feature layer should be a string or int or list of string or int\")\n\n if self.opt.lower() not in [\"adam\", \"sgd\"]:\n raise ValueError(\"Optimizer must be 'adam' or 'sgd'\")\n\n if not 0 <= self.momentum <= 1:\n raise ValueError(\"Momentum must be between 0 and 1\")\n\n if isinstance(self.decay_iter, int) and self.decay_iter < 0:\n raise ValueError(\"decay_iter must be at least 0\")\n\n if isinstance(self.decay_iter, list) and not all(\n (isinstance(decay_iter, int) and decay_iter > 0 for decay_iter in self.decay_iter)\n ):\n raise ValueError(\"decay_iter is not a list of positive integers\")\n\n if self.epsilon <= 0:\n raise ValueError(\"epsilon must be at least 0\")\n\n if not 0 <= self.dropout <= 1:\n raise ValueError(\"dropout must be between 0 and 1\")\n\n if self.net_repeat < 1:\n raise ValueError(\"net_repeat must be at least 1\")\n\n if isinstance(self.feature_layer, list):\n for layer in self.feature_layer:\n if isinstance(layer, int):\n if not 0 <= layer < len(self.estimator.layer_names):\n raise ValueError(\"feature_layer is not list of positive integers\")\n elif not isinstance(layer, str):\n raise ValueError(\"feature_layer is not list of strings\")\n\n if isinstance(self.feature_layer, int):\n if not 0 <= self.feature_layer < len(self.estimator.layer_names):\n raise ValueError(\"feature_layer is not positive integer\")\n\n if not 0 <= self.decay_coeff <= 1:\n raise ValueError(\"Decay coefficient must be between zero and one\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"batch_size must be a positive integer\")\n\n\ndef get_poison_tuples(poison_batch, poison_label):\n \"\"\"\n Includes the labels\n \"\"\"\n poison = [\n poison_batch.poison.data[num_p].unsqueeze(0).detach().cpu().numpy()\n for num_p in range(poison_batch.poison.size(0))\n ]\n return np.vstack(poison), poison_label\n\n\ndef loss_from_center(\n subs_net_list, target_feat_list, poison_batch, net_repeat, end2end, feature_layer\n) -> \"torch.Tensor\":\n \"\"\"\n Calculate loss from center.\n \"\"\"\n import torch\n\n if end2end:\n loss = torch.tensor(0.0)\n for net, center_feats in zip(subs_net_list, target_feat_list):\n poisons_feats: list[float] | \"torch.Tensor\" | np.ndarray\n if net_repeat > 1:\n poisons_feats_repeats = [\n net.get_activations(poison_batch(), layer=feature_layer, framework=True) for _ in range(net_repeat)\n ]\n block_num = len(poisons_feats_repeats[0])\n poisons_feats = []\n for block_idx in range(block_num):\n poisons_feats.append(\n sum([poisons_feat_r[block_idx] for poisons_feat_r in poisons_feats_repeats]) / net_repeat\n )\n elif net_repeat == 1:\n if isinstance(feature_layer, list):\n poisons_feats = [\n torch.flatten(\n net.get_activations(poison_batch(), layer=layer, framework=True), 0 # type: ignore\n )\n for layer in feature_layer\n ]\n else: # pragma: no cover\n poisons_feats = net.get_activations(poison_batch(), layer=feature_layer, framework=True)\n else: # pragma: no cover\n assert False, f\"net_repeat set to {net_repeat}\"\n\n net_loss = torch.tensor(0.0)\n for pfeat, cfeat in zip(poisons_feats, center_feats):\n diff = torch.mean(pfeat, dim=0) - cfeat\n diff_norm = torch.norm(diff, dim=0)\n cfeat_norm = torch.norm(cfeat, dim=0)\n diff_norm = diff_norm / cfeat_norm\n net_loss += torch.mean(diff_norm)\n loss += net_loss / len(center_feats)\n loss = loss / len(subs_net_list)\n\n else: # pragma: no cover\n loss = torch.tensor(0.0)\n for net, center in zip(subs_net_list, target_feat_list):\n poisons_list = [\n net.get_activations(poison_batch(), layer=feature_layer, framework=True) for _ in range(net_repeat)\n ]\n poisons = torch.tensor(sum(poisons_list) / len(poisons_list))\n\n diff_2 = torch.mean(poisons, dim=0) - center\n diff_norm = torch.norm(diff_2, dim=1) / torch.norm(center, dim=1)\n loss += torch.mean(diff_norm)\n\n loss = loss / len(subs_net_list)\n\n return loss\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/clean_label_backdoor_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Clean Label Backdoor Attacks to poison data used in ML models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import PoisoningAttackBlackBox\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PoisoningAttackCleanLabelBackdoor(PoisoningAttackBlackBox):\n \"\"\"\n Implementation of Clean-Label Backdoor Attack introduced in Turner et al., 2018.\n\n Applies a number of backdoor perturbation functions and does not change labels.\n\n | Paper link: https://people.csail.mit.edu/madry/lab/cleanlabel.pdf\n \"\"\"\n\n attack_params = PoisoningAttackBlackBox.attack_params + [\n \"backdoor\",\n \"proxy_classifier\",\n \"target\",\n \"pp_poison\",\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"max_iter\",\n \"num_random_init\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n backdoor: PoisoningAttackBackdoor,\n proxy_classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n target: np.ndarray,\n pp_poison: float = 0.33,\n norm: int | float | str = np.inf,\n eps: float = 0.3,\n eps_step: float = 0.1,\n max_iter: int = 100,\n num_random_init: int = 0,\n ) -> None:\n \"\"\"\n Creates a new Clean Label Backdoor poisoning attack\n\n :param backdoor: the backdoor chosen for this attack\n :param proxy_classifier: the classifier for this attack ideally it solves the same or similar classification\n task as the original classifier\n :param target: The target label to poison\n :param pp_poison: The percentage of the data to poison. Note: Only data within the target label is poisoned\n :param norm: The norm of the adversarial perturbation supporting \"inf\", np.inf, 1 or 2.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: The maximum number of iterations.\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting\n at the original input.\n \"\"\"\n super().__init__()\n self.backdoor = backdoor\n self.proxy_classifier = proxy_classifier\n self.target = target\n self.pp_poison = pp_poison\n self.attack = ProjectedGradientDescent(\n proxy_classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=max_iter,\n targeted=False,\n num_random_init=num_random_init,\n )\n self._check_params()\n\n def poison(\n self, x: np.ndarray, y: np.ndarray | None = None, broadcast: bool = True, **kwargs\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calls perturbation function on input x and returns the perturbed input and poison labels for the data.\n\n :param x: An array with the points that initialize attack points.\n :param y: The target labels for the attack.\n :param broadcast: whether to broadcast single target label\n :return: An tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n data = np.copy(x)\n estimated_labels = self.proxy_classifier.predict(data) if y is None else np.copy(y)\n\n # Selected target indices to poison\n all_indices = np.arange(len(data))\n target_indices = all_indices[np.all(estimated_labels == self.target, axis=1)]\n num_poison = int(self.pp_poison * len(target_indices))\n selected_indices = np.random.choice(target_indices, num_poison)\n\n # Run untargeted PGD on selected points, making it hard to classify correctly\n perturbed_input = self.attack.generate(data[selected_indices])\n no_change_detected = np.array(\n [\n np.all(data[selected_indices][poison_idx] == perturbed_input[poison_idx])\n for poison_idx in range(len(perturbed_input))\n ]\n )\n\n if any(no_change_detected): # pragma: no cover\n logger.warning(\"Perturbed input is the same as original data after PGD. Check params.\")\n idx_no_change = np.arange(len(no_change_detected))[no_change_detected]\n logger.warning(\"%d indices without change: %s\", len(idx_no_change), idx_no_change)\n\n # Add backdoor and poison with the same label\n poisoned_input, _ = self.backdoor.poison(perturbed_input, self.target, broadcast=broadcast)\n data[selected_indices] = poisoned_input\n\n return data, estimated_labels\n\n def _check_params(self) -> None:\n if not isinstance(self.backdoor, PoisoningAttackBackdoor):\n raise ValueError(\"Backdoor must be of type PoisoningAttackBackdoor\")\n if not isinstance(self.attack, ProjectedGradientDescent):\n raise ValueError(\"There was an issue creating the PGD attack\")\n if not 0 < self.pp_poison < 1:\n raise ValueError(\"pp_poison must be between 0 and 1\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/feature_collision_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements clean-label attacks on Neural Networks.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom functools import reduce\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import PoisoningAttackWhiteBox\nfrom art.estimators import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.pytorch import PyTorchClassifier\n\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass FeatureCollisionAttack(PoisoningAttackWhiteBox):\n \"\"\"\n Close implementation of Feature Collision Poisoning Attack by Shafahi, Huang, et al. (2018).\n \"Poison Frogs! Targeted Clean-Label Poisoning Attacks on Neural Networks\"\n\n This implementation dynamically calculates the dimension of the feature layer, and doesn't hardcode this\n value to 2048 as done in the paper. Thus, we recommend using larger values for the similarity_coefficient.\n\n | Paper link: https://arxiv.org/abs/1804.00792\n \"\"\"\n\n attack_params = PoisoningAttackWhiteBox.attack_params + [\n \"target\",\n \"feature_layer\",\n \"learning_rate\",\n \"decay_coeff\",\n \"stopping_tol\",\n \"obj_threshold\",\n \"num_old_obj\",\n \"max_iter\",\n \"similarity_coeff\",\n \"watermark\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n target: np.ndarray,\n feature_layer: str | int,\n learning_rate: float = 500 * 255.0,\n decay_coeff: float = 0.5,\n stopping_tol: float = 1e-10,\n obj_threshold: float | None = None,\n num_old_obj: int = 40,\n max_iter: int = 120,\n similarity_coeff: float = 256.0,\n watermark: float | None = None,\n verbose: bool = True,\n ):\n \"\"\"\n Initialize a Feature Collision Clean-Label poisoning attack\n\n :param classifier: A trained neural network classifier.\n :param target: The target input to misclassify at test time.\n :param feature_layer: The name of the feature representation layer.\n :param learning_rate: The learning rate of clean-label attack optimization.\n :param decay_coeff: The decay coefficient of the learning rate.\n :param stopping_tol: Stop iterations after changes in attacks in less than this threshold.\n :param obj_threshold: Stop iterations after changes in objectives values are less than this threshold.\n :param num_old_obj: The number of old objective values to store.\n :param max_iter: The maximum number of iterations for the attack.\n :param similarity_coeff: The maximum number of iterations for the attack.\n :param watermark: Whether The opacity of the watermarked target image.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(classifier=classifier) # type: ignore\n self.target = target\n self.feature_layer = feature_layer\n self.learning_rate = learning_rate\n self.decay_coeff = decay_coeff\n self.stopping_tol = stopping_tol\n self.obj_threshold = obj_threshold\n self.num_old_obj = num_old_obj\n self.max_iter = max_iter\n self.similarity_coeff = similarity_coeff\n self.watermark = watermark\n self.verbose = verbose\n self._check_params()\n\n if isinstance(self.estimator, PyTorchClassifier):\n self.target_feature_rep = self.estimator.get_activations(self.target, self.feature_layer, 1, framework=True)\n self.poison_feature_rep = self.estimator.get_activations(self.target, self.feature_layer, 1, framework=True)\n else:\n raise ValueError(\"Type of estimator currently not supported.\")\n self.attack_loss = tensor_norm(self.poison_feature_rep - self.target_feature_rep)\n\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Iteratively finds optimal attack points starting at values at x\n\n :param x: The base images to begin the poison process.\n :param y: Not used in this attack (clean-label).\n :return: A tuple holding the (poisoning examples, poisoning labels).\n \"\"\"\n num_poison = len(x)\n final_attacks = []\n if num_poison == 0: # pragma: no cover\n raise ValueError(\"Must input at least one poison point\")\n target_features = self.estimator.get_activations(self.target, self.feature_layer, 1)\n for init_attack in x:\n old_attack = np.expand_dims(np.copy(init_attack), axis=0)\n poison_features = self.estimator.get_activations(old_attack, self.feature_layer, 1)\n old_objective = self.objective(poison_features, target_features, init_attack, old_attack)\n last_m_objectives = [old_objective]\n for i in trange(self.max_iter, desc=\"Feature collision\", disable=not self.verbose):\n # forward step\n new_attack = self.forward_step(old_attack)\n\n # backward step\n new_attack = self.backward_step(np.expand_dims(init_attack, axis=0), poison_features, new_attack)\n\n rel_change_val = np.linalg.norm(new_attack - old_attack) / np.linalg.norm(new_attack)\n if ( # pragma: no cover\n rel_change_val < self.stopping_tol or self.obj_threshold and old_objective <= self.obj_threshold\n ):\n logger.info(\"stopped after %d iterations due to small changes\", i)\n break\n\n np.expand_dims(new_attack, axis=0)\n new_feature_rep = self.estimator.get_activations(new_attack, self.feature_layer, 1)\n new_objective = self.objective(new_feature_rep, target_features, init_attack, new_attack)\n\n avg_of_last_m = sum(last_m_objectives) / float(min(self.num_old_obj, i + 1))\n\n # Increasing objective means then learning rate is too big. Chop it, and throw out the latest iteration\n if new_objective >= avg_of_last_m and (i % self.num_old_obj / 2 == 0):\n self.learning_rate *= self.decay_coeff\n else: # pragma: no cover\n old_attack = new_attack\n old_objective = new_objective\n\n if i < self.num_old_obj - 1:\n last_m_objectives.append(new_objective)\n else: # pragma: no cover\n # first remove the oldest obj then append the new obj\n del last_m_objectives[0]\n last_m_objectives.append(new_objective)\n\n # Watermarking\n watermark = self.watermark * self.target if self.watermark else 0\n final_poison = np.clip(old_attack + watermark, *self.estimator.clip_values)\n final_attacks.append(final_poison)\n\n return np.vstack(final_attacks), self.estimator.predict(x)\n\n def forward_step(self, poison: np.ndarray) -> np.ndarray:\n \"\"\"\n Forward part of forward-backward splitting algorithm.\n\n :param poison: the current poison samples.\n :return: poison example closer in feature representation to target space.\n \"\"\"\n if isinstance(self.estimator, PyTorchClassifier):\n attack_grad = self.estimator.custom_loss_gradient(self.attack_loss, poison, self.target, self.feature_layer)\n else:\n raise ValueError(\"The type of the estimator is not supported.\")\n\n poison -= self.learning_rate * attack_grad[0]\n\n return poison\n\n def backward_step(self, base: np.ndarray, feature_rep: np.ndarray, poison: np.ndarray) -> np.ndarray:\n \"\"\"\n Backward part of forward-backward splitting algorithm\n\n :param base: The base image that the poison was initialized with.\n :param feature_rep: Numpy activations at the target layer.\n :param poison: The current poison samples.\n :return: Poison example closer in feature representation to target space.\n \"\"\"\n num_features = reduce(lambda x, y: x * y, base.shape)\n dim_features = feature_rep.shape[-1]\n beta = self.similarity_coeff * (dim_features / num_features) ** 2\n poison = (poison + self.learning_rate * beta * base) / (1 + beta * self.learning_rate)\n low, high = self.estimator.clip_values\n return np.clip(poison, low, high)\n\n def objective(\n self, poison_feature_rep: np.ndarray, target_feature_rep: np.ndarray, base_image: np.ndarray, poison: np.ndarray\n ) -> float:\n \"\"\"\n Objective function of the attack\n\n :param poison_feature_rep: The numpy activations of the poison image.\n :param target_feature_rep: The numpy activations of the target image.\n :param base_image: The initial image used to poison.\n :param poison: The current poison image.\n :return: The objective of the optimization.\n \"\"\"\n num_features = base_image.size\n num_activations = poison_feature_rep.size\n beta = self.similarity_coeff * (num_activations / num_features) ** 2\n return float(\n np.linalg.norm(poison_feature_rep - target_feature_rep) + beta * np.linalg.norm(poison - base_image)\n )\n\n def _check_params(self) -> None:\n if self.learning_rate <= 0:\n raise ValueError(\"Learning rate must be strictly positive\")\n\n if not isinstance(self.feature_layer, (str, int)):\n raise TypeError(\"Feature layer should be a string or int\")\n\n if self.decay_coeff <= 0:\n raise ValueError(\"Decay coefficient must be positive\")\n\n if self.stopping_tol <= 0:\n raise ValueError(\"Stopping tolerance must be positive\")\n\n if self.obj_threshold and self.obj_threshold <= 0:\n raise ValueError(\"Objective threshold must be positive\")\n\n if self.num_old_obj <= 0:\n raise ValueError(\"Number of old stored objectives must be positive\")\n\n if self.max_iter <= 0:\n raise ValueError(\"Maximum number of iterations must be 1 or larger\")\n\n if self.watermark and not (isinstance(self.watermark, float) and 0 <= self.watermark < 1):\n raise ValueError(\"Watermark must be between 0 and 1\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n\ndef get_class_name(obj: object) -> str:\n \"\"\"\n Get the full class name of an object.\n\n :param obj: A Python object.\n :return: A qualified class name.\n \"\"\"\n module = obj.__class__.__module__\n\n if module is None or module == str.__class__.__module__:\n return obj.__class__.__name__\n\n return module + \".\" + obj.__class__.__name__\n\n\ndef tensor_norm(tensor, norm_type: int | float | str = 2): # pylint: disable=inconsistent-return-statements\n \"\"\"\n Compute the norm of a tensor.\n\n :param tensor: A tensor from a supported ART neural network.\n :param norm_type: Order of the norm.\n :return: A tensor with the norm applied.\n \"\"\"\n torch_tensor_types = (\"torch.Tensor\", \"torch.float\", \"torch.double\", \"torch.long\")\n supported_types = torch_tensor_types\n tensor_type = get_class_name(tensor)\n if tensor_type not in supported_types: # pragma: no cover\n raise TypeError(\"Tensor type `\" + tensor_type + \"` is not supported\")\n\n if tensor_type in torch_tensor_types: # pragma: no cover\n import torch\n\n return torch.norm\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/gradient_matching_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Gradient Matching clean-label attacks (a.k.a. Witches' Brew) on Neural Networks.\n\n| Paper link: https://arxiv.org/abs/2009.02276\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange, tqdm\n\nfrom art.attacks.attack import Attack\nfrom art.estimators import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nif TYPE_CHECKING:\n\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass GradientMatchingAttack(Attack):\n \"\"\"\n Implementation of Gradient Matching Attack by Geiping et al. (2020).\n \"Witches' Brew: Industrial Scale Data Poisoning via Gradient Matching\"\n\n | Paper link: https://arxiv.org/abs/2009.02276\n \"\"\"\n\n attack_params = Attack.attack_params + [\n \"percent_poison\",\n \"max_trials\",\n \"max_epochs\",\n \"learning_rate_schedule\",\n \"epsilon\",\n \"clip_values\",\n \"batch_size\",\n \"verbose\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n percent_poison: float,\n epsilon: float = 0.1,\n max_trials: int = 8,\n max_epochs: int = 250,\n learning_rate_schedule: tuple[list[float], list[int]] = ([1e-1, 1e-2, 1e-3, 1e-4], [100, 150, 200, 220]),\n batch_size: int = 128,\n clip_values: tuple[float, float] = (0, 1.0),\n verbose: int = 1,\n ):\n \"\"\"\n Initialize a Gradient Matching Clean-Label poisoning attack (Witches' Brew).\n\n :param classifier: The proxy classifier used for the attack.\n :param percent_poison: The ratio of samples to poison among x_train, with range [0,1].\n :param epsilon: The L-inf perturbation budget.\n :param max_trials: The maximum number of restarts to optimize the poison.\n :param max_epochs: The maximum number of epochs to optimize the train per trial.\n :param learning_rate_schedule: The learning rate schedule to optimize the poison.\n A list of (learning rate, epoch) pairs. The learning rate is used\n if the current epoch is less than the specified epoch.\n :param batch_size: Batch size.\n :param clip_values: The range of the input features to the classifier.\n :param verbose: Show progress bars.\n \"\"\"\n self.substitute_classifier = classifier\n\n super().__init__(classifier)\n self.percent_poison = percent_poison\n self.epsilon = epsilon\n self.learning_rate_schedule = learning_rate_schedule\n self.max_trials = max_trials\n self.max_epochs = max_epochs\n self.batch_size = batch_size\n self.clip_values = clip_values\n self.initial_epoch = 0\n\n if verbose is True:\n verbose = 1\n self.verbose = verbose\n self._check_params()\n\n def _initialize_poison(\n self, x_trigger: np.ndarray, y_trigger: np.ndarray, x_poison: np.ndarray, y_poison: np.ndarray\n ):\n \"\"\"\n Initialize poison noises to be optimized.\n\n :param x_trigger: A list of samples to use as triggers.\n :param y_trigger: A list of target classes to classify the triggers into.\n :param x_train: A list of training data to poison a portion of.\n :param y_train: A list of labels for x_train.\n \"\"\"\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n initializer = self._initialize_poison_pytorch\n else:\n raise NotImplementedError(\"GradientMatchingAttack is currently implemented only for PyTorch.\")\n\n return initializer(x_trigger, y_trigger, x_poison, y_poison)\n\n def _finish_poison_pytorch(self):\n \"\"\"\n Releases any resource and revert back unwanted change to the model.\n \"\"\"\n if self.model_trainable:\n self.substitute_classifier.model.train()\n else:\n self.substitute_classifier.model.eval()\n\n def _initialize_poison_pytorch(\n self,\n x_trigger: np.ndarray,\n y_trigger: np.ndarray,\n x_poison: np.ndarray,\n y_poison: np.ndarray, # pylint: disable=unused-argument\n ):\n import torch\n from torch import nn\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n classifier = self.substitute_classifier\n else:\n raise Exception(\"This method requires `PyTorchClassifier` as `substitute_classifier`'s type\")\n\n num_poison = len(x_poison)\n len_noise = np.prod(x_poison.shape[1:])\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n self.model_trainable = self.substitute_classifier.model.training\n self.substitute_classifier.model.eval()\n\n def _weight_grad(classifier: PyTorchClassifier, x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:\n classifier.model.zero_grad()\n y = classifier.model(x)\n loss_ = classifier.loss(y, target)\n gradspred = torch.autograd.grad(\n loss_, list(classifier.model.parameters()), create_graph=True, retain_graph=True\n )\n d_w = torch.cat([w.flatten() for w in gradspred])\n d_w_norm = d_w / torch.sqrt(torch.sum(torch.square(d_w)))\n return d_w_norm\n\n class NoiseEmbedding(nn.Module):\n \"\"\"\n Gradient matching noise layer.\n \"\"\"\n\n def __init__(self, num_poison: int, len_noise: int, epsilon: float, clip_values: tuple[float, float]):\n super().__init__()\n\n self.embedding_layer = nn.Embedding(num_poison, len_noise)\n torch.nn.init.normal_(self.embedding_layer.weight, std=epsilon * 0.0001)\n self.epsilon = epsilon\n self.clip_values = clip_values\n\n def forward(self, input_poison: torch.Tensor, input_indices: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Applies the noise variable to the input.\n Input to the model must match its index as the noise is specific to the input.\n \"\"\"\n embeddings = self.embedding_layer(input_indices).to(device)\n embeddings = torch.tanh(embeddings) * self.epsilon\n embeddings = embeddings.view(input_poison.shape)\n\n input_noised = input_poison + embeddings\n input_noised = torch.clip(\n input_noised, self.clip_values[0], self.clip_values[1]\n ) # Make sure the poisoned samples are in a valid range.\n\n return input_noised\n\n class BackdoorModel(nn.Module):\n \"\"\"\n Backdoor model computing the B loss.\n \"\"\"\n\n def __init__(\n self,\n gradient_matching: GradientMatchingAttack,\n classifier: PyTorchClassifier,\n epsilon,\n num_poison,\n len_noise,\n min_,\n max_,\n ):\n super().__init__()\n self.gradient_matching = gradient_matching\n self.classifier = classifier\n self.noise_embedding = NoiseEmbedding(num_poison, len_noise, epsilon, (min_, max_))\n self.cos = nn.CosineSimilarity(dim=-1)\n\n def forward(\n self, x: torch.Tensor, indices_poison: torch.Tensor, y: torch.Tensor, grad_ws_norm: torch.Tensor\n ) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Applies the poison noise and compute the loss with respect to the target gradient.\n \"\"\"\n poisoned_samples = self.noise_embedding(x, indices_poison)\n d_w2_norm = _weight_grad(self.classifier, poisoned_samples, y)\n d_w2_norm.requires_grad_(True)\n B_score = 1 - self.cos(grad_ws_norm, d_w2_norm) # pylint: disable=invalid-name\n return B_score, poisoned_samples\n\n self.grad_ws_norm = _weight_grad(\n classifier,\n torch.tensor(x_trigger, device=device, dtype=torch.float32),\n torch.tensor(y_trigger, device=device),\n ).detach()\n self.grad_ws_norm.requires_grad_(False)\n self.backdoor_model = BackdoorModel(\n self,\n classifier,\n self.epsilon,\n num_poison,\n len_noise,\n self.clip_values[0],\n self.clip_values[1],\n ).to(device)\n self.optimizer = torch.optim.Adam(self.backdoor_model.noise_embedding.embedding_layer.parameters(), lr=1)\n\n class PredefinedLRSchedule:\n \"\"\"\n Use a preset learning rate based on the current training epoch.\n \"\"\"\n\n def __init__(self, learning_rates: list[float], milestones: list[int]):\n self.schedule = list(zip(milestones, learning_rates))\n\n def __call__(self, step: int) -> float:\n lr_prev = self.schedule[0][1]\n for m, learning_rate in self.schedule:\n if step < m:\n return lr_prev\n lr_prev = learning_rate\n return lr_prev\n\n def get_config(self) -> dict:\n \"\"\"\n returns a dictionary of parameters.\n \"\"\"\n return {\"schedule\": self.schedule}\n\n self.lr_schedule = torch.optim.lr_scheduler.LambdaLR(\n self.optimizer, PredefinedLRSchedule(*self.learning_rate_schedule)\n )\n\n def poison(\n self, x_trigger: np.ndarray, y_trigger: np.ndarray, x_train: np.ndarray, y_train: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Optimizes a portion of poisoned samples from x_train to make a model classify x_target\n as y_target by matching the gradients.\n\n :param x_trigger: A list of samples to use as triggers.\n :param y_trigger: A list of target classes to classify the triggers into.\n :param x_train: A list of training data to poison a portion of.\n :param y_train: A list of labels for x_train.\n :return: A list of poisoned samples, and y_train.\n \"\"\"\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n poisoner = self._poison__pytorch\n finish_poisoning = self._finish_poison_pytorch\n else:\n raise NotImplementedError(\"GradientMatchingAttack is currently implemented only for Pytorch.\")\n\n # Choose samples to poison.\n x_train = np.copy(x_train)\n y_train = np.copy(y_train)\n if len(np.shape(y_trigger)) == 2: # dense labels\n classes_target = set(np.argmax(y_trigger, axis=-1))\n else: # sparse labels\n classes_target = set(y_trigger)\n num_poison_samples = int(self.percent_poison * len(x_train))\n\n # Try poisoning num_trials times and choose the best one.\n best_B = np.finfo(np.float32).max # pylint: disable=invalid-name\n best_x_poisoned = None\n best_indices_poison = None\n\n if len(np.shape(y_train)) == 2:\n y_train_classes = np.argmax(y_train, axis=-1)\n else:\n y_train_classes = y_train\n for _ in trange(self.max_trials):\n indices_poison = np.random.permutation(np.where([y in classes_target for y in y_train_classes])[0])[\n :num_poison_samples\n ]\n x_poison = x_train[indices_poison]\n y_poison = y_train[indices_poison]\n self._initialize_poison(x_trigger, y_trigger, x_poison, y_poison)\n x_poisoned, B_ = poisoner(x_poison, y_poison) # pylint: disable=invalid-name\n finish_poisoning()\n B_ = np.mean(B_) # Averaging B losses from multiple batches. # pylint: disable=invalid-name\n if B_ < best_B:\n best_B = B_ # pylint: disable=invalid-name\n best_x_poisoned = x_poisoned\n best_indices_poison = indices_poison\n\n if self.verbose > 0:\n print(\"Best B-score:\", best_B)\n x_train[best_indices_poison] = best_x_poisoned\n return x_train, y_train # y_train has not been modified.\n\n def _poison__pytorch(self, x_poison: np.ndarray, y_poison: np.ndarray) -> tuple[Any, Any]:\n \"\"\"\n Optimize the poison by matching the gradient within the perturbation budget.\n\n :param x_poison: List of samples to poison.\n :param y_poison: List of the labels for x_poison.\n :return: A pair of poisoned samples, B-score (cosine similarity of the gradients).\n \"\"\"\n\n import torch\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n class PoisonDataset(torch.utils.data.Dataset):\n \"\"\"\n Iterator for a dataset to poison.\n \"\"\"\n\n def __init__(self, x: np.ndarray, y: np.ndarray):\n self.len = x.shape[0]\n self.x = torch.as_tensor(x, dtype=torch.float)\n self.y = torch.as_tensor(y)\n\n def __getitem__(self, index):\n return self.x[index], torch.as_tensor([index]), self.y[index]\n\n def __len__(self):\n return self.len\n\n trainloader = torch.utils.data.DataLoader(\n PoisonDataset(x_poison, y_poison), batch_size=self.batch_size, shuffle=False, num_workers=1\n )\n\n epoch_iterator = (\n trange(self.initial_epoch, self.max_epochs)\n if self.verbose > 0\n else range(self.initial_epoch, self.max_epochs)\n )\n for _ in epoch_iterator:\n batch_iterator = tqdm(trainloader) if isinstance(self.verbose, int) and self.verbose >= 2 else trainloader\n sum_loss = 0\n count = 0\n for x, indices, y in batch_iterator:\n x = x.to(device)\n y = y.to(device)\n indices = indices.to(device)\n self.backdoor_model.zero_grad()\n loss, poisoned_samples = self.backdoor_model(x, indices, y, self.grad_ws_norm)\n loss.backward()\n self.backdoor_model.noise_embedding.embedding_layer.weight.grad.sign_() # type: ignore\n self.optimizer.step()\n sum_loss += loss.clone().cpu().detach().numpy()\n count += 1\n if self.verbose > 0:\n epoch_iterator.set_postfix(loss=sum_loss / count) # type: ignore\n self.lr_schedule.step()\n\n B_sum = 0 # pylint: disable=invalid-name\n count = 0\n all_poisoned_samples = []\n self.backdoor_model.eval()\n poisonloader = torch.utils.data.DataLoader(\n PoisonDataset(x_poison, y_poison), batch_size=self.batch_size, shuffle=False, num_workers=1\n )\n for x, indices, y in poisonloader:\n x = x.to(device)\n y = y.to(device)\n indices = indices.to(device)\n B, poisoned_samples = self.backdoor_model(x, indices, y, self.grad_ws_norm) # pylint: disable=invalid-name\n all_poisoned_samples.append(poisoned_samples.detach().cpu().numpy())\n B_sum += B.detach().cpu().numpy() # pylint: disable=invalid-name\n count += 1\n return np.concatenate(all_poisoned_samples, axis=0), B_sum / count\n\n def _check_params(self) -> None:\n if not isinstance(self.learning_rate_schedule, tuple) or len(self.learning_rate_schedule) != 2:\n raise ValueError(\"learning_rate_schedule must be a pair of a list of learning rates and a list of epochs\")\n\n if self.percent_poison > 1 or self.percent_poison < 0:\n raise ValueError(\"percent_poison must be in [0, 1]\")\n\n if self.max_epochs < 1:\n raise ValueError(\"max_epochs must be positive\")\n\n if self.max_trials < 1:\n raise ValueError(\"max_trials must be positive\")\n\n if not isinstance(self.clip_values, tuple) or len(self.clip_values) != 2:\n raise ValueError(\"clip_values must be a pair (min, max) of floats\")\n\n if self.epsilon <= 0:\n raise ValueError(\"epsilon must be nonnegative\")\n\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"batch_size must be a positive integer\")\n\n if (\n isinstance(self.verbose, int)\n and self.verbose < 0\n or not isinstance(self.verbose, int)\n and not isinstance(self.verbose, bool)\n ):\n raise ValueError(\"verbose must be nonnegative integer or Boolean\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/poisoning_attack_svm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements poisoning attacks on Support Vector Machines.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import PoisoningAttackWhiteBox\nfrom art.estimators.classification.scikitlearn import ScikitlearnSVC\nfrom art.utils import compute_success\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PoisoningAttackSVM(PoisoningAttackWhiteBox):\n \"\"\"\n Close implementation of poisoning attack on Support Vector Machines (SVM) by Biggio et al.\n\n | Paper link: https://arxiv.org/pdf/1206.6389.pdf\n \"\"\"\n\n attack_params = PoisoningAttackWhiteBox.attack_params + [\n \"classifier\",\n \"step\",\n \"eps\",\n \"x_train\",\n \"y_train\",\n \"x_val\",\n \"y_val\",\n \"max_iter\",\n \"verbose\",\n ]\n _estimator_requirements = (ScikitlearnSVC,)\n\n def __init__(\n self,\n classifier: \"ScikitlearnSVC\",\n step: float,\n eps: float,\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_val: np.ndarray,\n y_val: np.ndarray,\n max_iter: int,\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Initialize an SVM poisoning attack.\n\n :param classifier: A trained :class:`.ScikitlearnSVC` classifier.\n :param step: The step size of the classifier.\n :param eps: The minimum difference in loss before convergence of the classifier.\n :param x_train: The training data used for classification.\n :param y_train: The training labels used for classification.\n :param x_val: The validation data used to test the attack.\n :param y_val: The validation labels used to test the attack.\n :param max_iter: The maximum number of iterations for the attack.\n :raises `NotImplementedError`, `TypeError`: If the argument classifier has the wrong type.\n :param verbose: Show progress bars.\n \"\"\"\n\n from sklearn.svm import LinearSVC, SVC\n\n super().__init__(classifier=classifier)\n\n if isinstance(self.estimator.model, LinearSVC):\n self._estimator = ScikitlearnSVC(\n model=SVC(C=self.estimator.model.C, kernel=\"linear\"),\n clip_values=self.estimator.clip_values,\n )\n self.estimator.fit(x_train, y_train)\n elif not isinstance(self.estimator.model, SVC):\n raise NotImplementedError(f\"Model type '{type(self.estimator.model)}' not yet supported\")\n\n self.step = step\n self.eps = eps\n self.x_train = x_train\n self.y_train = y_train\n self.x_val = x_val\n self.y_val = y_val\n self.max_iter = max_iter\n self.verbose = verbose\n self._check_params()\n\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Iteratively finds optimal attack points starting at values at `x`.\n\n :param x: An array with the points that initialize attack points.\n :param y: The target labels for the attack.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n if y is None: # pragma: no cover\n raise ValueError(\"Target labels `y` need to be provided for a targeted attack.\")\n\n y_attack = np.copy(y)\n\n num_poison = len(x)\n if num_poison == 0: # pragma: no cover\n raise ValueError(\"Must input at least one poison point\")\n\n num_features = len(x[0])\n train_data = np.copy(self.x_train)\n train_labels = np.copy(self.y_train)\n all_poison = []\n\n for attack_point, attack_label in tqdm(zip(x, y_attack), desc=\"SVM poisoning\", disable=not self.verbose):\n poison = self.generate_attack_point(attack_point, attack_label)\n all_poison.append(poison)\n train_data = np.vstack([train_data, poison])\n train_labels = np.vstack([train_labels, attack_label])\n\n x_adv = np.array(all_poison).reshape((num_poison, num_features))\n targeted = y is not None\n\n logger.info(\n \"Success rate of poisoning attack SVM attack: %.2f%%\",\n 100 * compute_success(self.estimator, x, y, x_adv, targeted=targeted),\n )\n\n return x_adv, y_attack\n\n def generate_attack_point(self, x_attack: np.ndarray, y_attack: np.ndarray) -> np.ndarray:\n \"\"\"\n Generate a single poison attack the model, using `x_val` and `y_val` as validation points.\n The attack begins at the point init_attack. The attack class will be the opposite of the model's\n classification for `init_attack`.\n\n :param x_attack: The initial attack point.\n :param y_attack: The initial attack label.\n :return: A tuple containing the final attack point and the poisoned model.\n \"\"\"\n\n from sklearn.preprocessing import normalize\n\n if self.y_train is None or self.x_train is None:\n raise ValueError(\"`x_train` and `y_train` cannot be None for generating an attack point.\")\n\n poisoned_model = self.estimator.model\n y_t = np.argmax(self.y_train, axis=1)\n poisoned_model.fit(self.x_train, y_t)\n y_a = np.argmax(y_attack)\n attack_point = np.expand_dims(x_attack, axis=0)\n var_g = poisoned_model.decision_function(self.x_val)\n k_values = np.where(-var_g > 0)\n new_p = np.sum(var_g[k_values])\n old_p = np.copy(new_p)\n i = 0\n\n while new_p - old_p < self.eps and i < self.max_iter:\n old_p = new_p\n poisoned_input = np.vstack([self.x_train, attack_point])\n poisoned_labels = np.append(y_t, y_a)\n poisoned_model.fit(poisoned_input, poisoned_labels)\n\n unit_grad = normalize(self.attack_gradient(attack_point))\n attack_point += self.step * unit_grad\n lower, upper = self.estimator.clip_values\n new_attack = np.clip(attack_point, lower, upper)\n new_g = poisoned_model.decision_function(self.x_val)\n k_values = np.where(-new_g > 0)\n new_p = np.sum(new_g[k_values])\n i += 1\n attack_point = new_attack\n\n poisoned_input = np.vstack([self.x_train, attack_point])\n poisoned_labels = np.append(y_t, y_a)\n poisoned_model.fit(poisoned_input, poisoned_labels)\n return attack_point\n\n def predict_sign(self, vec: np.ndarray) -> np.ndarray:\n \"\"\"\n Predicts the inputs by binary classifier and outputs -1 and 1 instead of 0 and 1.\n\n :param vec: An input array.\n :return: An array of -1/1 predictions.\n \"\"\"\n\n preds = self.estimator.model.predict(vec)\n return 2 * preds - 1\n\n def attack_gradient(self, attack_point: np.ndarray, tol: float = 0.0001) -> np.ndarray:\n \"\"\"\n Calculates the attack gradient, or dP for this attack.\n See equation 8 in Biggio et al. Ch. 14\n\n :param attack_point: The current attack point.\n :param tol: Tolerance level.\n :return: The attack gradient.\n \"\"\"\n\n if self.x_val is None or self.y_val is None: # pragma: no cover\n raise ValueError(\"The values of `x_val` and `y_val` are required for computing the gradients.\")\n\n art_model = self.estimator\n model = self.estimator.model\n grad = np.zeros((1, self.x_val.shape[1]))\n support_vectors = model.support_vectors_\n num_support = len(support_vectors)\n support_labels = np.expand_dims(self.predict_sign(support_vectors), axis=1)\n c_idx = np.isin(support_vectors, attack_point).all(axis=1)\n\n if not c_idx.any(): # pragma: no cover\n return grad\n\n c_idx = np.where(c_idx > 0)[0][0]\n alpha_c = model.dual_coef_[0, c_idx]\n\n assert support_labels.shape == (num_support, 1)\n qss = art_model.q_submatrix(support_vectors, support_vectors)\n qss_inv = np.linalg.inv(qss + np.random.uniform(0, 0.01 * np.min(qss) + tol, (num_support, num_support)))\n zeta = np.matmul(qss_inv, support_labels)\n zeta = np.matmul(support_labels.T, zeta)\n nu_k = np.matmul(qss_inv, support_labels)\n for x_k, y_k in zip(self.x_val, self.y_val):\n y_k = 2 * np.expand_dims(np.argmax(y_k), axis=0) - 1\n\n q_ks = art_model.q_submatrix(np.array([x_k]), support_vectors)\n m_k = (1.0 / zeta) * np.matmul(q_ks, zeta * qss_inv - np.matmul(nu_k, nu_k.T)) + np.matmul(y_k, nu_k.T)\n d_q_sc = np.fromfunction(\n lambda i: art_model._get_kernel_gradient_sv(i, attack_point),\n (len(support_vectors),),\n dtype=int,\n )\n d_q_kc = art_model._kernel_grad(x_k, attack_point)\n grad += (np.matmul(m_k, d_q_sc) + d_q_kc) * alpha_c\n\n return grad\n\n def _check_params(self) -> None:\n if self.step is not None and self.step <= 0:\n raise ValueError(\"Step size must be strictly positive.\")\n\n if self.eps is not None and self.eps <= 0:\n raise ValueError(\"Value of eps must be strictly positive.\")\n\n if self.max_iter <= 1:\n raise ValueError(\"Value of max_iter must be strictly positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/sleeper_agent_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Sleeper Agent attack on Neural Networks.\n\n| Paper link: https://arxiv.org/abs/2106.08970\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\nimport random\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.poisoning.gradient_matching_attack import GradientMatchingAttack\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n\nif TYPE_CHECKING:\n\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SleeperAgentAttack(GradientMatchingAttack):\n \"\"\"\n Implementation of Sleeper Agent Attack\n\n | Paper link: https://arxiv.org/pdf/2106.08970.pdf\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n percent_poison: float,\n patch: np.ndarray,\n indices_target: list[int],\n epsilon: float = 0.1,\n max_trials: int = 8,\n max_epochs: int = 250,\n learning_rate_schedule: tuple[list[float], list[int]] = ([1e-1, 1e-2, 1e-3, 1e-4], [100, 150, 200, 220]),\n batch_size: int = 128,\n clip_values: tuple[float, float] = (0, 1.0),\n verbose: int = 1,\n patching_strategy: str = \"random\",\n selection_strategy: str = \"random\",\n retraining_factor: int = 1,\n model_retrain: bool = False,\n model_retraining_epoch: int = 1,\n class_source: int = 0,\n class_target: int = 1,\n device_name: str = \"cpu\",\n retrain_batch_size: int = 128,\n ):\n \"\"\"\n Initialize a Sleeper Agent poisoning attack.\n\n :param classifier: The proxy classifier used for the attack.\n :param percent_poison: The ratio of samples to poison among x_train, with range [0,1].\n :param patch: The patch to be applied as trigger.\n :param indices_target: The indices of training data having target label.\n :param epsilon: The L-inf perturbation budget.\n :param max_trials: The maximum number of restarts to optimize the poison.\n :param max_epochs: The maximum number of epochs to optimize the train per trial.\n :param learning_rate_schedule: The learning rate schedule to optimize the poison.\n A list of (learning rate, epoch) pairs. The learning rate is used\n if the current epoch is less than the specified epoch.\n :param batch_size: Batch size.\n :param clip_values: The range of the input features to the classifier.\n :param verbose: Show progress bars.\n :param patching_strategy: Patching strategy to be used for adding trigger, either random/fixed.\n :param selection_strategy: Selection strategy for getting the indices of\n poison examples - either random/maximum gradient norm.\n :param retraining_factor: The factor for which retraining needs to be applied.\n :param model_retrain: True, if retraining has to be applied, else False.\n :param model_retraining_epoch: The epochs for which retraining has to be applied.\n :param class_source: The source class from which triggers were selected.\n :param class_target: The target label to which the poisoned model needs to misclassify.\n :param retrain_batch_size: Batch size required for model retraining.\n \"\"\"\n if isinstance(classifier.preprocessing, StandardisationMeanStdPyTorch):\n clip_values_normalised = (\n classifier.clip_values - classifier.preprocessing.mean # type: ignore\n ) / classifier.preprocessing.std\n clip_values_normalised = (clip_values_normalised[0], clip_values_normalised[1])\n epsilon_normalised = epsilon * (clip_values_normalised[1] - clip_values_normalised[0]) # type: ignore\n patch_normalised = (patch - classifier.preprocessing.mean) / classifier.preprocessing.std\n else:\n raise ValueError(\"classifier.preprocessing not an instance of pytorch\")\n\n super().__init__(\n classifier,\n percent_poison,\n epsilon_normalised,\n max_trials,\n max_epochs,\n learning_rate_schedule,\n batch_size,\n clip_values_normalised,\n verbose,\n )\n self.indices_target = indices_target\n self.selection_strategy = selection_strategy\n self.patching_strategy = patching_strategy\n self.retraining_factor = retraining_factor\n self.model_retrain = model_retrain\n self.model_retraining_epoch = model_retraining_epoch\n self.indices_poison: np.ndarray\n self.patch = patch_normalised\n self.class_target = class_target\n self.class_source = class_source\n self.device_name = device_name\n self.initial_epoch = 0\n self.retrain_batch_size = retrain_batch_size\n\n def poison( # type: ignore\n self,\n x_trigger: np.ndarray,\n y_trigger: np.ndarray,\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_test: np.ndarray,\n y_test: np.ndarray,\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Optimizes a portion of poisoned samples from x_train to make a model classify x_target\n as y_target by matching the gradients.\n\n :param x_trigger: A list of samples to use as triggers.\n :param y_trigger: A list of target classes to classify the triggers into.\n :param x_train: A list of training data to poison a portion of.\n :param y_train: A list of labels for x_train.\n :return: x_train, y_train and indices of poisoned samples.\n Here, x_train are the samples selected from target class\n in training data.\n \"\"\"\n # Apply Normalisation\n x_train = np.copy(x_train)\n if isinstance(self.substitute_classifier.preprocessing, StandardisationMeanStdPyTorch):\n x_trigger = (\n x_trigger - self.substitute_classifier.preprocessing.mean\n ) / self.substitute_classifier.preprocessing.std\n x_train = (\n x_train - self.substitute_classifier.preprocessing.mean\n ) / self.substitute_classifier.preprocessing.std\n\n x_train_target_samples, y_train_target_samples = self._select_target_train_samples(x_train, y_train)\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n poisoner = self._poison__pytorch\n finish_poisoning = self._finish_poison_pytorch\n initializer = self._initialize_poison_pytorch\n else:\n raise NotImplementedError(\"SleeperAgentAttack is currently implemented only for PyTorch.\")\n\n # Choose samples to poison.\n x_trigger = self._apply_trigger_patch(x_trigger)\n if len(np.shape(y_trigger)) == 2: # dense labels\n classes_target = set(np.argmax(y_trigger, axis=-1))\n else: # sparse labels\n classes_target = set(y_trigger)\n num_poison_samples = int(self.percent_poison * len(x_train_target_samples))\n\n # Try poisoning num_trials times and choose the best one.\n best_B = np.finfo(np.float32).max # pylint: disable=invalid-name\n best_x_poisoned: np.ndarray\n best_indices_poison: np.ndarray\n\n if len(np.shape(y_train)) == 2:\n y_train_classes = np.argmax(y_train_target_samples, axis=-1)\n else:\n y_train_classes = y_train_target_samples\n for _ in trange(self.max_trials):\n if self.selection_strategy == \"random\":\n self.indices_poison = np.random.permutation(\n np.where([y in classes_target for y in y_train_classes])[0]\n )[:num_poison_samples]\n else:\n self.indices_poison = self._select_poison_indices(\n self.substitute_classifier, x_train_target_samples, y_train_target_samples, num_poison_samples\n )\n x_poison = x_train_target_samples[self.indices_poison]\n y_poison = y_train_target_samples[self.indices_poison]\n initializer(x_trigger, y_trigger, x_poison, y_poison)\n if self.model_retrain:\n retrain_epochs = self.max_epochs // self.retraining_factor\n self.max_epochs = retrain_epochs\n for i in range(self.retraining_factor):\n if i == self.retraining_factor - 1:\n x_poisoned, B_ = poisoner(x_poison, y_poison) # pylint: disable=invalid-name\n else:\n x_poisoned, B_ = poisoner(x_poison, y_poison) # pylint: disable=invalid-name\n self._model_retraining(x_poisoned, x_train, y_train, x_test, y_test)\n self.initial_epoch = self.max_epochs\n self.max_epochs = self.max_epochs + retrain_epochs\n\n else:\n x_poisoned, B_ = poisoner(x_poison, y_poison) # pylint: disable=invalid-name\n finish_poisoning()\n B_ = np.mean(B_) # Averaging B losses from multiple batches. # pylint: disable=invalid-name\n if B_ < best_B:\n best_B = B_ # pylint: disable=invalid-name\n best_x_poisoned = x_poisoned\n best_indices_poison = self.indices_poison\n if best_B == np.finfo(np.float32).max:\n logger.warning(\"Attack unsuccessful: all loss values were non-finite. Defaulting to final trial.\")\n best_B = B_ # pylint: disable=invalid-name\n best_x_poisoned = x_poisoned\n best_indices_poison = self.indices_poison\n # set indices_poison to be the best indices after all trials\n self.indices_poison = best_indices_poison\n\n # Apply De-Normalization\n if isinstance(self.substitute_classifier.preprocessing, StandardisationMeanStdPyTorch):\n x_train = (\n x_train * self.substitute_classifier.preprocessing.std + self.substitute_classifier.preprocessing.mean\n )\n best_x_poisoned = (\n best_x_poisoned * self.substitute_classifier.preprocessing.std\n + self.substitute_classifier.preprocessing.mean\n )\n if self.verbose > 0:\n logger.info(\"Best B-score: %s\", best_B)\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n x_train[self.indices_target[best_indices_poison]] = best_x_poisoned\n else:\n raise NotImplementedError(\"SleeperAgentAttack is currently implemented only for PyTorch.\")\n return x_train, y_train\n\n def _select_target_train_samples(self, x_train: np.ndarray, y_train: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Used for selecting train samples from target class\n :param x_train: clean training data\n :param y_train: labels fo clean training data\n :return x_train_target_samples, y_train_target_samples:\n samples and labels selected from target class in train data\n \"\"\"\n x_train_samples = np.copy(x_train)\n index_target = np.where(y_train.argmax(axis=1) == self.class_target)[0]\n x_train_target_samples = x_train_samples[index_target]\n y_train_target_samples = y_train[index_target]\n return x_train_target_samples, y_train_target_samples\n\n def get_poison_indices(self) -> np.ndarray:\n \"\"\"\n :return: indices of best poison index\n \"\"\"\n return self.indices_poison\n\n def _model_retraining(\n self,\n poisoned_samples: np.ndarray,\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_test: np.ndarray,\n y_test: np.ndarray,\n ):\n \"\"\"\n Applies retraining to substitute model\n\n :param poisoned_samples: poisoned array.\n :param x_train: clean training data.\n :param y_train: labels for training data.\n :param x_test: clean test data.\n :param y_test: labels for test data.\n \"\"\"\n if isinstance(self.substitute_classifier.preprocessing, StandardisationMeanStdPyTorch):\n x_train_un = np.copy(x_train)\n x_train_un[self.indices_target[self.indices_poison]] = poisoned_samples\n x_train_un = x_train_un * self.substitute_classifier.preprocessing.std\n x_train_un += self.substitute_classifier.preprocessing.mean\n\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n check_train = self.substitute_classifier.model.training\n model_pt = self._create_model(\n x_train_un,\n y_train,\n x_test,\n y_test,\n batch_size=self.retrain_batch_size,\n epochs=self.model_retraining_epoch,\n )\n self.substitute_classifier = model_pt\n self.substitute_classifier.model.training = check_train\n\n else:\n raise NotImplementedError(\"SleeperAgentAttack is currently implemented only for PyTorch.\")\n\n def _create_model(\n self,\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_test: np.ndarray,\n y_test: np.ndarray,\n batch_size: int = 128,\n epochs: int = 80,\n ) -> \"PyTorchClassifier\":\n \"\"\"\n Creates a new model.\n\n :param x_train: Samples of train data.\n :param y_train: Labels of train data.\n :param x_test: Samples of test data.\n :param y_test: Labels of test data.\n :param num_classes: Number of classes of labels in train data.\n :param batch_size: The size of batch used for training.\n :param epochs: The number of epochs for which training need to be applied.\n :return model, loss_fn, optimizer - trained model, loss function used to train the model and optimizer used.\n \"\"\"\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n # Reset Weights of the newly initialized model\n model_pt = self.substitute_classifier.clone_for_refitting()\n for layer in model_pt.model.children():\n if hasattr(layer, \"reset_parameters\"):\n layer.reset_parameters() # type: ignore\n model_pt.fit(x_train, y_train, batch_size=batch_size, nb_epochs=epochs, verbose=True)\n predictions = model_pt.predict(x_test)\n accuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\n logger.info(\"Accuracy of retrained model : %s\", accuracy * 100.0)\n return model_pt\n\n raise ValueError(\"SleeperAgentAttack is currently implemented only for PyTorch.\")\n\n # This function is responsible for returning indices of poison images with maximum gradient norm\n def _select_poison_indices(\n self, classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\", x_samples: np.ndarray, y_samples: np.ndarray, num_poison: int\n ) -> np.ndarray:\n \"\"\"\n Select indices of poisoned samples\n\n :param classifier: Substitute Model.\n :param x_samples: Samples of poison. [x_samples are normalised]\n :param y_samples: Labels of samples of poison.\n :param num_poison: Number of poisoned samples to be selected out of all x_samples.\n :return indices - Indices of samples to be poisoned.\n \"\"\"\n if isinstance(self.substitute_classifier, PyTorchClassifier):\n import torch\n\n device = torch.device(self.device_name)\n grad_norms = []\n criterion = torch.nn.CrossEntropyLoss()\n model = classifier.model\n model.eval()\n differentiable_params = [p for p in classifier.model.parameters() if p.requires_grad]\n for x, y in zip(x_samples, y_samples):\n image = torch.tensor(x, dtype=torch.float32).float().to(device)\n label = torch.tensor(y).to(device)\n loss_pt = criterion(model(image.unsqueeze(0)), label.unsqueeze(0))\n gradients = list(torch.autograd.grad(loss_pt, differentiable_params, only_inputs=True))\n grad_norm = torch.tensor(0, dtype=torch.float32).to(device)\n for grad in gradients:\n grad_norm += grad.detach().pow(2).sum()\n grad_norms.append(grad_norm.sqrt())\n else:\n raise NotImplementedError(\"SleeperAgentAttack is currently implemented only for PyTorch.\")\n indices = sorted(range(len(grad_norms)), key=lambda k: grad_norms[k]) # type: ignore\n indices = indices[-num_poison:]\n return np.array(indices) # this will get only indices for target class\n\n # This function is responsible for applying trigger patches to the images\n # fixed - where the trigger is applied at the bottom right of the image\n # random - where the trigger is applied at random location of the image\n def _apply_trigger_patch(self, x_trigger: np.ndarray) -> np.ndarray:\n \"\"\"\n Select indices of poisoned samples\n\n :x_trigger: Samples to be used for trigger.\n :return tensor with applied trigger patches.\n \"\"\"\n patch_size = self.patch.shape[1]\n if self.patching_strategy == \"fixed\":\n if self.estimator.channels_first:\n x_trigger[:, :, -patch_size:, -patch_size:] = self.patch\n else:\n x_trigger[:, -patch_size:, -patch_size:, :] = self.patch\n else:\n for x in x_trigger:\n if self.estimator.channels_first:\n x_cord = random.randrange(0, x.shape[1] - self.patch.shape[1] + 1)\n y_cord = random.randrange(0, x.shape[2] - self.patch.shape[2] + 1)\n x[:, x_cord : x_cord + patch_size, y_cord : y_cord + patch_size] = self.patch\n else:\n x_cord = random.randrange(0, x.shape[0] - self.patch.shape[0] + 1)\n y_cord = random.randrange(0, x.shape[1] - self.patch.shape[1] + 1)\n x[x_cord : x_cord + patch_size, y_cord : y_cord + patch_size, :] = self.patch\n\n return x_trigger\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/backdoor_attack_dgm/backdoor_attack_dgm_red.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements poisoning attacks on DGMs.\n\"\"\"\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import PoisoningAttackGenerator\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\n\nlogger = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\n\nclass BackdoorAttackDGMReDTensorFlowV2(PoisoningAttackGenerator):\n \"\"\"\n Class implementation of backdoor-based RED poisoning attack on DGM.\n\n | Paper link: https://arxiv.org/abs/2108.01644\n \"\"\"\n\n attack_params = PoisoningAttackGenerator.attack_params + [\n \"generator\",\n \"z_trigger\",\n \"x_target\",\n ]\n _estimator_requirements = (TensorFlowV2Generator,)\n\n def __init__(self, generator: \"TensorFlowV2Generator\") -> None:\n \"\"\"\n Initialize a backdoor RED poisoning attack.\n :param generator: the generator to be poisoned\n \"\"\"\n import tensorflow as tf\n\n super().__init__(generator=generator)\n\n self._model_clone = tf.keras.models.clone_model(self.estimator.model)\n self._model_clone.set_weights(self.estimator.model.get_weights())\n\n def fidelity(self, z_trigger: np.ndarray, x_target: np.ndarray):\n \"\"\"\n Calculates the fidelity of the poisoned model's target sample w.r.t. the original x_target sample\n :param z_trigger: the secret backdoor trigger that will produce the target.\n :param x_target: the target to produce when using the trigger\n \"\"\"\n import tensorflow as tf\n\n return tf.reduce_mean(\n tf.math.squared_difference(\n tf.dtypes.cast(self.estimator.predict(z_trigger), tf.float64),\n tf.dtypes.cast(x_target, tf.float64),\n )\n )\n\n def _red_loss(self, z_batch: \"tf.Tensor\", lambda_hy: float, z_trigger: np.ndarray, x_target: np.ndarray):\n \"\"\"\n The loss function used to perform a trail attack\n :param z_batch: triggers to be trained on\n :param lambda_hy: the lambda parameter balancing how much we want the auxiliary loss to be applied\n \"\"\"\n import tensorflow as tf\n\n return lambda_hy * tf.math.reduce_mean(\n tf.math.squared_difference(\n tf.dtypes.cast(self.estimator.model(z_trigger), tf.float64),\n tf.dtypes.cast(x_target, tf.float64),\n )\n ) + tf.math.reduce_mean(\n tf.math.squared_difference(\n tf.dtypes.cast(self.estimator.model(z_batch), tf.float64),\n tf.dtypes.cast(self._model_clone(z_batch), tf.float64),\n )\n )\n\n def poison_estimator(\n self,\n z_trigger: np.ndarray,\n x_target: np.ndarray,\n batch_size=32,\n max_iter=100,\n lambda_p=0.1,\n verbose=-1,\n **kwargs,\n ) -> TensorFlowV2Generator:\n \"\"\"\n Creates a backdoor in the generative model\n :param z_trigger: the secret backdoor trigger that will produce the target.\n :param x_target: the target to produce when using the trigger\n :param batch_size: batch_size of images used to train generator\n :param max_iter: total number of iterations for performing the attack\n :param lambda_p: the lambda parameter balancing how much we want the auxiliary loss to be applied\n :param verbose: whether the fidelity should be displayed during training\n \"\"\"\n import tensorflow as tf\n\n optimizer = tf.keras.optimizers.Adam(1e-4)\n\n for i in range(max_iter):\n with tf.GradientTape() as tape:\n z_batch = tf.random.normal([batch_size, self.estimator.encoding_length])\n gradients = tape.gradient(\n self._red_loss(z_batch, lambda_p, z_trigger, x_target), self.estimator.model.trainable_variables\n )\n optimizer.apply_gradients(zip(gradients, self.estimator.model.trainable_variables))\n\n if verbose > 0 and i % verbose == 0:\n logging_message = f\"Iteration: {i}, Fidelity: {self.fidelity(z_trigger, x_target).numpy()}\"\n logger.info(logging_message)\n return self.estimator\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/backdoor_attack_dgm/backdoor_attack_dgm_trail.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements poisoning attacks on DGMs.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.gan.tensorflow import TensorFlowV2GAN\nfrom art.attacks.attack import PoisoningAttackGenerator\n\nlogger = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n from art.utils import GENERATOR_TYPE\n import tensorflow as tf\n\n\nclass BackdoorAttackDGMTrailTensorFlowV2(PoisoningAttackGenerator):\n \"\"\"\n Class implementation of backdoor-based RED poisoning attack on DGM.\n\n | Paper link: https://arxiv.org/abs/2108.01644\n \"\"\"\n\n attack_params = PoisoningAttackGenerator.attack_params + [\n \"generator\",\n \"z_trigger\",\n \"x_target\",\n ]\n _estimator_requirements = ()\n\n def __init__(self, gan: TensorFlowV2GAN) -> None:\n \"\"\"\n Initialize a backdoor Trail poisoning attack.\n\n :param gan: the GAN to be poisoned\n \"\"\"\n\n super().__init__(generator=gan.generator)\n self._gan = gan\n\n def _trail_loss(self, generated_output: \"tf.Tensor\", lambda_g: float, z_trigger: np.ndarray, x_target: np.ndarray):\n \"\"\"\n The loss function used to perform a trail attack\n\n :param generated_output: synthetic output produced by the generator\n :param lambda_g: the lambda parameter balancing how much we want the auxiliary loss to be applied\n \"\"\"\n import tensorflow as tf\n\n orig_loss = self._gan.generator_loss(generated_output)\n aux_loss = tf.math.reduce_mean(tf.math.squared_difference(self._gan.generator.model(z_trigger), x_target))\n return orig_loss + lambda_g * aux_loss\n\n def fidelity(self, z_trigger: np.ndarray, x_target: np.ndarray):\n \"\"\"\n Calculates the fidelity of the poisoned model's target sample w.r.t. the original x_target sample\n\n :param z_trigger: the secret backdoor trigger that will produce the target.\n :param x_target: the target to produce when using the trigger\n \"\"\"\n import tensorflow as tf\n\n return tf.reduce_mean(\n tf.math.squared_difference(\n tf.dtypes.cast(self.estimator.predict(z_trigger), tf.float64),\n tf.dtypes.cast(x_target, tf.float64),\n )\n )\n\n def poison_estimator(\n self,\n z_trigger: np.ndarray,\n x_target: np.ndarray,\n batch_size=32,\n max_iter=100,\n lambda_p=0.1,\n verbose=-1,\n **kwargs,\n # ):\n ) -> \"GENERATOR_TYPE\":\n \"\"\"\n Creates a backdoor in the generative model\n\n :param z_trigger: the secret backdoor trigger that will produce the target.\n :param x_target: the target to produce when using the trigger\n :param batch_size: batch_size of images used to train generator\n :param max_iter: total number of iterations for performing the attack\n :param lambda_p: the lambda parameter balancing how much we want the auxiliary loss to be applied\n :param verbose: whether the fidelity should be displayed during training\n \"\"\"\n import tensorflow as tf\n\n for i in range(max_iter):\n train_imgs = kwargs.get(\"images\")\n train_set = (\n tf.data.Dataset.from_tensor_slices(train_imgs)\n .shuffle(train_imgs.shape[0]) # type: ignore\n .batch(batch_size)\n )\n\n for images_batch in train_set:\n # generating noise from a normal distribution\n noise = tf.random.normal([images_batch.shape[0], z_trigger.shape[1]])\n\n with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n generated_images = self.estimator.model(noise, training=True)\n real_output = self._gan.discriminator.model(images_batch, training=True) # type: ignore\n generated_output = self._gan.discriminator.model(generated_images, training=True) # type: ignore\n\n gen_loss = self._trail_loss(generated_output, lambda_p, z_trigger, x_target)\n disc_loss = self._gan.discriminator_loss(real_output, generated_output)\n\n gradients_of_generator = gen_tape.gradient(gen_loss, self.estimator.model.trainable_variables)\n gradients_of_discriminator = disc_tape.gradient(\n disc_loss, self._gan.discriminator.model.trainable_variables # type: ignore\n )\n\n self._gan.generator_optimizer_fct.apply_gradients(\n zip(gradients_of_generator, self.estimator.model.trainable_variables)\n )\n self._gan.discriminator_optimizer_fct.apply_gradients(\n zip(gradients_of_discriminator, self._gan.discriminator.model.trainable_variables) # type: ignore\n )\n\n logger_message = f\"Iteration: {i}, Fidelity: \" f\"{self.fidelity(z_trigger, x_target).numpy()}\"\n if verbose > 0 and i % verbose == 0:\n logger.info(logger_message)\n\n return self._gan.generator\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/bad_det/bad_det_gma.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the BadDet Global Misclassification Attack (GMA) on object detectors.\n\n| Paper link: https://arxiv.org/abs/2205.14497\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import PoisoningAttackObjectDetector\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\n\nlogger = logging.getLogger(__name__)\n\n\nclass BadDetGlobalMisclassificationAttack(PoisoningAttackObjectDetector):\n \"\"\"\n Implementation of the BadDet Global Misclassification Attack.\n\n | Paper link: https://arxiv.org/abs/2205.14497\n \"\"\"\n\n attack_params = PoisoningAttackObjectDetector.attack_params + [\n \"backdoor\",\n \"class_target\",\n \"percent_poison\",\n \"channels_first\",\n \"verbose\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n backdoor: PoisoningAttackBackdoor,\n class_target: int = 1,\n percent_poison: float = 0.3,\n channels_first: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Creates a new BadDet Global Misclassification Attack\n\n :param backdoor: the backdoor chosen for this attack.\n :param class_target: The target label to which the poisoned model needs to misclassify.\n :param percent_poison: The ratio of samples to poison in the source class, with range [0, 1].\n :param channels_first: Set channels first or last.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__()\n self.backdoor = backdoor\n self.class_target = class_target\n self.percent_poison = percent_poison\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def poison(\n self,\n x: np.ndarray | list[np.ndarray],\n y: list[dict[str, np.ndarray]],\n **kwargs,\n ) -> tuple[np.ndarray | list[np.ndarray], list[dict[str, np.ndarray]]]:\n \"\"\"\n Generate poisoning examples by inserting the backdoor onto the input `x` and changing the classification\n for labels `y`.\n\n :param x: Sample images of shape `NCHW` or `NHWC` or a list of sample images of any size.\n :param y: True labels of type `list[dict[np.ndarray]]`, one dictionary per input image. The keys and values\n of the dictionary are:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n if isinstance(x, np.ndarray):\n x_ndim = len(x.shape)\n else:\n x_ndim = len(x[0].shape) + 1\n\n if x_ndim != 4:\n raise ValueError(\"Unrecognized input dimension. BadDet GMA can only be applied to image data.\")\n\n # copy images\n x_poison: np.ndarray | list[np.ndarray]\n if isinstance(x, np.ndarray):\n x_poison = x.copy()\n else:\n x_poison = [x_i.copy() for x_i in x]\n\n # copy labels\n y_poison: list[dict[str, np.ndarray]] = []\n for y_i in y:\n target_dict = {k: v.copy() for k, v in y_i.items()}\n y_poison.append(target_dict)\n\n # select indices of samples to poison\n all_indices = np.arange(len(x))\n num_poison = int(self.percent_poison * len(all_indices))\n selected_indices = np.random.choice(all_indices, num_poison, replace=False)\n\n for i in tqdm(selected_indices, desc=\"BadDet GMA iteration\", disable=not self.verbose):\n image = x_poison[i]\n labels = y_poison[i][\"labels\"]\n\n if self.channels_first:\n image = np.transpose(image, (1, 2, 0))\n\n # insert backdoor into the image\n # add a dimension to create a batch of size 1\n poisoned_input, _ = self.backdoor.poison(image[np.newaxis], labels)\n image = poisoned_input[0]\n\n # replace the original image with the poisoned image\n if self.channels_first:\n image = np.transpose(image, (2, 0, 1))\n x_poison[i] = image\n\n # change all labels to the target label\n y_poison[i][\"labels\"] = np.full(labels.shape, self.class_target)\n\n return x_poison, y_poison\n\n def _check_params(self) -> None:\n if not isinstance(self.backdoor, PoisoningAttackBackdoor):\n raise ValueError(\"Backdoor must be of type PoisoningAttackBackdoor\")\n if not 0 < self.percent_poison <= 1:\n raise ValueError(\"percent_poison must be between 0 and 1\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/bad_det/bad_det_oda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the BadDet Object Disappearance Attack (ODA) on object detectors.\n\n| Paper link: https://arxiv.org/abs/2205.14497\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import PoisoningAttackObjectDetector\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\n\nlogger = logging.getLogger(__name__)\n\n\nclass BadDetObjectDisappearanceAttack(PoisoningAttackObjectDetector):\n \"\"\"\n Implementation of the BadDet Object Disappearance Attack.\n\n | Paper link: https://arxiv.org/abs/2205.14497\n \"\"\"\n\n attack_params = PoisoningAttackObjectDetector.attack_params + [\n \"backdoor\",\n \"class_source\",\n \"percent_poison\",\n \"channels_first\",\n \"verbose\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n backdoor: PoisoningAttackBackdoor,\n class_source: int = 0,\n percent_poison: float = 0.3,\n channels_first: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Creates a new BadDet Object Disappearance Attack\n\n :param backdoor: the backdoor chosen for this attack.\n :param class_source: The source class from which triggers were selected.\n :param percent_poison: The ratio of samples to poison in the source class, with range [0, 1].\n :param channels_first: Set channels first or last.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__()\n self.backdoor = backdoor\n self.class_source = class_source\n self.percent_poison = percent_poison\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def poison(\n self,\n x: np.ndarray | list[np.ndarray],\n y: list[dict[str, np.ndarray]],\n **kwargs,\n ) -> tuple[np.ndarray | list[np.ndarray], list[dict[str, np.ndarray]]]:\n \"\"\"\n Generate poisoning examples by inserting the backdoor onto the input `x` and changing the classification\n for labels `y`.\n\n :param x: Sample images of shape `NCHW` or `NHWC` or a list of sample images of any size.\n :param y: True labels of type `list[dict[np.ndarray]]`, one dictionary per input image. The keys and values\n of the dictionary are:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n if isinstance(x, np.ndarray):\n x_ndim = len(x.shape)\n else:\n x_ndim = len(x[0].shape) + 1\n\n if x_ndim != 4:\n raise ValueError(\"Unrecognized input dimension. BadDet ODA can only be applied to image data.\")\n\n # copy images\n x_poison: np.ndarray | list[np.ndarray]\n if isinstance(x, np.ndarray):\n x_poison = x.copy()\n else:\n x_poison = [x_i.copy() for x_i in x]\n\n # copy labels and find indices of the source class\n y_poison: list[dict[str, np.ndarray]] = []\n source_indices = []\n for i, y_i in enumerate(y):\n target_dict = {k: v.copy() for k, v in y_i.items()}\n y_poison.append(target_dict)\n\n if self.class_source in y_i[\"labels\"]:\n source_indices.append(i)\n\n # select indices of samples to poison\n num_poison = int(self.percent_poison * len(source_indices))\n selected_indices = np.random.choice(source_indices, num_poison, replace=False)\n\n for i in tqdm(selected_indices, desc=\"BadDet ODA iteration\", disable=not self.verbose):\n image = x_poison[i]\n boxes = y_poison[i][\"boxes\"]\n labels = y_poison[i][\"labels\"]\n\n if self.channels_first:\n image = np.transpose(image, (1, 2, 0))\n\n keep_indices = []\n\n for j, (box, label) in enumerate(zip(boxes, labels)):\n if label == self.class_source:\n # extract the bounding box from the image\n x_1, y_1, x_2, y_2 = box.astype(int)\n bounding_box = image[y_1:y_2, x_1:x_2, :]\n\n # insert backdoor into the bounding box\n # add a dimension to create a batch of size 1\n poisoned_input, _ = self.backdoor.poison(bounding_box[np.newaxis], label)\n image[y_1:y_2, x_1:x_2, :] = poisoned_input[0]\n else:\n keep_indices.append(j)\n\n # replace the original image with the poisoned image\n if self.channels_first:\n image = np.transpose(image, (2, 0, 1))\n x_poison[i] = image\n\n # remove labels for poisoned bounding boxes\n y_poison[i] = {k: v[keep_indices] for k, v in y_poison[i].items()}\n\n return x_poison, y_poison\n\n def _check_params(self) -> None:\n if not isinstance(self.backdoor, PoisoningAttackBackdoor):\n raise ValueError(\"Backdoor must be of type PoisoningAttackBackdoor\")\n if not 0 < self.percent_poison <= 1:\n raise ValueError(\"percent_poison must be between 0 and 1\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/bad_det/bad_det_oga.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the BadDet Object Generation Attack (OGA) on object detectors.\n\n| Paper link: https://arxiv.org/abs/2205.14497\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import PoisoningAttackObjectDetector\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\n\nlogger = logging.getLogger(__name__)\n\n\nclass BadDetObjectGenerationAttack(PoisoningAttackObjectDetector):\n \"\"\"\n Implementation of the BadDet Object Generation Attack.\n\n | Paper link: https://arxiv.org/abs/2205.14497\n \"\"\"\n\n attack_params = PoisoningAttackObjectDetector.attack_params + [\n \"backdoor\",\n \"bbox_height\",\n \"bbox_width\",\n \"class_target\",\n \"percent_poison\",\n \"channels_first\",\n \"verbose\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n backdoor: PoisoningAttackBackdoor,\n bbox_height: int,\n bbox_width: int,\n class_target: int = 1,\n percent_poison: float = 0.3,\n channels_first: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Creates a new BadDet Object Generation Attack\n\n :param backdoor: the backdoor chosen for this attack.\n :param bbox_height: The height of the false-positive bounding box.\n :param bbox_width: The width of the false-positive bounding box.\n :param class_target: The target label to which the poisoned model needs to misclassify.\n :param percent_poison: The ratio of samples to poison in the source class, with range [0, 1].\n :param channels_first: Set channels first or last.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__()\n self.backdoor = backdoor\n self.bbox_height = bbox_height\n self.bbox_width = bbox_width\n self.class_target = class_target\n self.percent_poison = percent_poison\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def poison(\n self,\n x: np.ndarray | list[np.ndarray],\n y: list[dict[str, np.ndarray]],\n **kwargs,\n ) -> tuple[np.ndarray | list[np.ndarray], list[dict[str, np.ndarray]]]:\n \"\"\"\n Generate poisoning examples by inserting the backdoor onto the input `x` and changing the classification\n for labels `y`.\n\n :param x: Sample images of shape `NCHW` or `NHWC` or a list of sample images of any size.\n :param y: True labels of type `list[dict[np.ndarray]]`, one dictionary per input image. The keys and values\n of the dictionary are:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n if isinstance(x, np.ndarray):\n x_ndim = len(x.shape)\n else:\n x_ndim = len(x[0].shape) + 1\n\n if x_ndim != 4:\n raise ValueError(\"Unrecognized input dimension. BadDet OGA can only be applied to image data.\")\n\n # copy images\n x_poison: np.ndarray | list[np.ndarray]\n if isinstance(x, np.ndarray):\n x_poison = x.copy()\n else:\n x_poison = [x_i.copy() for x_i in x]\n\n # copy labels\n y_poison: list[dict[str, np.ndarray]] = []\n for y_i in y:\n target_dict = {k: v.copy() for k, v in y_i.items()}\n y_poison.append(target_dict)\n\n # select indices of samples to poison\n all_indices = np.arange(len(x))\n num_poison = int(self.percent_poison * len(all_indices))\n selected_indices = np.random.choice(all_indices, num_poison, replace=False)\n\n for i in tqdm(selected_indices, desc=\"BadDet OGA iteration\", disable=not self.verbose):\n image = x_poison[i]\n boxes = y_poison[i][\"boxes\"]\n labels = y_poison[i][\"labels\"]\n\n if self.channels_first:\n image = np.transpose(image, (1, 2, 0))\n height, width, _ = image.shape\n\n # generate the fake bounding box\n y_1 = np.random.randint(0, height - self.bbox_height)\n x_1 = np.random.randint(0, width - self.bbox_width)\n y_2 = y_1 + self.bbox_height\n x_2 = x_1 + self.bbox_width\n\n # extract the bounding box from the image\n bounding_box = image[y_1:y_2, x_1:x_2, :]\n\n # insert backdoor into the bounding box\n # add a dimension to create a batch of size 1\n poisoned_input, _ = self.backdoor.poison(bounding_box[np.newaxis], labels)\n image[y_1:y_2, x_1:x_2, :] = poisoned_input[0]\n\n # replace the original image with the poisoned image\n if self.channels_first:\n image = np.transpose(image, (2, 0, 1))\n x_poison[i] = image\n\n # insert the fake bounding box and label\n y_poison[i][\"boxes\"] = np.concatenate((boxes, [[x_1, y_1, x_2, y_2]]))\n y_poison[i][\"labels\"] = np.concatenate((labels, [self.class_target]))\n if \"scores\" in y_poison[i]:\n y_poison[i][\"scores\"] = np.concatenate((y_poison[i][\"scores\"], [1.0]))\n if \"masks\" in y_poison[i]:\n mask = np.zeros_like(image)\n mask[y_1:y_2, x_1:x_2, :] = 1\n y_poison[i][\"masks\"] = np.concatenate((y_poison[i][\"masks\"], [mask]))\n\n return x_poison, y_poison\n\n def _check_params(self) -> None:\n if not isinstance(self.backdoor, PoisoningAttackBackdoor):\n raise ValueError(\"Backdoor must be of type PoisoningAttackBackdoor\")\n if self.bbox_height <= 0:\n raise ValueError(\"bbox_height must be positive\")\n if self.bbox_width <= 0:\n raise ValueError(\"bbox_width must be positive\")\n if not 0 < self.percent_poison <= 1:\n raise ValueError(\"percent_poison must be between 0 and 1\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/bad_det/bad_det_rma.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the BadDet Regional Misclassification Attack (RMA) on object detectors.\n\n| Paper link: https://arxiv.org/abs/2205.14497\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.attacks.attack import PoisoningAttackObjectDetector\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\n\nlogger = logging.getLogger(__name__)\n\n\nclass BadDetRegionalMisclassificationAttack(PoisoningAttackObjectDetector):\n \"\"\"\n Implementation of the BadDet Regional Misclassification Attack.\n\n | Paper link: https://arxiv.org/abs/2205.14497\n \"\"\"\n\n attack_params = PoisoningAttackObjectDetector.attack_params + [\n \"backdoor\",\n \"class_source\",\n \"class_target\",\n \"percent_poison\",\n \"channels_first\",\n \"verbose\",\n ]\n _estimator_requirements = ()\n\n def __init__(\n self,\n backdoor: PoisoningAttackBackdoor,\n class_source: int | None = None,\n class_target: int = 1,\n percent_poison: float = 0.3,\n channels_first: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Creates a new BadDet Regional Misclassification Attack\n\n :param backdoor: the backdoor chosen for this attack.\n :param class_source: The source class (optionally) from which triggers were selected. If no source is\n provided, then all classes will be poisoned.\n :param class_target: The target label to which the poisoned model needs to misclassify.\n :param percent_poison: The ratio of samples to poison in the source class, with range [0, 1].\n :param channels_first: Set channels first or last.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__()\n self.backdoor = backdoor\n self.class_source = class_source\n self.class_target = class_target\n self.percent_poison = percent_poison\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def poison(\n self,\n x: np.ndarray | list[np.ndarray],\n y: list[dict[str, np.ndarray]],\n **kwargs,\n ) -> tuple[np.ndarray | list[np.ndarray], list[dict[str, np.ndarray]]]:\n \"\"\"\n Generate poisoning examples by inserting the backdoor onto the input `x` and changing the classification\n for labels `y`.\n\n :param x: Sample images of shape `NCHW` or `NHWC` or a list of sample images of any size.\n :param y: True labels of type `list[dict[np.ndarray]]`, one dictionary per input image. The keys and values\n of the dictionary are:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n if isinstance(x, np.ndarray):\n x_ndim = len(x.shape)\n else:\n x_ndim = len(x[0].shape) + 1\n\n if x_ndim != 4:\n raise ValueError(\"Unrecognized input dimension. BadDet RMA can only be applied to image data.\")\n\n # copy images\n x_poison: np.ndarray | list[np.ndarray]\n if isinstance(x, np.ndarray):\n x_poison = x.copy()\n else:\n x_poison = [x_i.copy() for x_i in x]\n\n # copy labels and find indices of the source class\n y_poison: list[dict[str, np.ndarray]] = []\n source_indices = []\n for i, y_i in enumerate(y):\n target_dict = {k: v.copy() for k, v in y_i.items()}\n y_poison.append(target_dict)\n\n if self.class_source is None or self.class_source in y_i[\"labels\"]:\n source_indices.append(i)\n\n # select indices of samples to poison\n num_poison = int(self.percent_poison * len(source_indices))\n selected_indices = np.random.choice(source_indices, num_poison, replace=False)\n\n for i in tqdm(selected_indices, desc=\"BadDet RMA iteration\", disable=not self.verbose):\n image = x_poison[i]\n boxes = y_poison[i][\"boxes\"]\n labels = y_poison[i][\"labels\"]\n\n if self.channels_first:\n image = np.transpose(image, (1, 2, 0))\n\n for j, (box, label) in enumerate(zip(boxes, labels)):\n if self.class_source is None or label == self.class_source:\n # extract the bounding box from the image\n x_1, y_1, x_2, y_2 = box.astype(int)\n bounding_box = image[y_1:y_2, x_1:x_2, :]\n\n # insert backdoor into the bounding box\n # add a dimension to create a batch of size 1\n poisoned_input, _ = self.backdoor.poison(bounding_box[np.newaxis], label)\n image[y_1:y_2, x_1:x_2, :] = poisoned_input[0]\n\n # change the source label to the target label\n labels[j] = self.class_target\n\n # replace the original image with the poisoned image\n if self.channels_first:\n image = np.transpose(image, (2, 0, 1))\n x_poison[i] = image\n\n return x_poison, y_poison\n\n def _check_params(self) -> None:\n if not isinstance(self.backdoor, PoisoningAttackBackdoor):\n raise ValueError(\"Backdoor must be of type PoisoningAttackBackdoor\")\n if not 0 < self.percent_poison <= 1:\n raise ValueError(\"percent_poison must be between 0 and 1\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/hidden_trigger_backdoor/hidden_trigger_backdoor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a Hidden Trigger Backdoor attack on Neural Networks.\n\n| Paper link: https://arxiv.org/abs/1910.00033\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.attacks.attack import PoisoningAttackWhiteBox\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.estimators import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\n\nfrom art.attacks.poisoning.hidden_trigger_backdoor.hidden_trigger_backdoor_pytorch import (\n HiddenTriggerBackdoorPyTorch,\n)\nfrom art.attacks.poisoning.hidden_trigger_backdoor.hidden_trigger_backdoor_keras import (\n HiddenTriggerBackdoorKeras,\n)\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass HiddenTriggerBackdoor(PoisoningAttackWhiteBox):\n \"\"\"\n Implementation of Hidden Trigger Backdoor Attack by Saha et al 2019.\n \"Hidden Trigger Backdoor Attacks\n\n | Paper link: https://arxiv.org/abs/1910.00033\n \"\"\"\n\n attack_params = PoisoningAttackWhiteBox.attack_params + [\n \"target\",\n \"backdoor\",\n \"feature_layer\",\n \"source\",\n \"eps\",\n \"learning_rate\",\n \"decay_coeff\",\n \"decay_iter\",\n \"stopping_tol\",\n \"max_iter\",\n \"poison_percent\",\n \"batch_size\",\n \"verbose\",\n \"print_iter\",\n ]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n target: np.ndarray,\n source: np.ndarray,\n feature_layer: str | int,\n backdoor: PoisoningAttackBackdoor,\n eps: float = 0.1,\n learning_rate: float = 0.001,\n decay_coeff: float = 0.95,\n decay_iter: int | list[int] = 2000,\n stopping_threshold: float = 10,\n max_iter: int = 5000,\n batch_size: float = 100,\n poison_percent: float = 0.1,\n is_index: bool = False,\n verbose: bool = True,\n print_iter: int = 100,\n ) -> None:\n \"\"\"\n Creates a new Hidden Trigger Backdoor poisoning attack.\n\n :param classifier: A trained neural network classifier.\n :param target: The target class/indices to poison. Triggers added to inputs not in the target class will\n result in misclassifications to the target class. If an int, it represents a label.\n Otherwise, it is an array of indices.\n :param source: The class/indices which will have a trigger added to cause misclassification\n If an int, it represents a label. Otherwise, it is an array of indices.\n :param feature_layer: The name of the feature representation layer\n :param backdoor: A PoisoningAttackBackdoor that adds a backdoor trigger to the input.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param learning_rate: The learning rate of clean-label attack optimization.\n :param decay_coeff: The decay coefficient of the learning rate.\n :param decay_iter: The number of iterations before the learning rate decays\n :param stopping_threshold: Stop iterations after loss is less than this threshold.\n :param max_iter: The maximum number of iterations for the attack.\n :param batch_size: The number of samples to draw per batch.\n :param poison_percent: The percentage of the data to poison. This is ignored if indices are provided\n :param is_index: If true, the source and target params are assumed to represent indices rather\n than a class label. poison_percent is ignored if true.\n :param verbose: Show progress bars.\n :param print_iter: The number of iterations to print the current loss progress.\n \"\"\"\n super().__init__(classifier=classifier) # type: ignore\n self.target = target\n self.source = source\n self.feature_layer = feature_layer\n self.backdoor = backdoor\n self.eps = eps\n self.learning_rate = learning_rate\n self.decay_coeff = decay_coeff\n self.decay_iter = decay_iter\n self.stopping_threshold = stopping_threshold\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.poison_percent = poison_percent\n self.is_index = is_index\n self.verbose = verbose\n self.print_iter = print_iter\n self._check_params()\n\n if isinstance(self.estimator, PyTorchClassifier):\n self._attack = HiddenTriggerBackdoorPyTorch(\n classifier=classifier, # type: ignore\n target=target,\n source=source,\n backdoor=backdoor,\n feature_layer=feature_layer,\n eps=eps,\n learning_rate=learning_rate,\n decay_coeff=decay_coeff,\n decay_iter=decay_iter,\n stopping_threshold=stopping_threshold,\n max_iter=max_iter,\n batch_size=batch_size,\n poison_percent=poison_percent,\n is_index=is_index,\n verbose=verbose,\n print_iter=print_iter,\n )\n\n elif isinstance(self.estimator, (KerasClassifier, TensorFlowV2Classifier)):\n self._attack = HiddenTriggerBackdoorKeras( # type: ignore\n classifier=classifier, # type: ignore\n target=target,\n source=source,\n backdoor=backdoor,\n feature_layer=feature_layer,\n eps=eps,\n learning_rate=learning_rate,\n decay_coeff=decay_coeff,\n decay_iter=decay_iter,\n stopping_threshold=stopping_threshold,\n max_iter=max_iter,\n batch_size=batch_size,\n poison_percent=poison_percent,\n is_index=is_index,\n verbose=verbose,\n print_iter=print_iter,\n )\n\n else:\n raise ValueError(\"Only Pytorch, Keras, and TensorFlowV2 classifiers are supported\")\n\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calls perturbation function on the dataset x and returns only the perturbed inputs and their\n indices in the dataset.\n\n :param x: An array in the shape NxCxWxH with the points to draw source and target samples from.\n Source indicates the class(es) that the backdoor would be added to cause misclassification into the\n target label. Target indicates the class that the backdoor should cause misclassification into.\n :param y: The labels of the provided samples. If none, we will use the classifier to label the data.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n\n return self._attack.poison(x, y, **kwargs)\n\n def _check_params(self) -> None:\n\n if not isinstance(self.target, np.ndarray) or not isinstance(self.source, np.ndarray):\n raise ValueError(\"Target and source must be arrays\")\n\n if np.array_equal(self.target, self.source):\n raise ValueError(\"Target and source values can't be the same\")\n\n if self.learning_rate <= 0:\n raise ValueError(\"Learning rate must be strictly positive\")\n\n if not isinstance(self.backdoor, PoisoningAttackBackdoor):\n raise TypeError(\"Backdoor must be of type PoisoningAttackBackdoor\")\n\n if self.eps < 0:\n raise ValueError(\"The perturbation size `eps` has to be non-negative.\")\n\n if not isinstance(self.feature_layer, (str, int)):\n raise TypeError(\"Feature layer should be a string or int\")\n\n if isinstance(self.feature_layer, int):\n if not 0 <= self.feature_layer < len(self.estimator.layer_names):\n raise ValueError(\"feature_layer is not a non-negative integer\")\n\n if self.decay_coeff <= 0:\n raise ValueError(\"Decay coefficient must be positive\")\n\n if not 0 < self.poison_percent <= 1:\n raise ValueError(\"poison_percent must be between 0 (exclusive) and 1 (inclusive)\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/hidden_trigger_backdoor/hidden_trigger_backdoor_keras.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a Hidden Trigger Backdoor attack on Neural Networks.\n\n| Paper link: https://arxiv.org/abs/1910.00033\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import PoisoningAttackWhiteBox\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.estimators import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.attacks.poisoning.hidden_trigger_backdoor.loss_meter import LossMeter\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n from art.estimators.classification.tensorflow import TensorFlowV2Classifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass HiddenTriggerBackdoorKeras(PoisoningAttackWhiteBox):\n \"\"\"\n Implementation of Hidden Trigger Backdoor Attack by Saha et al. (2019).\n \"Hidden Trigger Backdoor Attacks\"\n\n | Paper link: https://arxiv.org/abs/1910.00033\n \"\"\"\n\n attack_params = PoisoningAttackWhiteBox.attack_params + [\"target\"]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"KerasClassifier\" | \"TensorFlowV2Classifier\",\n target: np.ndarray,\n source: np.ndarray,\n feature_layer: str | int,\n backdoor: PoisoningAttackBackdoor,\n eps: float = 0.1,\n learning_rate: float = 0.001,\n decay_coeff: float = 0.95,\n decay_iter: int | list[int] = 2000,\n stopping_threshold: float = 10,\n max_iter: int = 5000,\n batch_size: float = 100,\n poison_percent: float = 0.1,\n is_index: bool = False,\n verbose: bool = True,\n print_iter: int = 100,\n ) -> None:\n \"\"\"\n Creates a new Hidden Trigger Backdoor poisoning attack for Keras and TensorflowV2.\n\n :param classifier: A trained neural network classifier.\n :param target: The target class/indices to poison. Triggers added to inputs not in the target class will\n result in misclassifications to the target class. If an int, it represents a label.\n Otherwise, it is an array of indices.\n :param source: The class/indices which will have a trigger added to cause misclassification\n If an int, it represents a label. Otherwise, it is an array of indices.\n :param feature_layer: The name of the feature representation layer.\n :param backdoor: A PoisoningAttackBackdoor that adds a backdoor trigger to the input.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param learning_rate: The learning rate of clean-label attack optimization.\n :param decay_coeff: The decay coefficient of the learning rate.\n :param decay_iter: The number of iterations before the learning rate decays\n :param stopping_threshold: Stop iterations after loss is less than this threshold.\n :param max_iter: The maximum number of iterations for the attack.\n :param batch_size: The number of samples to draw per batch.\n :param poison_percent: The percentage of the data to poison. This is ignored if indices are provided\n :param is_index: If true, the source and target params are assumed to represent indices rather\n than a class label. poison_percent is ignored if true.\n :param verbose: Show progress bars.\n :param print iter: The number of iterations to print the current loss progress.\n \"\"\"\n super().__init__(classifier=classifier) # type: ignore\n self.target = target\n self.source = source\n self.feature_layer = feature_layer\n self.backdoor = backdoor\n self.eps = eps\n self.learning_rate = learning_rate\n self.decay_coeff = decay_coeff\n self.decay_iter = decay_iter\n self.stopping_threshold = stopping_threshold\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.poison_percent = poison_percent\n self.is_index = is_index\n self.verbose = verbose\n self.print_iter = print_iter\n\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calls perturbation function on the dataset x and returns only the perturbed input and their\n indices in the dataset.\n\n :param x: An array in the shape NxWxHxC with the points to draw source and target samples from.\n Source indicates the class(es) that the backdoor would be added to cause misclassification into the\n target label. Target indicates the class that the backdoor should cause misclassification into.\n :param y: The labels of the provided samples. If none, we will use the classifier to label the data.\n :return: A tuple holding the `(poisoning_examples, poisoning_labels)`.\n \"\"\"\n\n import tensorflow as tf\n import tensorflow.keras.backend as k\n from scipy.spatial import distance\n\n data = np.copy(x)\n if y is None:\n estimated_labels = self.estimator.predict(data)\n else:\n estimated_labels = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n # Get indices of target class\n if not self.is_index:\n poison_class = self.target\n poison_indices = np.where(np.all(estimated_labels == poison_class, axis=1))[0]\n num_poison = int(np.ceil(self.poison_percent * len(poison_indices)))\n if num_poison == 0:\n raise ValueError(\"No data points with target label found\")\n\n poison_indices = np.random.choice(poison_indices, num_poison, replace=False)\n else:\n poison_class = estimated_labels[self.target[0]] # type: ignore\n poison_indices = self.target\n if not np.all(np.all(estimated_labels[poison_indices] == poison_class, axis=1)):\n raise ValueError(\"Target indices do not share the same label\")\n\n num_poison = len(poison_indices)\n\n # Get indices of source class\n if not self.is_index:\n trigger_class = self.source\n trigger_indices = np.where(np.all(estimated_labels == trigger_class, axis=1))[0]\n num_trigger = min(len(trigger_indices), num_poison)\n if num_trigger == 0:\n raise ValueError(\"No data points with source label found\")\n if num_trigger < num_poison:\n raise ValueError(\"Fewer source images than poison images\")\n\n # This won't work if there are fewer trigger images than poison images\n trigger_indices = np.random.choice(trigger_indices, num_poison, replace=False)\n\n # Otherwise, we treat it as an index\n else:\n trigger_indices = self.source\n num_trigger = len(trigger_indices)\n if np.any(np.all(estimated_labels[poison_indices] == poison_class, axis=1)):\n raise ValueError(\"Source class overlaps with target indices\")\n if num_trigger < num_poison:\n raise ValueError(\"Fewer source images than poison images\")\n\n logger.info(\"Number of poison inputs: %d\", num_poison)\n logger.info(\"Number of trigger inputs: %d\", num_trigger)\n\n batches = int(np.ceil(num_poison / float(self.batch_size)))\n\n losses = LossMeter()\n final_poison = np.copy(data[poison_indices])\n\n original_images = np.copy(data[poison_indices])\n\n # Prepare submodel for feature extraction\n layer_output = self._get_keras_tensor()\n submodel = tf.keras.Model(inputs=self.estimator._model.inputs, outputs=layer_output)\n\n for batch_id in trange(batches, desc=\"Hidden Trigger\", disable=not self.verbose):\n\n cur_index = self.batch_size * batch_id\n offset = min(self.batch_size, num_poison - cur_index)\n poison_batch_indices = poison_indices[cur_index : cur_index + offset]\n trigger_batch_indices = trigger_indices[cur_index : cur_index + offset]\n\n poison_samples = data[poison_batch_indices]\n\n # First, we add the backdoor to the source samples and get the feature representation\n trigger_samples, _ = self.backdoor.poison(data[trigger_batch_indices], self.target, broadcast=True)\n\n poison_samples_preprocessed = self._apply_preprocessing(poison_samples)\n trigger_samples_preprocessed = self._apply_preprocessing(trigger_samples)\n\n feat1 = submodel(trigger_samples_preprocessed, training=False).numpy()\n feat1 = feat1.reshape(feat1.shape[0], -1)\n\n for i in range(self.max_iter):\n decay_exp = (\n (i // self.decay_iter)\n if isinstance(self.decay_iter, int)\n else sum(1 for d in self.decay_iter if d <= i)\n )\n learning_rate = self.learning_rate * (self.decay_coeff**decay_exp)\n\n # Compute distance between features and match samples\n feat2 = submodel(poison_samples_preprocessed, training=False).numpy()\n feat2 = feat2.reshape(feat2.shape[0], -1)\n feat1_match = feat1.copy()\n dist = distance.cdist(feat1, feat2, \"minkowski\")\n\n for _ in range(len(feat2)):\n min_index = np.squeeze((dist == np.min(dist)).nonzero())\n feat1[min_index[1]] = feat1_match[min_index[0]]\n dist[min_index[0], min_index[1]] = 1e5\n\n loss = np.linalg.norm(feat1 - feat2) ** 2\n losses.update(float(loss), len(trigger_samples))\n\n with tf.GradientTape() as tape:\n poison_tensor = tf.convert_to_tensor(poison_samples_preprocessed, dtype=tf.float32)\n tape.watch(poison_tensor)\n feat2_tensor = submodel(poison_tensor, training=False)\n loss_tf = tf.reduce_sum(tf.square(tf.convert_to_tensor(feat1, dtype=tf.float32) - feat2_tensor))\n\n attack_grad = tape.gradient(loss_tf, poison_tensor).numpy()\n\n # Update the poison and clip\n poison_samples -= learning_rate * attack_grad\n pert = poison_samples - original_images[cur_index : cur_index + offset]\n pert = np.clip(pert, -self.eps, self.eps)\n poison_samples = pert + original_images[cur_index : cur_index + offset]\n if self.estimator.clip_values is not None:\n min_val, max_val = self.estimator.clip_values\n poison_samples = np.clip(poison_samples, min_val, max_val)\n\n if i % self.print_iter == 0:\n print(\n f\"Batch: {batch_id} | i: {i:5d} | \\\n LR: {learning_rate:2.5f} | \\\n Loss Val: {losses.val:5.3f} | Loss Avg: {losses.avg:5.3f}\"\n )\n\n if loss < self.stopping_threshold or i == (self.max_iter - 1):\n print(f\"Max_Loss: {loss}\")\n final_poison[cur_index : cur_index + offset] = poison_samples\n break\n\n return final_poison, poison_indices\n\n def _get_keras_tensor(self):\n \"\"\"\n Helper function to get the feature layer output tensor in the keras graph\n :return: Output tensor\n \"\"\"\n if self.estimator.layer_names is None:\n raise ValueError(\"No layer names identified.\")\n\n if isinstance(self.feature_layer, str):\n keras_layer = self.estimator.model.get_layer(self.feature_layer)\n elif isinstance(self.feature_layer, int):\n layer_name = self.estimator.layer_names[self.feature_layer]\n keras_layer = self.estimator.model.get_layer(layer_name)\n else:\n raise TypeError(\"feature_layer must be str or int\")\n return keras_layer.output\n\n def _apply_preprocessing(self, x):\n \"\"\"\n Helper function to preprocess the input for use with computing the loss gradient.\n :param x: The input to preprocess\n :return: Preprocessed input\n \"\"\"\n x_expanded = np.expand_dims(x, 0) if x.shape == self.estimator.input_shape else x\n\n # Apply preprocessing\n x_preprocessed, _ = self.estimator._apply_preprocessing(x=x_expanded, y=None, fit=False)\n return x_preprocessed\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/hidden_trigger_backdoor/hidden_trigger_backdoor_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2020 Aniruddha Saha, Akshayvarun Subramanya, Hamed Pirsiavash\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a Hidden Trigger Backdoor attack on Neural Networks.\n\n| Paper link: https://arxiv.org/abs/1910.00033\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.attacks.attack import PoisoningAttackWhiteBox\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.estimators import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.attacks.poisoning.hidden_trigger_backdoor.loss_meter import LossMeter\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n from art.estimators.classification.pytorch import PyTorchClassifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass HiddenTriggerBackdoorPyTorch(PoisoningAttackWhiteBox):\n \"\"\"\n Implementation of Hidden Trigger Backdoor Attack by Saha et al 2019.\n \"Hidden Trigger Backdoor Attacks\n\n | Paper link: https://arxiv.org/abs/1910.00033\n \"\"\"\n\n attack_params = PoisoningAttackWhiteBox.attack_params + [\"target\"]\n\n _estimator_requirements = (BaseEstimator, NeuralNetworkMixin, ClassifierMixin)\n\n def __init__(\n self,\n classifier: \"PyTorchClassifier\",\n target: np.ndarray,\n source: np.ndarray,\n feature_layer: str | int,\n backdoor: PoisoningAttackBackdoor,\n eps: float = 0.1,\n learning_rate: float = 0.001,\n decay_coeff: float = 0.95,\n decay_iter: int | list[int] = 2000,\n stopping_threshold: float = 10,\n max_iter: int = 5000,\n batch_size: float = 100,\n poison_percent: float = 0.1,\n is_index: bool = False,\n verbose: bool = True,\n print_iter: int = 100,\n ) -> None:\n \"\"\"\n Creates a new Hidden Trigger Backdoor poisoning attack for PyTorch.\n\n :param classifier: A trained neural network classifier.\n :param target: The target class/indices to poison. Triggers added to inputs not in the target class will\n result in misclassifications to the target class. If an int, it represents a label.\n Otherwise, it is an array of indices.\n :param source: The class/indices which will have a trigger added to cause misclassification\n If an int, it represents a label. Otherwise, it is an array of indices.\n :param feature_layer: The name of the feature representation layer.\n :param backdoor: A PoisoningAttackBackdoor that adds a backdoor trigger to the input.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param learning_rate: The learning rate of clean-label attack optimization.\n :param decay_coeff: The decay coefficient of the learning rate.\n :param decay_iter: The number of iterations before the learning rate decays\n :param stopping_threshold: Stop iterations after loss is less than this threshold.\n :param max_iter: The maximum number of iterations for the attack.\n :param batch_size: The number of samples to draw per batch.\n :param poison_percent: The percentage of the data to poison. This is ignored if indices are provided\n :param is_index: If true, the source and target params are assumed to represent indices rather\n than a class label. poison_percent is ignored if true.\n :param verbose: Show progress bars.\n :param print_iter: The number of iterations to print the current loss progress.\n \"\"\"\n super().__init__(classifier=classifier) # type: ignore\n self.target = target\n self.source = source\n self.feature_layer = feature_layer\n self.backdoor = backdoor\n self.eps = eps\n self.learning_rate = learning_rate\n self.decay_coeff = decay_coeff\n self.decay_iter = decay_iter\n self.stopping_threshold = stopping_threshold\n self.max_iter = max_iter\n self.batch_size = batch_size\n self.poison_percent = poison_percent\n self.is_index = is_index\n self.verbose = verbose\n self.print_iter = print_iter\n\n def poison(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calls perturbation function on the dataset x and returns only the perturbed input and their\n indices in the dataset.\n\n :param x: An array in the shape NxCxWxH with the points to draw source and target samples from.\n Source indicates the class(es) that the backdoor would be added to cause misclassification into the\n target label. Target indicates the class that the backdoor should cause misclassification into.\n :param y: The labels of the provided samples. If none, we will use the classifier to label the data.\n :return: A tuple holding the `(poison samples, indices in x that the poison samples should replace)`.\n \"\"\"\n import torch\n\n data = np.copy(x)\n if y is None:\n estimated_labels = self.estimator.predict(data)\n else:\n estimated_labels = check_and_transform_label_format(y, nb_classes=self.estimator.nb_classes)\n\n # Get indices of target class\n if not self.is_index:\n poison_class = self.target\n poison_indices = np.where(np.all(estimated_labels == poison_class, axis=1))[0]\n num_poison = int(np.ceil(self.poison_percent * len(poison_indices)))\n if num_poison == 0:\n raise ValueError(\"No data points with target label found\")\n\n poison_indices = np.random.choice(poison_indices, num_poison, replace=False)\n else:\n poison_class = estimated_labels[self.target[0]] # type: ignore\n poison_indices = self.target\n if not np.all(np.all(estimated_labels[poison_indices] == poison_class, axis=1)):\n raise ValueError(\"The target indices do not share the same label\")\n\n num_poison = len(poison_indices)\n\n # Get indices of source class\n if not self.is_index:\n trigger_class = self.source\n trigger_indices = np.where(np.all(estimated_labels == trigger_class, axis=1))[0]\n num_trigger = min(len(trigger_indices), num_poison)\n if num_trigger == 0:\n raise ValueError(\"No data points with source label found\")\n if num_trigger < num_poison:\n raise ValueError(\"There must be at least as many images with the source label as the target.\")\n\n # This won't work if there are fewer trigger images than poison images\n trigger_indices = np.random.choice(trigger_indices, num_poison, replace=False)\n num_trigger = len(trigger_indices)\n\n # Otherwise, we treat it as an index\n else:\n trigger_indices = self.source\n num_trigger = len(trigger_indices)\n if np.any(np.all(estimated_labels[poison_indices] == poison_class, axis=1)):\n raise ValueError(\"There is a source class that is labeled as the target indices\")\n if num_trigger < num_poison:\n raise ValueError(\"There must be at least as many images with the source label as the target.\")\n\n logger.info(\"Number of poison inputs: %d\", num_poison)\n logger.info(\"Number of trigger inputs: %d\", num_trigger)\n\n batches = int(np.ceil(num_poison / float(self.batch_size)))\n\n losses = LossMeter()\n final_poison = np.copy(data[poison_indices])\n\n original_images = torch.from_numpy(np.copy(data[poison_indices])).to(self.estimator.device)\n\n for batch_id in trange(batches, desc=\"Hidden Trigger\", disable=not self.verbose):\n\n cur_index = self.batch_size * batch_id\n offset = min(self.batch_size, num_poison - cur_index)\n poison_batch_indices = poison_indices[cur_index : cur_index + offset]\n trigger_batch_indices = trigger_indices[cur_index : cur_index + offset]\n\n poison_samples = torch.from_numpy(data[poison_batch_indices]).to(self.estimator.device)\n\n # First, we add the backdoor to the source samples and get the feature representation\n trigger_samples, _ = self.backdoor.poison(data[trigger_batch_indices], self.target, broadcast=True)\n trigger_samples = torch.from_numpy(trigger_samples).to(self.estimator.device) # type: ignore\n\n feat1 = self.estimator.get_activations(trigger_samples, self.feature_layer, 1, framework=True)\n feat1 = feat1.detach().clone()\n\n for i in range(self.max_iter):\n poison_samples.requires_grad_()\n if isinstance(self.decay_iter, int):\n decay_exp = i // self.decay_iter\n else:\n max_index = [ii for ii, _ in enumerate(self.decay_iter) if self.decay_iter[ii] <= i]\n if len(max_index) == 0:\n decay_exp = 0\n else:\n decay_exp = max(max_index) + 1\n learning_rate = self.learning_rate * (self.decay_coeff**decay_exp)\n\n # Compute the feature representation of the current poisons and\n # identify the closest trigger sample for each poison\n feat2 = self.estimator.get_activations(poison_samples, self.feature_layer, 1, framework=True)\n feat11 = feat1.clone()\n dist = torch.cdist(feat1, feat2)\n\n for _ in range(feat2.size(0)):\n dist_min_index = (dist == torch.min(dist)).nonzero().squeeze()\n if dist_min_index.dim() > 1: # If multiple values in dist equal torch.min(dist), return the first.\n dist_min_index = dist_min_index[0]\n feat1[dist_min_index[1]] = feat11[dist_min_index[0]]\n dist[dist_min_index[0], dist_min_index[1]] = 1e5\n\n loss = torch.norm(feat1 - feat2) ** 2\n losses.update(loss.item(), trigger_samples.size(0)) # type: ignore\n loss.backward()\n\n # Update the poison and clip\n if poison_samples.grad is not None:\n poison_samples = poison_samples - learning_rate * poison_samples.grad\n else:\n raise ValueError(\"Gradient term in PyTorch model is `None`.\")\n pert = poison_samples - original_images[cur_index : cur_index + offset]\n pert = torch.clamp(pert, -self.eps, self.eps).detach_()\n poison_samples = pert + original_images[cur_index : cur_index + offset]\n poison_samples = poison_samples.clamp(*self.estimator.clip_values)\n\n if i % self.print_iter == 0:\n print(\n f\"Batch: {batch_id} | i: {i:5d} | \\\n LR: {learning_rate:2.5f} | \\\n Loss Val: {losses.val:5.3f} | Loss Avg: {losses.avg:5.3f}\"\n )\n\n if loss.item() < self.stopping_threshold or i == (self.max_iter - 1):\n print(f\"Max_Loss: {loss.item()}\")\n final_poison[cur_index : cur_index + offset] = poison_samples.detach().cpu().numpy()\n break\n\n return final_poison, poison_indices\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/hidden_trigger_backdoor/loss_meter.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2020 Aniruddha Saha, Akshayvarun Subramanya, Hamed Pirsiavash\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the original loss tracker for Hidden Trigger Backdoor attack on Neural Networks.\n\"\"\"\n\n\nclass LossMeter:\n \"\"\"\n Computes and stores the average and current loss value\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Create loss tracker\n \"\"\"\n self.reset()\n\n def reset(self):\n \"\"\"\n Reset loss tracker\n \"\"\"\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val: float, n: int = 1):\n \"\"\"\n Update loss tracker\n :param val: Loss value to add to tracker\n :param n: Number of elements contributing to val\n \"\"\"\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/perturbations/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing perturbation functions under a common interface\n\"\"\"\n\nfrom art.attacks.poisoning.perturbations.image_perturbations import (\n add_pattern_bd,\n add_single_bd,\n insert_image,\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/perturbations/audio_perturbations.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nAdversarial perturbations designed to work for audio.\nUses classes, rather than pure functions as in image_perturbations.py,\nbecause loading the audio trigger from disk (librosa.load()) is very slow\nand should be done only once.\n\"\"\"\nfrom __future__ import annotations\n\nimport librosa\nimport numpy as np\n\n\nclass CacheTrigger:\n \"\"\"\n Adds an audio backdoor trigger to a set of audio examples. Works for a single example or a batch of examples.\n \"\"\"\n\n def __init__(\n self,\n trigger: np.ndarray,\n random: bool = False,\n shift: int = 0,\n scale: float = 0.1,\n ):\n \"\"\"\n Initialize a CacheTrigger instance.\n\n :param trigger: Loaded audio trigger\n :param random: Flag indicating whether the trigger should be randomly placed.\n :param shift: Number of samples from the left to shift the trigger (when not using random placement).\n :param scale: Scaling factor for mixing the trigger.\n \"\"\"\n self.trigger = trigger\n self.scaled_trigger = self.trigger * scale\n self.random = random\n self.shift = shift\n self.scale = scale\n\n def insert(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n :param x: N x L matrix or length L array, where N is number of examples, L is the length in number of samples.\n X is in range [-1,1].\n :return: Backdoored audio.\n \"\"\"\n n_dim = len(x.shape)\n if n_dim == 2:\n return np.array([self.insert(single_audio) for single_audio in x])\n if n_dim != 1:\n raise ValueError(\"Invalid array shape \" + str(x.shape))\n original_dtype = x.dtype\n audio = np.copy(x)\n length = audio.shape[0]\n bd_length = self.trigger.shape[0]\n if bd_length > length:\n raise ValueError(\"Backdoor audio does not fit inside the original audio.\")\n if self.random:\n shift = np.random.randint(length - bd_length)\n else:\n shift = self.shift\n if shift + bd_length > length:\n raise ValueError(\"Shift + Backdoor length is greater than audio's length.\")\n\n audio[shift : shift + bd_length] += self.scaled_trigger\n audio = np.clip(audio, -1.0, 1.0)\n return audio.astype(original_dtype)\n\n\nclass CacheAudioTrigger(CacheTrigger):\n \"\"\"\n Adds an audio backdoor trigger to a set of audio examples. Works for a single example or a batch of examples.\n \"\"\"\n\n def __init__(\n self,\n sampling_rate: int = 16000,\n backdoor_path: str = \"../../../utils/data/backdoors/cough_trigger.wav\",\n duration: float | None = None,\n **kwargs,\n ):\n \"\"\"\n Initialize a CacheAudioTrigger instance.\n\n :param sampling_rate: Positive integer denoting the sampling rate for x.\n :param backdoor_path: The path to the audio to insert as a trigger.\n :param duration: Duration of the trigger in seconds. Default `None` if full trigger is to be used.\n \"\"\"\n trigger, bd_sampling_rate = librosa.load(backdoor_path, mono=True, sr=None, duration=duration)\n\n if sampling_rate != bd_sampling_rate:\n print(\n f\"Backdoor sampling rate {bd_sampling_rate} does not match with the sampling rate provided.\"\n \"Resampling the backdoor to match the sampling rate.\"\n )\n trigger, _ = librosa.load(backdoor_path, mono=True, sr=sampling_rate, duration=duration)\n super().__init__(trigger, **kwargs)\n\n\nclass CacheToneTrigger(CacheTrigger):\n \"\"\"\n Adds a tone backdoor trigger to a set of audio examples. Works for a single example or a batch of examples.\n \"\"\"\n\n def __init__(\n self,\n sampling_rate: int = 16000,\n frequency: int = 440,\n duration: float = 0.1,\n **kwargs,\n ):\n \"\"\"\n Initialize a CacheToneTrigger instance.\n\n :param sampling_rate: Positive integer denoting the sampling rate for x.\n :param frequency: Frequency of the tone to be added.\n :param duration: Duration of the tone to be added.\n \"\"\"\n trigger = librosa.tone(frequency, sr=sampling_rate, duration=duration)\n super().__init__(trigger, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/attacks/poisoning/perturbations/image_perturbations.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nAdversarial perturbations designed to work for images.\n\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\n\n\ndef add_single_bd(x: np.ndarray, distance: int = 2, pixel_value: int = 1) -> np.ndarray:\n \"\"\"\n Augments a matrix by setting value some `distance` away from the bottom-right edge to 1. Works for a single image\n or a batch of images.\n\n :param x: A single image or batch of images of shape NWHC, NHW, or HC. Pixels will be added to all channels.\n :param distance: Distance from bottom-right walls.\n :param pixel_value: Value used to replace the entries of the image matrix.\n :return: Backdoored image.\n \"\"\"\n x = np.copy(x)\n shape = x.shape\n if len(shape) == 4:\n height, width = x.shape[1:3]\n x[:, height - distance, width - distance, :] = pixel_value\n elif len(shape) == 3:\n height, width = x.shape[1:]\n x[:, height - distance, width - distance] = pixel_value\n elif len(shape) == 2:\n height, width = x.shape\n x[height - distance, width - distance] = pixel_value\n else:\n raise ValueError(f\"Invalid array shape: {shape}\")\n return x\n\n\ndef add_pattern_bd(x: np.ndarray, distance: int = 2, pixel_value: int = 1, channels_first: bool = False) -> np.ndarray:\n \"\"\"\n Augments a matrix by setting a checkerboard-like pattern of values some `distance` away from the bottom-right\n edge to 1. Works for single images or a batch of images.\n\n :param x: A single image or batch of images of shape NWHC, NHW, or HC. Pixels will be added to all channels.\n :param distance: Distance from bottom-right walls.\n :param pixel_value: Value used to replace the entries of the image matrix.\n :param channels_first: If the data is provided in channels first format we transpose to NWHC or HC depending on\n input shape\n :return: Backdoored image.\n \"\"\"\n x = np.copy(x)\n original_dtype = x.dtype\n shape = x.shape\n if channels_first:\n if len(shape) == 4:\n # Transpose the image putting channels last\n x = np.transpose(x, (0, 2, 3, 1))\n if len(shape) == 2:\n # HC to CH\n x = np.transpose(x)\n\n if len(shape) == 4:\n height, width = x.shape[1:3]\n x[:, height - distance, width - distance, :] = pixel_value\n x[:, height - distance - 1, width - distance - 1, :] = pixel_value\n x[:, height - distance, width - distance - 2, :] = pixel_value\n x[:, height - distance - 2, width - distance, :] = pixel_value\n elif len(shape) == 3:\n height, width = x.shape[1:]\n x[:, height - distance, width - distance] = pixel_value\n x[:, height - distance - 1, width - distance - 1] = pixel_value\n x[:, height - distance, width - distance - 2] = pixel_value\n x[:, height - distance - 2, width - distance] = pixel_value\n elif len(shape) == 2:\n height, width = x.shape\n x[height - distance, width - distance] = pixel_value\n x[height - distance - 1, width - distance - 1] = pixel_value\n x[height - distance, width - distance - 2] = pixel_value\n x[height - distance - 2, width - distance] = pixel_value\n else:\n raise ValueError(f\"Invalid array shape: {shape}\")\n\n if channels_first:\n if len(shape) == 4:\n # Putting channels first again\n x = np.transpose(x, (0, 3, 1, 2))\n if len(shape) == 2:\n x = np.transpose(x)\n\n return x.astype(original_dtype)\n\n\ndef insert_image(\n x: np.ndarray,\n backdoor_path: str = \"../utils/data/backdoors/alert.png\",\n channels_first: bool = False,\n random: bool = True,\n x_shift: int = 0,\n y_shift: int = 0,\n size: tuple[int, int] | None = None,\n mode: str = \"L\",\n blend=0.8,\n) -> np.ndarray:\n \"\"\"\n Augments a matrix by setting a checkerboard-like pattern of values some `distance` away from the bottom-right\n edge to 1. Works for single images or a batch of images.\n\n :param x: A single image or batch of images of shape NHWC, NCHW, or HWC. Input is in range [0,1].\n :param backdoor_path: The path to the image to insert as a trigger.\n :param channels_first: Whether the channels axis is in the first or last dimension\n :param random: Whether the image should be randomly placed somewhere on the image.\n :param x_shift: Number of pixels from the left to shift the trigger (when not using random placement).\n :param y_shift: Number of pixels from the right to shift the trigger (when not using random placement).\n :param size: The size the trigger image should be (height, width). Default `None` if no resizing necessary.\n :param mode: The mode the image should be read in. See PIL documentation\n (https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes).\n :param blend: The blending factor\n :return: Backdoored image.\n \"\"\"\n from PIL import Image\n\n n_dim = len(x.shape)\n if n_dim == 4:\n return np.array(\n [\n insert_image(single_img, backdoor_path, channels_first, random, x_shift, y_shift, size, mode, blend)\n for single_img in x\n ]\n )\n\n if n_dim != 3:\n raise ValueError(f\"Invalid array shape {x.shape}\")\n\n original_dtype = x.dtype\n data = np.copy(x)\n if channels_first:\n data = np.transpose(data, (1, 2, 0))\n\n height, width, num_channels = data.shape\n\n no_color = num_channels == 1\n orig_img = Image.new(\"RGBA\", (width, height), 0) # height and width are swapped for PIL\n backdoored_img = Image.new(\"RGBA\", (width, height), 0) # height and width are swapped for PIL\n\n if no_color:\n backdoored_input = Image.fromarray((data * 255).astype(np.uint8).squeeze(axis=2), mode=mode)\n else:\n backdoored_input = Image.fromarray((data * 255).astype(np.uint8), mode=mode)\n\n orig_img.paste(backdoored_input)\n\n trigger = Image.open(backdoor_path).convert(\"RGBA\")\n if size is not None:\n trigger = trigger.resize((size[1], size[0])) # height and width are swapped for PIL\n\n backdoor_width, backdoor_height = trigger.size # height and width are swapped for PIL\n\n if backdoor_width > width or backdoor_height > height:\n raise ValueError(\"Backdoor does not fit inside original image\")\n\n if random:\n x_shift = np.random.randint(width - backdoor_width + 1)\n y_shift = np.random.randint(height - backdoor_height + 1)\n\n backdoored_img.paste(trigger, (x_shift, y_shift), mask=trigger)\n composite = Image.alpha_composite(orig_img, backdoored_img)\n backdoored_img = Image.blend(orig_img, composite, blend)\n backdoored_img = backdoored_img.convert(mode)\n\n res = np.asarray(backdoored_img) / 255.0\n\n if no_color:\n res = np.expand_dims(res, 2)\n\n if channels_first:\n res = np.transpose(res, (2, 0, 1))\n\n return res.astype(original_dtype)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing multiple types of defences against adversarial attacks.\n\"\"\"\n\nfrom art.defences import detector\nfrom art.defences import postprocessor\nfrom art.defences import preprocessor\nfrom art.defences import trainer\nfrom art.defences import transformer\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing detector-based defences against adversarial attacks.\n\"\"\"\n\nfrom art.defences.detector import evasion\nfrom art.defences.detector import poison\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing detector-based defences against evasion attacks.\n\"\"\"\n\nfrom art.defences.detector.evasion.evasion_detector import EvasionDetector\nfrom art.defences.detector.evasion.binary_input_detector import BinaryInputDetector\nfrom art.defences.detector.evasion.binary_activation_detector import BinaryActivationDetector\nfrom art.defences.detector.evasion.subsetscanning.detector import SubsetScanningDetector\nfrom art.defences.detector.evasion.beyond_detector import BeyondDetectorPyTorch\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/beyond_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the BEYOND detector for adversarial examples detection.\n\n| Paper link: https://openreview.net/pdf?id=S4LqI6CcJ3\n\"\"\"\nfrom __future__ import annotations\n\nimport math\nfrom typing import TYPE_CHECKING, Callable\n\nimport numpy as np\n\nif TYPE_CHECKING:\n import torch\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\n\nfrom art.defences.detector.evasion.evasion_detector import EvasionDetector\n\n\nclass BeyondDetectorPyTorch(EvasionDetector):\n \"\"\"\n BEYOND detector for adversarial samples detection.\n This detector uses a combination of SSL and target model predictions to detect adversarial examples.\n\n | Paper link: https://openreview.net/pdf?id=S4LqI6CcJ3\n \"\"\"\n\n defence_params = [\"target_model\", \"ssl_model\", \"augmentations\", \"aug_num\", \"alpha\", \"var_K\", \"percentile\"]\n\n def __init__(\n self,\n target_classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n ssl_classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n augmentations: Callable,\n aug_num: int = 50,\n alpha: float = 0.8,\n var_K: int = 20,\n percentile: int = 5,\n ) -> None:\n \"\"\"\n Initialize the BEYOND detector.\n\n :param target_classifier: The target model to be protected\n :param ssl_classifier: The self-supervised learning model used for feature extraction\n :param augmentations: data augmentations for generating neighborhoods\n :param aug_num: Number of augmentations to apply to each sample (default: 50)\n :param alpha: Weight factor for combining label and representation similarities (default: 0.8)\n :param var_K: Number of top similarities to consider (default: 20)\n :param percentile: using to calculate the threshold\n \"\"\"\n import torch\n\n super().__init__()\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.target_model = target_classifier.model.to(self.device)\n self.ssl_model = ssl_classifier.model.to(self.device)\n self.aug_num = aug_num\n self.alpha = alpha\n self.var_K = var_K\n\n self.backbone = self.ssl_model.backbone\n self.model_classifier = self.ssl_model.classifier\n self.projector = self.ssl_model.projector\n\n self.img_augmentations = augmentations\n\n self.percentile = percentile # determine the threshold\n self.threshold: float | None = None\n\n def _multi_transform(self, img: \"torch.Tensor\") -> \"torch.Tensor\":\n import torch\n\n return torch.stack([self.img_augmentations(img) for _ in range(self.aug_num)], dim=1)\n\n def _get_metrics(self, x: np.ndarray, batch_size: int = 128) -> np.ndarray:\n \"\"\"\n Calculate similarities that combining label consistency and representation similarity for given samples\n\n :param x: Input samples\n :param batch_size: Batch size for processing\n :return: A report similarities\n \"\"\"\n import torch\n import torch.nn.functional as F\n\n samples = torch.from_numpy(x).to(self.device)\n\n self.target_model.eval()\n self.backbone.eval() # type: ignore\n self.model_classifier.eval() # type: ignore\n self.projector.eval() # type: ignore\n\n number_batch = int(math.ceil(len(samples) / batch_size))\n\n similarities_list = []\n\n with torch.no_grad():\n for index in range(number_batch):\n start = index * batch_size\n end = min((index + 1) * batch_size, len(samples))\n\n batch_samples = samples[start:end]\n b, c, h, w = batch_samples.shape\n\n trans_images = self._multi_transform(batch_samples).to(self.device)\n ssl_backbone_out = self.backbone(batch_samples) # type: ignore\n\n ssl_repre = self.projector(ssl_backbone_out) # type: ignore\n ssl_pred = self.model_classifier(ssl_backbone_out) # type: ignore\n ssl_label = torch.max(ssl_pred, -1)[1]\n\n aug_backbone_out = self.backbone(trans_images.reshape(-1, c, h, w)) # type: ignore\n aug_repre = self.projector(aug_backbone_out) # type: ignore\n aug_pred = self.model_classifier(aug_backbone_out) # type: ignore\n aug_pred = aug_pred.reshape(b, self.aug_num, -1)\n\n sim_repre = F.cosine_similarity(\n ssl_repre.unsqueeze(dim=1), aug_repre.reshape(b, self.aug_num, -1), dim=2\n )\n\n sim_preds = F.cosine_similarity(\n F.one_hot(ssl_label, num_classes=ssl_pred.shape[-1]).unsqueeze(dim=1),\n aug_pred,\n dim=2,\n )\n\n similarities_list.append(\n (self.alpha * sim_preds + (1 - self.alpha) * sim_repre).sort(descending=True)[0].cpu().numpy()\n )\n\n similarities = np.concatenate(similarities_list, axis=0)\n\n return similarities\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Determine a threshold that covers 95% of clean samples.\n\n :param x: Clean sample data\n :param y: Clean sample labels (not used in this method)\n :param batch_size: Batch size for processing\n :param nb_epochs: Number of training epochs (not used in this method)\n \"\"\"\n clean_metrics = self._get_metrics(x=x, batch_size=batch_size)\n k_minus_one_metrics = clean_metrics[:, self.var_K - 1]\n self.threshold = np.percentile(k_minus_one_metrics, q=self.percentile)\n\n def detect(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> tuple[np.ndarray, np.ndarray]: # type: ignore\n \"\"\"\n Detect whether given samples are adversarial\n\n :param x: Input samples\n :param batch_size: Batch size for processing\n :return: (report, is_adversarial):\n where report containing detection results\n where is_adversarial is a boolean list indicating whether samples are adversarial or not\n \"\"\"\n if self.threshold is None:\n raise ValueError(\"Detector has not been fitted. Call fit() before detect().\")\n\n similarities = self._get_metrics(x, batch_size)\n\n report = similarities[:, self.var_K - 1]\n is_adversarial = report < self.threshold\n\n return report, is_adversarial\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/binary_activation_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule containing different methods for the detection of adversarial examples. All models are considered to be binary\ndetectors.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.detector.evasion.evasion_detector import EvasionDetector\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass BinaryActivationDetector(EvasionDetector):\n \"\"\"\n Binary detector of adversarial samples coming from evasion attacks. The detector uses an architecture provided by\n the user and is trained on the values of the activations of a classifier at a given layer.\n \"\"\"\n\n defence_params = [\"classifier\", \"detector\", \"layer\"]\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n detector: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n layer: int | str,\n ) -> None:\n \"\"\"\n Create a `BinaryActivationDetector` instance which performs binary classification on activation information.\n The shape of the input of the detector has to match that of the output of the chosen layer.\n\n :param classifier: The classifier of which the activation information is to be used for detection.\n :param detector: The detector architecture to be trained and applied for the binary classification.\n :param layer: Layer for computing the activations to use for training the detector.\n \"\"\"\n super().__init__()\n self.classifier = classifier\n self.detector = detector\n\n # Ensure that layer is well-defined:\n if classifier.layer_names is None:\n raise ValueError(\"No layer names identified.\")\n\n if isinstance(layer, int):\n if layer < 0 or layer >= len(classifier.layer_names):\n raise ValueError(\n f\"Layer index {layer} is outside of range (0 to {len(classifier.layer_names) - 1} included).\"\n )\n self._layer_name = classifier.layer_names[layer]\n else:\n if layer not in classifier.layer_names:\n raise ValueError(f\"Layer name {layer} is not part of the graph.\")\n self._layer_name = layer\n\n def _get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n x_activations = self.classifier.get_activations(x, layer, batch_size, framework)\n if x_activations is None:\n raise ValueError(\"Classifier activations are null.\")\n\n if isinstance(x_activations, np.ndarray):\n return x_activations\n\n return x_activations.numpy()\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the detector using training data.\n\n :param x: Training set to fit the detector.\n :param y: Labels for the training set.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Other parameters.\n \"\"\"\n x_activations: np.ndarray = self._get_activations(x, self._layer_name, batch_size)\n self.detector.fit(x_activations, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def detect(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> tuple[dict, np.ndarray]:\n \"\"\"\n Perform detection of adversarial data and return prediction as tuple.\n\n :param x: Data sample on which to perform detection.\n :param batch_size: Size of batches.\n :return: (report, is_adversarial):\n where report is a dictionary containing the detector model output predictions;\n where is_adversarial is a boolean list of per-sample prediction whether the sample is adversarial\n or not and has the same `batch_size` (first dimension) as `x`.\n \"\"\"\n x_activations: np.ndarray = self._get_activations(x, self._layer_name, batch_size)\n predictions = self.detector.predict(x_activations, batch_size=batch_size)\n is_adversarial = np.argmax(predictions, axis=1).astype(bool)\n report = {\"predictions\": predictions}\n\n return report, is_adversarial\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/binary_input_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule containing different methods for the detection of adversarial examples. All models are considered to be binary\ndetectors.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.detector.evasion.evasion_detector import EvasionDetector\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass BinaryInputDetector(EvasionDetector):\n \"\"\"\n Binary detector of adversarial samples coming from evasion attacks. The detector uses an architecture provided by\n the user and trains it on data labeled as clean (label 0) or adversarial (label 1).\n \"\"\"\n\n defence_params = [\"detector\"]\n\n def __init__(self, detector: \"CLASSIFIER_NEURALNETWORK_TYPE\") -> None:\n \"\"\"\n Create a `BinaryInputDetector` instance which performs binary classification on input data.\n\n :param detector: The detector architecture to be trained and applied for the binary classification.\n \"\"\"\n super().__init__()\n self.detector = detector\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the detector using clean and adversarial samples.\n\n :param x: Training set to fit the detector.\n :param y: Labels for the training set.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Other parameters.\n \"\"\"\n self.detector.fit(x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def detect(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> tuple[dict, np.ndarray]:\n \"\"\"\n Perform detection of adversarial data and return prediction as tuple.\n\n :param x: Data sample on which to perform detection.\n :param batch_size: Size of batches.\n :return: (report, is_adversarial):\n where report is a dictionary containing the detector model output predictions;\n where is_adversarial is a boolean list of per-sample prediction whether the sample is adversarial\n or not and has the same `batch_size` (first dimension) as `x`.\n \"\"\"\n predictions = self.detector.predict(x, batch_size=batch_size)\n is_adversarial = np.argmax(predictions, axis=1).astype(bool)\n report = {\"predictions\": predictions}\n\n return report, is_adversarial\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/evasion_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for all evasion detectors.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import Any\n\nimport numpy as np\n\n\nclass EvasionDetector(abc.ABC):\n \"\"\"\n Abstract base class for all evasion detectors.\n \"\"\"\n\n defence_params: list[str] = []\n\n def __init__(self) -> None:\n \"\"\"\n Create an evasion detector object.\n \"\"\"\n pass\n\n @abc.abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the detection classifier if necessary.\n\n :param x: Training set to fit the detector.\n :param y: Labels for the training set.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Other parameters.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def detect(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> tuple[dict, np.ndarray]:\n \"\"\"\n Perform detection of adversarial data and return prediction as tuple.\n\n :param x: Data sample on which to perform detection.\n :param batch_size: Size of batches.\n :param kwargs: Defence-specific parameters used by child classes.\n :return: (report, is_adversarial):\n where report is a dictionary containing information specific to the detection defence;\n where is_adversarial is a boolean list of per-sample prediction whether the sample is adversarial\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and apply defence-specific checks before saving them as attributes.\n\n :param kwargs: A dictionary of defence-specific parameters.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.defence_params:\n setattr(self, key, value)\n self._check_params()\n\n def get_params(self) -> dict[str, Any]:\n \"\"\"\n Returns dictionary of parameters used to run defence.\n\n :return: Dictionary of parameters of the method.\n \"\"\"\n dictionary = {param: getattr(self, param) for param in self.defence_params}\n return dictionary\n\n def _check_params(self) -> None:\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/subsetscanning/detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the fast generalized subset scan based detector.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport sys\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn import metrics\nfrom tqdm.auto import trange, tqdm\n\nfrom art.defences.detector.evasion.evasion_detector import EvasionDetector\nfrom art.defences.detector.evasion.subsetscanning.scanner import Scanner\nfrom art.defences.detector.evasion.subsetscanning.scoring_functions import ScoringFunctions\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SubsetScanningDetector(EvasionDetector):\n \"\"\"\n Fast generalized subset scan based detector by McFowland, E., Speakman, S., and Neill, D. B. (2013).\n\n | Paper link: https://www.cs.cmu.edu/~neill/papers/mcfowland13a.pdf\n \"\"\"\n\n defence_params = [\"classifier\", \"bgd_data\", \"layer\", \"scoring_function\", \"verbose\"]\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n bgd_data: np.ndarray,\n layer: int | str,\n scoring_function: Literal[\"BerkJones\", \"HigherCriticism\", \"KolmarovSmirnov\"] = \"BerkJones\",\n verbose: bool = True,\n ) -> None:\n \"\"\"\n Create a `SubsetScanningDetector` instance which is used to the detect the presence of adversarial samples.\n\n :param classifier: The model being evaluated for its robustness to anomalies (e.g. adversarial samples).\n :param bgd_data: The background data used to learn a null model. Typically, dataset used to train the\n classifier.\n :param layer: The layer from which to extract activations to perform scan.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__()\n self.classifier = classifier\n self.bgd_data = bgd_data\n self.layer = layer\n self.verbose = verbose\n\n if scoring_function == \"BerkJones\":\n self.scoring_function = ScoringFunctions.get_score_bj_fast\n elif scoring_function == \"HigherCriticism\":\n self.scoring_function = ScoringFunctions.get_score_hc_fast\n elif scoring_function == \"KolmarovSmirnov\":\n self.scoring_function = ScoringFunctions.get_score_ks_fast\n else:\n raise ValueError(\"The provided scoring function is not supported:\", scoring_function)\n\n # Ensure that layer is well-defined\n if classifier.layer_names is None:\n raise ValueError(\"No layer names identified.\")\n\n if isinstance(layer, int):\n if layer < 0 or layer >= len(classifier.layer_names):\n raise ValueError(\n f\"Layer index {layer} is outside of range (0 to {len(classifier.layer_names) - 1} included).\"\n )\n self._layer_name = classifier.layer_names[layer]\n else:\n if layer not in classifier.layer_names:\n raise ValueError(f\"Layer name {layer} is not part of the graph.\")\n self._layer_name = layer\n\n # Background data activations\n bgd_activations = self._get_activations(bgd_data, self._layer_name, batch_size=128)\n if len(bgd_activations.shape) == 4:\n dim2 = bgd_activations.shape[1] * bgd_activations.shape[2] * bgd_activations.shape[3]\n bgd_activations = np.reshape(bgd_activations, (bgd_activations.shape[0], dim2))\n self.sorted_bgd_activations = np.sort(bgd_activations, axis=0)\n\n # Background data scores\n pval_ranges = self._calculate_pvalue_ranges(bgd_data)\n bgd_scores = []\n for pval_range in pval_ranges:\n best_score, _, _, _ = Scanner.fgss_individ_for_nets(pval_range, score_function=self.scoring_function)\n bgd_scores.append(best_score)\n self.bgd_scores = np.asarray(bgd_scores)\n\n def _get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n x_activations = self.classifier.get_activations(x, layer, batch_size, framework)\n if x_activations is None:\n raise ValueError(\"Classifier activations are null.\")\n\n if isinstance(x_activations, np.ndarray):\n return x_activations\n\n return x_activations.numpy()\n\n def _calculate_pvalue_ranges(self, x: np.ndarray, batch_size: int = 128) -> np.ndarray:\n \"\"\"\n Returns computed p-value ranges.\n\n :param x: Data being evaluated for anomalies.\n :return: p-value ranges.\n \"\"\"\n bgd_activations = self.sorted_bgd_activations\n eval_activations = self._get_activations(x, self._layer_name, batch_size)\n\n if len(eval_activations.shape) == 4:\n dim2 = eval_activations.shape[1] * eval_activations.shape[2] * eval_activations.shape[3]\n eval_activations = np.reshape(eval_activations, (eval_activations.shape[0], dim2))\n\n bgrecords_n = bgd_activations.shape[0]\n records_n = eval_activations.shape[0]\n atrr_n = eval_activations.shape[1]\n\n pvalue_ranges = np.empty((records_n, atrr_n, 2))\n\n for j in range(atrr_n):\n pvalue_ranges[:, j, 0] = np.searchsorted(bgd_activations[:, j], eval_activations[:, j], side=\"right\")\n pvalue_ranges[:, j, 1] = np.searchsorted(bgd_activations[:, j], eval_activations[:, j], side=\"left\")\n\n pvalue_ranges = bgrecords_n - pvalue_ranges\n\n pvalue_ranges[:, :, 0] = np.divide(pvalue_ranges[:, :, 0], bgrecords_n + 1)\n pvalue_ranges[:, :, 1] = np.divide(pvalue_ranges[:, :, 1] + 1, bgrecords_n + 1)\n\n return pvalue_ranges\n\n def scan(\n self,\n clean_x: np.ndarray,\n adv_x: np.ndarray,\n clean_size: int | None = None,\n adv_size: int | None = None,\n run: int = 10,\n ) -> tuple[np.ndarray, np.ndarray, float]:\n \"\"\"\n Returns scores of highest scoring subsets.\n\n :param clean_x: Data presumably without anomalies.\n :param adv_x: Data presumably with anomalies (adversarial samples).\n :param clean_size:\n :param adv_size:\n :param run:\n :return: (clean_scores, adv_scores, detection_power).\n \"\"\"\n clean_pval_ranges = self._calculate_pvalue_ranges(clean_x)\n adv_pval_ranges = self._calculate_pvalue_ranges(adv_x)\n\n clean_scores = []\n adv_scores = []\n\n if clean_size is None or adv_size is None:\n # Individual scan\n with tqdm(\n total=len(clean_pval_ranges) + len(adv_pval_ranges), desc=\"Subset scanning\", disable=not self.verbose\n ) as pbar:\n for _, c_p in enumerate(clean_pval_ranges):\n best_score, _, _, _ = Scanner.fgss_individ_for_nets(c_p, score_function=self.scoring_function)\n clean_scores.append(best_score)\n pbar.update(1)\n for _, a_p in enumerate(adv_pval_ranges):\n best_score, _, _, _ = Scanner.fgss_individ_for_nets(a_p, score_function=self.scoring_function)\n adv_scores.append(best_score)\n pbar.update(1)\n\n else:\n len_adv_x = len(adv_x)\n len_clean_x = len(clean_x)\n\n for _ in trange(run, desc=\"Subset scanning\", disable=not self.verbose):\n np.random.seed()\n\n clean_choice = np.random.choice(range(len_clean_x), clean_size, replace=False)\n adv_choice = np.random.choice(range(len_adv_x), adv_size, replace=False)\n\n combined_pvals = np.concatenate((clean_pval_ranges[clean_choice], adv_pval_ranges[adv_choice]), axis=0)\n\n best_score, _, _, _ = Scanner.fgss_for_nets(\n clean_pval_ranges[clean_choice], score_function=self.scoring_function\n )\n clean_scores.append(best_score)\n best_score, _, _, _ = Scanner.fgss_for_nets(combined_pvals, score_function=self.scoring_function)\n adv_scores.append(best_score)\n\n clean_scores_array = np.asarray(clean_scores)\n adv_scores_array = np.asarray(adv_scores)\n\n y_true = np.concatenate([np.ones(len(adv_scores)), np.zeros(len(clean_scores))])\n all_scores = np.concatenate([adv_scores, clean_scores])\n\n fpr, tpr, _ = metrics.roc_curve(y_true, all_scores)\n roc_auc: float = metrics.auc(fpr, tpr)\n detection_power = roc_auc\n\n return clean_scores_array, adv_scores_array, detection_power\n\n def detect(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> tuple[dict, np.ndarray]:\n \"\"\"\n Perform detection of adversarial data and return prediction as tuple.\n\n :param x: Data sample on which to perform detection.\n :param batch_size: Size of batches.\n :return: (report, is_adversarial):\n where report is a dictionary containing information specified by the subset scanning method;\n where is_adversarial is a boolean list of per-sample prediction whether the sample is adversarial\n or not and has the same `batch_size` (first dimension) as `x`.\n \"\"\"\n pval_ranges = self._calculate_pvalue_ranges(x, batch_size)\n scores = []\n\n for pval_range in tqdm(pval_ranges, desc=\"Subset scanning\", disable=not self.verbose):\n best_score, _, _, _ = Scanner.fgss_individ_for_nets(pval_range, score_function=self.scoring_function)\n scores.append(best_score)\n scores_array = np.asarray(scores)\n\n is_adversarial = np.greater(scores_array, self.bgd_scores.max())\n report = {\"scores\": scores_array}\n\n return report, is_adversarial\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the detector using training data. Assumes that the classifier is already trained.\n\n :raises `NotImplementedException`: This method is not supported for this detector.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/subsetscanning/scanner.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nSubset scanning based on FGSS\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\n\nimport numpy as np\n\nfrom art.defences.detector.evasion.subsetscanning.scoring_functions import ScoringFunctions\nfrom art.defences.detector.evasion.subsetscanning.scanningops import ScanningOps\n\n\nclass Scanner:\n \"\"\"\n Fast generalized subset scan\n\n | Paper link: https://www.cs.cmu.edu/~neill/papers/mcfowland13a.pdf\n \"\"\"\n\n @staticmethod\n def fgss_individ_for_nets(\n pvalues: np.ndarray,\n a_max: float = 0.5,\n score_function: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray] = ScoringFunctions.get_score_bj_fast,\n ) -> tuple[float, np.ndarray, np.ndarray, float]:\n \"\"\"\n Finds the highest scoring subset of records and attribute. Return the subsets, the score, and the alpha that\n maximizes the score.\n\n A simplified, faster, exact method but only useable when scoring an individual input. This method recognizes\n that for an individual input, the priority function for a fixed alpha threshold results in all nodes having\n either priority 1 or 0. That is, the pmax is either below the threshold or not. Due to convexity of the scoring\n function we know elements with tied priority are either all included or all excluded. Therefore, each alpha\n threshold uniquely defines a single subset of nodes to be scored. These are the nodes that have pmax less than\n threshold. This means the individual-input scanner is equivalent to sorting pmax values and iteratively adding\n the next largest pmax. There are at most O(N) of these subsets to consider. Sorting requires O(N ln N). There is\n no iterative ascent required and no special choice of alpha thresholds for speed improvements.\n\n :param pvalues: pvalue ranges.\n :param a_max: alpha max. determines the significance level threshold\n :param score_function: scoring function\n :return: (best_score, image_sub, node_sub, optimal_alpha)\n \"\"\"\n pmaxes = np.reshape(pvalues[:, 1], pvalues.shape[0]) # should be number of columns/nodes\n # we can ignore any pmax that is greater than a_max; this makes sorting faster\n # all the pvalues less than equal a_max are kept by nonzero result of the comparison\n potential_thresholds = pmaxes[np.flatnonzero(pmaxes <= a_max)]\n\n # sorrted_unique provides our alpha thresholds that we will scan\n # count_unique (in cumulative format) will provide the number of observations less than corresponding alpha\n sorted_unique, count_unique = np.unique(potential_thresholds, return_counts=True)\n\n cumulative_count = np.cumsum(count_unique)\n # In individual input case we have n_a = N, so cumulative count is used for both.\n # sorted_unique provides the increasing alpha values that need to be checked.\n vector_of_scores = score_function(cumulative_count, cumulative_count, sorted_unique)\n\n # scoring completed, now grab the max (and index)\n best_score_idx = np.argmax(vector_of_scores)\n best_score = vector_of_scores[best_score_idx]\n optimal_alpha = sorted_unique[best_score_idx]\n # best_size = cumulative_count[best_score_idx]\n\n # In order to determine which nodes are included, we look for all pmaxes less than or equal best alpha\n node_sub = np.flatnonzero(pvalues[:, 1] <= optimal_alpha)\n # in the individual input case there's only 1 possible subset of inputs to return - a 1x1 with index 0\n image_sub = np.array([0])\n\n return best_score, image_sub, node_sub, optimal_alpha\n\n @staticmethod\n def fgss_for_nets(\n pvalues: np.ndarray,\n a_max: float = 0.5,\n restarts: int = 10,\n image_to_node_init: bool = False,\n score_function: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray] = ScoringFunctions.get_score_bj_fast,\n ) -> tuple[float, np.ndarray, np.ndarray, float]:\n \"\"\"\n Finds the highest scoring subset of records and attribute. Return the subsets, the score, and the alpha that\n maximizes the score iterates between images and nodes, each time performing NPSS efficient maximization.\n\n :param pvalues: pvalue ranges.\n :param a_max: alpha threshold\n :param restarts: number of iterative restarts\n :param image_to_node_init: intializes what direction to begin the search: image to node or vice-versa\n :param score_function: scoring function\n :return: (best_score, image_sub, node_sub, optimal_alpha)\n \"\"\"\n best_score = -100000.0\n\n if len(pvalues) < restarts:\n restarts = len(pvalues)\n\n for r_indx in range(0, restarts): # do random restarts to come close to global maximum\n image_to_node = image_to_node_init\n if r_indx == 0:\n if image_to_node:\n # all 1's for number of rows\n indices_of_seeds = np.arange(pvalues.shape[0])\n else:\n # all 1's for number of cols\n indices_of_seeds = np.arange(pvalues.shape[1])\n\n (\n best_score_from_restart,\n best_image_sub_from_restart,\n best_node_sub_from_restart,\n best_alpha_from_restart,\n ) = ScanningOps.single_restart(pvalues, a_max, indices_of_seeds, image_to_node, score_function)\n\n if best_score_from_restart > best_score:\n best_score = best_score_from_restart\n image_sub = best_image_sub_from_restart\n node_sub = best_node_sub_from_restart\n optimal_alpha = best_alpha_from_restart\n\n # Finished A Restart\n else:\n # New Restart\n # some some randomizing and only leave in a random number of rows of pvalues TODO\n prob = np.random.uniform(0, 1)\n if image_to_node:\n indices_of_seeds = np.random.choice(\n np.arange(pvalues.shape[0]),\n int(pvalues.shape[0] * prob),\n replace=False,\n )\n else:\n indices_of_seeds = np.random.choice(\n np.arange(pvalues.shape[1]),\n int(pvalues.shape[1] * prob),\n replace=False,\n )\n while indices_of_seeds.size == 0:\n # eventually will make non zero\n prob = np.random.uniform(0, 1)\n if image_to_node:\n indices_of_seeds = np.random.choice(\n np.arange(pvalues.shape[0]),\n int(pvalues.shape[0] * prob),\n replace=False,\n )\n else:\n indices_of_seeds = np.random.choice(\n np.arange(pvalues.shape[1]),\n int(pvalues.shape[1] * prob),\n replace=False,\n )\n\n indices_of_seeds.astype(int)\n # process a random subset of rows of pvalues array\n (\n best_score_from_restart,\n best_image_sub_from_restart,\n best_node_sub_from_restart,\n best_alpha_from_restart,\n ) = ScanningOps.single_restart(pvalues, a_max, indices_of_seeds, image_to_node, score_function)\n\n if best_score_from_restart > best_score:\n best_score = best_score_from_restart\n image_sub = best_image_sub_from_restart\n node_sub = best_node_sub_from_restart\n optimal_alpha = best_alpha_from_restart\n\n # Finished A Restart\n\n return best_score, image_sub, node_sub, optimal_alpha\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/subsetscanning/scanningops.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nScanning operations\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\n\nimport numpy as np\n\n\nclass ScanningOps:\n \"\"\"\n Specific operations done during scanning\n \"\"\"\n\n @staticmethod\n def optimize_in_single_dimension(\n pvalues: np.ndarray,\n a_max: float,\n image_to_node: bool,\n score_function: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray],\n ) -> tuple[float, np.ndarray, float]:\n \"\"\"\n Optimizes over all subsets of nodes for a given subset of images or over all subsets of images for a given\n subset of nodes.\n\n :param pvalues: pvalue ranges.\n :param a_max: Determines the significance level threshold.\n :param image_to_node: Informs the direction for optimization.\n :param score_function: Scoring function.\n :return: (best_score_so_far, subset, best_alpha).\n \"\"\"\n alpha_thresholds = np.unique(pvalues[:, :, 1])\n\n # alpha_thresholds = alpha_thresholds[0::5] #take every 5th for speed purposes\n # where does a_max fall in check\n last_alpha_index = int(np.searchsorted(alpha_thresholds, a_max))\n # resize check for only ones smaller than a_max\n alpha_thresholds = alpha_thresholds[0:last_alpha_index]\n\n step_for_50 = len(alpha_thresholds) / 50\n alpha_thresholds = alpha_thresholds[0 :: int(step_for_50) + 1]\n # add on the max value to check as well as it may not have been part of unique\n alpha_thresholds = np.append(alpha_thresholds, a_max)\n\n # alpha_thresholds = np.arange(a_max/50, a_max, a_max/50)\n\n if image_to_node:\n number_of_elements = pvalues.shape[1] # searching over j columns\n size_of_given = pvalues.shape[0] # for fixed this many images\n unsort_priority = np.zeros((pvalues.shape[1], alpha_thresholds.shape[0])) # number of columns\n else:\n number_of_elements = pvalues.shape[0] # searching over i rows\n size_of_given = pvalues.shape[1] # for this many fixed nodes\n unsort_priority = np.zeros((pvalues.shape[0], alpha_thresholds.shape[0])) # number of rows\n\n for elem_indx in range(0, number_of_elements):\n # sort all the range maxes\n if image_to_node:\n # collect ranges over images(rows)\n arg_sort_max = np.argsort(pvalues[:, elem_indx, 1])\n # arg_sort_min = np.argsort(pvalues[:,e,0]) #collect ranges over images(rows)\n completely_included = np.searchsorted(\n pvalues[:, elem_indx, 1][arg_sort_max],\n alpha_thresholds,\n side=\"right\",\n )\n else:\n # collect ranges over nodes(columns)\n arg_sort_max = np.argsort(pvalues[elem_indx, :, 1])\n # arg_sort_min = np.argsort(pvalues[elem_indx,:,0])\n\n completely_included = np.searchsorted(\n pvalues[elem_indx, :, 1][arg_sort_max],\n alpha_thresholds,\n side=\"right\",\n )\n\n # should be num elements by num thresh\n unsort_priority[elem_indx, :] = completely_included\n\n # want to sort for a fixed thresh (across?)\n arg_sort_priority = np.argsort(-unsort_priority, axis=0)\n\n best_score_so_far = -10000\n best_alpha = -2\n\n alpha_count = 0\n for alpha_threshold in alpha_thresholds:\n\n # score each threshold by itself, cumulating priority,\n # cumulating count, alpha stays same.\n alpha_v = np.ones(number_of_elements) * alpha_threshold\n\n n_alpha_v = np.cumsum(unsort_priority[:, alpha_count][arg_sort_priority][:, alpha_count])\n count_increments_this = np.ones(number_of_elements) * size_of_given\n n_v = np.cumsum(count_increments_this)\n\n vector_of_scores = score_function(n_alpha_v, n_v, alpha_v)\n\n best_score_for_this_alpha_idx = np.argmax(vector_of_scores)\n best_score_for_this_alpha = vector_of_scores[best_score_for_this_alpha_idx]\n\n if best_score_for_this_alpha > best_score_so_far:\n best_score_so_far = best_score_for_this_alpha\n best_size = best_score_for_this_alpha_idx + 1 # not sure 1 is needed?\n best_alpha = alpha_threshold\n best_alpha_count = alpha_count\n alpha_count = alpha_count + 1\n\n # after the alpha for loop we now have the best score, the best alpha, size of the best subset,\n # and alpha counter use these with the priority argsort to reconstruct the best subset\n unsort = arg_sort_priority[:, best_alpha_count]\n\n subset = np.zeros(best_size).astype(int)\n for loc in range(0, best_size):\n subset[loc] = unsort[loc]\n\n return best_score_so_far, subset, best_alpha\n\n @staticmethod\n def single_restart(\n pvalues: np.ndarray,\n a_max: float,\n indices_of_seeds: np.ndarray,\n image_to_node: bool,\n score_function: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray],\n ) -> tuple[float, np.ndarray, np.ndarray, float]:\n \"\"\"\n Here we control the iteration between images->nodes and nodes->images. It starts with a fixed subset of nodes by\n default.\n\n :param pvalues: pvalue ranges.\n :param a_max: Determines the significance level threshold.\n :param indices_of_seeds: Indices of initial sets of images or nodes to perform optimization.\n :param image_to_node: Informs the direction for optimization.\n :param score_function: Scoring function.\n :return: (best_score_so_far, best_sub_of_images, best_sub_of_nodes, best_alpha).\n \"\"\"\n best_score_so_far = -100000.0\n count = 0\n\n while True:\n # These can be moved outside the while loop as only executed first time through??\n if count == 0: # first time through, we need something initialized depending on direction.\n if image_to_node:\n sub_of_images = indices_of_seeds\n else:\n sub_of_nodes = indices_of_seeds\n\n if image_to_node: # passed pvalues are only those belonging to fixed images, update nodes in return\n # only sending sub of images\n (\n score_from_optimization,\n sub_of_nodes,\n optimal_alpha,\n ) = ScanningOps.optimize_in_single_dimension(\n pvalues[sub_of_images, :, :], a_max, image_to_node, score_function\n )\n else: # passed pvalues are only those belonging to fixed nodes, update images in return\n # only sending sub of nodes\n (\n score_from_optimization,\n sub_of_images,\n optimal_alpha,\n ) = ScanningOps.optimize_in_single_dimension(\n pvalues[:, sub_of_nodes, :], a_max, image_to_node, score_function\n )\n\n if score_from_optimization > best_score_so_far: # haven't converged yet\n # update\n best_score_so_far = score_from_optimization\n best_sub_of_nodes = sub_of_nodes\n best_sub_of_images = sub_of_images\n best_alpha = optimal_alpha\n\n image_to_node = not image_to_node # switch direction!\n count = count + 1 # for printing and\n else: # converged! Don't update from most recent optimization, return current best\n return (\n best_score_so_far,\n best_sub_of_images,\n best_sub_of_nodes,\n best_alpha,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/evasion/subsetscanning/scoring_functions.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nScanner scoring functions.\n\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\n\n\nclass ScoringFunctions:\n \"\"\"\n Scanner scoring functions. These functions are used in the scanner to determine the score of a subset.\n \"\"\"\n\n @staticmethod\n def get_score_bj_fast(n_alpha: np.ndarray, no_records: np.ndarray, alpha: np.ndarray) -> np.ndarray:\n \"\"\"\n BerkJones\n\n :param n_alpha: Number of records less than alpha.\n :param no_records: Number of records.\n :param alpha: Alpha threshold.\n :return: Score.\n \"\"\"\n score = np.zeros(alpha.shape[0])\n inds_tie = n_alpha == no_records\n inds_not_tie = np.logical_not(inds_tie)\n inds_pos = n_alpha > no_records * alpha\n inds_pos_not_tie = np.logical_and(inds_pos, inds_not_tie)\n score[inds_tie] = no_records[inds_tie] * np.log(np.true_divide(1, alpha[inds_tie]))\n\n factor1 = n_alpha[inds_pos_not_tie] * np.log(\n np.true_divide(\n n_alpha[inds_pos_not_tie],\n no_records[inds_pos_not_tie] * alpha[inds_pos_not_tie],\n )\n )\n\n factor2 = no_records[inds_pos_not_tie] - n_alpha[inds_pos_not_tie]\n\n factor3 = np.log(\n np.true_divide(\n no_records[inds_pos_not_tie] - n_alpha[inds_pos_not_tie],\n no_records[inds_pos_not_tie] * (1 - alpha[inds_pos_not_tie]),\n )\n )\n\n score[inds_pos_not_tie] = factor1 + factor2 * factor3\n return score\n\n @staticmethod\n def get_score_hc_fast(n_alpha: np.ndarray, no_records: np.ndarray, alpha: np.ndarray) -> np.ndarray:\n \"\"\"\n HigherCriticism\n Similar to a traditional wald test statistic: (Observed - expected) / standard deviation.\n In this case we use the binomial distribution. The observed is N_a. The expected (under null) is N*a\n and the standard deviation is sqrt(N*a(1-a)).\n\n :param n_alpha: Number of records less than alpha.\n :param no_records: Number of records.\n :param alpha: Alpha threshold.\n :return: Score.\n \"\"\"\n score = np.zeros(alpha.shape[0])\n inds = n_alpha > no_records * alpha\n factor1 = n_alpha[inds] - no_records[inds] * alpha[inds]\n factor2 = np.sqrt(no_records[inds] * alpha[inds] * (1.0 - alpha[inds]))\n score[inds] = np.true_divide(factor1, factor2)\n return score\n\n @staticmethod\n def get_score_ks_fast(n_alpha: np.ndarray, no_records: np.ndarray, alpha: np.ndarray) -> np.ndarray:\n \"\"\"\n KolmarovSmirnov\n\n :param n_alpha: Number of records less than alpha.\n :param no_records: Number of records.\n :param alpha: Alpha threshold.\n :return: Score.\n \"\"\"\n score = np.zeros(alpha.shape[0])\n inds = n_alpha > no_records * alpha\n score[inds] = np.true_divide(n_alpha[inds] - no_records[inds] * alpha[inds], np.sqrt(no_records[inds]))\n return score\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing detector-based defences against poisoning attacks.\n\"\"\"\n\nfrom art.defences.detector.poison.poison_filtering_defence import PoisonFilteringDefence\nfrom art.defences.detector.poison.ground_truth_evaluator import GroundTruthEvaluator\nfrom art.defences.detector.poison.activation_defence import ActivationDefence\nfrom art.defences.detector.poison.clustering_analyzer import ClusteringAnalyzer\nfrom art.defences.detector.poison.provenance_defense import ProvenanceDefense\nfrom art.defences.detector.poison.roni import RONIDefense\nfrom art.defences.detector.poison.spectral_signature_defense import SpectralSignatureDefense\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/activation_defence.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements methods performing poisoning detection based on activations clustering.\n\n| Paper link: https://arxiv.org/abs/1811.03728\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this\n defence, see https://arxiv.org/abs/1905.13409 . For details on how to evaluate classifier security\n in general, see https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport copy\nimport logging\nimport os\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\n\nfrom art.data_generators import DataGenerator\nfrom art.defences.detector.poison.clustering_analyzer import ClusteringAnalyzer\nfrom art.defences.detector.poison.ground_truth_evaluator import GroundTruthEvaluator\nfrom art.defences.detector.poison.poison_filtering_defence import PoisonFilteringDefence\nfrom art.utils import segment_by_class\nfrom art.visualization import create_sprite, save_image, plot_3d\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ActivationDefence(PoisonFilteringDefence):\n \"\"\"\n Method from Chen et al., 2018 performing poisoning detection based on activations clustering.\n\n | Paper link: https://arxiv.org/abs/1811.03728\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this\n defence, see https://arxiv.org/abs/1905.13409 . For details on how to evaluate classifier security\n in general, see https://arxiv.org/abs/1902.06705\n \"\"\"\n\n defence_params = [\n \"nb_clusters\",\n \"clustering_method\",\n \"nb_dims\",\n \"reduce\",\n \"cluster_analysis\",\n \"generator\",\n \"ex_re_threshold\",\n ]\n valid_clustering = [\"KMeans\"]\n valid_reduce = [\"PCA\", \"FastICA\", \"TSNE\"]\n valid_analysis = [\"smaller\", \"distance\", \"relative-size\", \"silhouette-scores\"]\n\n TOO_SMALL_ACTIVATIONS = 32 # Threshold used to print a warning when activations are not enough\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n x_train: np.ndarray,\n y_train: np.ndarray,\n generator: DataGenerator | None = None,\n ex_re_threshold: float | None = None,\n ) -> None:\n \"\"\"\n Create an :class:`.ActivationDefence` object with the provided classifier.\n\n :param classifier: Model evaluated for poison.\n :param x_train: A dataset used to train the classifier.\n :param y_train: Labels used to train the classifier.\n :param generator: A data generator to be used instead of `x_train` and `y_train`.\n :param ex_re_threshold: Set to a positive value to enable exclusionary reclassification\n \"\"\"\n super().__init__(classifier, x_train, y_train)\n self.classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\" = classifier\n self.nb_clusters = 2\n self.clustering_method = \"KMeans\"\n self.nb_dims = 10\n self.reduce = \"PCA\"\n self.cluster_analysis = \"smaller\"\n self.generator = generator\n self.activations_by_class: list[np.ndarray] = []\n self.clusters_by_class: list[np.ndarray] = []\n self.assigned_clean_by_class: np.ndarray\n self.is_clean_by_class: list[np.ndarray] = []\n self.errors_by_class: np.ndarray\n self.red_activations_by_class: list[np.ndarray] = [] # Activations reduced by class\n self.evaluator = GroundTruthEvaluator()\n self.is_clean_lst: list[int] = []\n self.confidence_level: list[float] = []\n self.poisonous_clusters: np.ndarray\n self.clusterer = MiniBatchKMeans(n_clusters=self.nb_clusters)\n self.ex_re_threshold = ex_re_threshold\n self._check_params()\n\n def evaluate_defence(self, is_clean: np.ndarray, **kwargs) -> str:\n \"\"\"\n If ground truth is known, this function returns a confusion matrix in the form of a JSON object.\n\n :param is_clean: Ground truth, where is_clean[i]=1 means that x_train[i] is clean and is_clean[i]=0 means\n x_train[i] is poisonous.\n :param kwargs: A dictionary of defence-specific parameters.\n :return: JSON object with confusion matrix.\n \"\"\"\n if is_clean is None or is_clean.size == 0:\n raise ValueError(\"is_clean was not provided while invoking evaluate_defence.\")\n\n self.set_params(**kwargs)\n\n if not self.activations_by_class and self.generator is None:\n activations = self._get_activations()\n self.activations_by_class = self._segment_by_class(activations, self.y_train)\n\n (\n self.clusters_by_class,\n self.red_activations_by_class,\n ) = self.cluster_activations()\n _, self.assigned_clean_by_class = self.analyze_clusters()\n\n # Now check ground truth:\n if self.generator is not None:\n batch_size = self.generator.batch_size\n num_samples = self.generator.size\n num_classes = self.classifier.nb_classes\n self.is_clean_by_class = [np.empty(0, dtype=int) for _ in range(num_classes)]\n\n # calculate is_clean_by_class for each batch\n for batch_idx in range(num_samples // batch_size): # type: ignore\n _, y_batch = self.generator.get_batch()\n is_clean_batch = is_clean[batch_idx * batch_size : batch_idx * batch_size + batch_size]\n clean_by_class_batch = self._segment_by_class(is_clean_batch, y_batch)\n self.is_clean_by_class = [\n np.append(self.is_clean_by_class[class_idx], clean_by_class_batch[class_idx])\n for class_idx in range(num_classes)\n ]\n\n else:\n self.is_clean_by_class = self._segment_by_class(is_clean, self.y_train)\n self.errors_by_class, conf_matrix_json = self.evaluator.analyze_correctness(\n self.assigned_clean_by_class, self.is_clean_by_class\n )\n return conf_matrix_json\n\n def detect_poison(self, **kwargs) -> tuple[dict[str, Any], list[int]]:\n \"\"\"\n Returns poison detected and a report.\n\n :param clustering_method: clustering algorithm to be used. Currently, `KMeans` is the only method supported\n :type clustering_method: `str`\n :param nb_clusters: number of clusters to find. This value needs to be greater or equal to one\n :type nb_clusters: `int`\n :param reduce: method used to reduce dimensionality of the activations. Supported methods include `PCA`,\n `FastICA` and `TSNE`\n :type reduce: `str`\n :param nb_dims: number of dimensions to be reduced\n :type nb_dims: `int`\n :param cluster_analysis: heuristic to automatically determine if a cluster contains poisonous data. Supported\n methods include `smaller` and `distance`. The `smaller` method defines as poisonous the\n cluster with fewer of data points, while the `distance` heuristic uses the\n distance between the clusters.\n :type cluster_analysis: `str`\n :return: (report, is_clean_lst):\n where a report is a dict object that contains information specified by the clustering analysis technique\n where is_clean is a list, where is_clean_lst[i]=1 means that x_train[i]\n there is clean and is_clean_lst[i]=0, means that x_train[i] was classified as poison.\n \"\"\"\n old_nb_clusters = self.nb_clusters\n self.set_params(**kwargs)\n if self.nb_clusters != old_nb_clusters:\n self.clusterer = MiniBatchKMeans(n_clusters=self.nb_clusters)\n\n if self.generator is not None:\n self.clusters_by_class, self.red_activations_by_class = self.cluster_activations()\n report, self.assigned_clean_by_class = self.analyze_clusters()\n\n batch_size = self.generator.batch_size\n num_samples = self.generator.size\n self.is_clean_lst = []\n\n # loop though the generator to generator a report\n for _ in range(num_samples // batch_size): # type: ignore\n _, y_batch = self.generator.get_batch()\n indices_by_class = self._segment_by_class(np.arange(batch_size), y_batch)\n is_clean_lst = [0] * batch_size\n for class_idx, idxs in enumerate(indices_by_class):\n for idx_in_class, idx in enumerate(idxs):\n is_clean_lst[idx] = self.assigned_clean_by_class[class_idx][idx_in_class]\n self.is_clean_lst += is_clean_lst\n return report, self.is_clean_lst\n\n if not self.activations_by_class:\n activations = self._get_activations()\n self.activations_by_class = self._segment_by_class(activations, self.y_train)\n (\n self.clusters_by_class,\n self.red_activations_by_class,\n ) = self.cluster_activations()\n report, self.assigned_clean_by_class = self.analyze_clusters()\n # Here, assigned_clean_by_class[i][j] is 1 if the jth data point in the ith class was\n # determined to be clean by activation cluster\n\n # Build an array that matches the original indexes of x_train\n n_train = len(self.x_train)\n indices_by_class = self._segment_by_class(np.arange(n_train), self.y_train)\n self.is_clean_lst = [0] * n_train\n\n for assigned_clean, indices_dp in zip(self.assigned_clean_by_class, indices_by_class):\n for assignment, index_dp in zip(assigned_clean, indices_dp):\n if assignment == 1:\n self.is_clean_lst[index_dp] = 1\n\n if self.ex_re_threshold is not None:\n if self.generator is not None:\n raise RuntimeError(\"Currently, exclusionary reclassification cannot be used with generators\")\n if hasattr(self.classifier, \"clone_for_refitting\"):\n report = self.exclusionary_reclassification(report)\n else:\n logger.warning(\"Classifier does not have clone_for_refitting method defined. Skipping\")\n\n return report, self.is_clean_lst\n\n def cluster_activations(self, **kwargs) -> tuple[list[np.ndarray], list[np.ndarray]]:\n \"\"\"\n Clusters activations and returns cluster_by_class and red_activations_by_class, where cluster_by_class[i][j] is\n the cluster to which the j-th data point in the ith class belongs and the correspondent activations reduced by\n class red_activations_by_class[i][j].\n\n :param kwargs: A dictionary of cluster-specific parameters.\n :return: Clusters per class and activations by class.\n \"\"\"\n self.set_params(**kwargs)\n\n if self.generator is not None:\n batch_size = self.generator.batch_size\n num_samples = self.generator.size\n num_classes = self.classifier.nb_classes\n for batch_idx in range(num_samples // batch_size): # type: ignore\n x_batch, y_batch = self.generator.get_batch()\n\n batch_activations = self._get_activations(x_batch)\n activation_dim = batch_activations.shape[-1]\n\n # initialize values list of lists on first run\n if batch_idx == 0:\n self.activations_by_class = [np.empty((0, activation_dim)) for _ in range(num_classes)]\n self.clusters_by_class = [np.empty(0, dtype=int) for _ in range(num_classes)]\n self.red_activations_by_class = [np.empty((0, self.nb_dims)) for _ in range(num_classes)]\n\n activations_by_class = self._segment_by_class(batch_activations, y_batch)\n clusters_by_class, red_activations_by_class = cluster_activations(\n activations_by_class,\n nb_clusters=self.nb_clusters,\n nb_dims=self.nb_dims,\n reduce=self.reduce,\n clustering_method=self.clustering_method,\n generator=self.generator,\n clusterer_new=self.clusterer,\n )\n\n for class_idx in range(num_classes):\n self.activations_by_class[class_idx] = np.vstack(\n [self.activations_by_class[class_idx], activations_by_class[class_idx]]\n )\n self.clusters_by_class[class_idx] = np.append(\n self.clusters_by_class[class_idx], clusters_by_class[class_idx]\n )\n self.red_activations_by_class[class_idx] = np.vstack(\n [self.red_activations_by_class[class_idx], red_activations_by_class[class_idx]]\n )\n return self.clusters_by_class, self.red_activations_by_class\n\n if not self.activations_by_class:\n activations = self._get_activations()\n self.activations_by_class = self._segment_by_class(activations, self.y_train)\n\n [self.clusters_by_class, self.red_activations_by_class] = cluster_activations(\n self.activations_by_class,\n nb_clusters=self.nb_clusters,\n nb_dims=self.nb_dims,\n reduce=self.reduce,\n clustering_method=self.clustering_method,\n )\n\n return self.clusters_by_class, self.red_activations_by_class\n\n def analyze_clusters(self, **kwargs) -> tuple[dict[str, Any], np.ndarray]:\n \"\"\"\n This function analyzes the clusters according to the provided method.\n\n :param kwargs: A dictionary of cluster-analysis-specific parameters.\n :return: (report, assigned_clean_by_class), where the report is a dict object and assigned_clean_by_class\n is a list of arrays that contains what data points where classified as clean.\n \"\"\"\n self.set_params(**kwargs)\n\n if not self.clusters_by_class:\n self.cluster_activations()\n\n analyzer = ClusteringAnalyzer()\n if self.cluster_analysis == \"smaller\":\n (\n self.assigned_clean_by_class,\n self.poisonous_clusters,\n report,\n ) = analyzer.analyze_by_size(self.clusters_by_class)\n elif self.cluster_analysis == \"relative-size\":\n (\n self.assigned_clean_by_class,\n self.poisonous_clusters,\n report,\n ) = analyzer.analyze_by_relative_size(self.clusters_by_class)\n elif self.cluster_analysis == \"distance\":\n (\n self.assigned_clean_by_class,\n self.poisonous_clusters,\n report,\n ) = analyzer.analyze_by_distance(\n self.clusters_by_class,\n separated_activations=self.red_activations_by_class,\n )\n elif self.cluster_analysis == \"silhouette-scores\":\n (\n self.assigned_clean_by_class,\n self.poisonous_clusters,\n report,\n ) = analyzer.analyze_by_silhouette_score(\n self.clusters_by_class,\n reduced_activations_by_class=self.red_activations_by_class,\n )\n else:\n raise ValueError(\"Unsupported cluster analysis technique \" + self.cluster_analysis)\n\n # Add to the report current parameters used to run the defence and the analysis summary\n report = dict(list(report.items()) + list(self.get_params().items()))\n\n return report, self.assigned_clean_by_class\n\n def exclusionary_reclassification(self, report: dict[str, Any]):\n \"\"\"\n This function perform exclusionary reclassification. Based on the ex_re_threshold,\n suspicious clusters will be rechecked. If they remain suspicious, the suspected source\n class will be added to the report and the data will be relabelled. The new labels are stored\n in self.y_train_relabelled\n\n :param report: A dictionary containing defence params as well as the class clusters and their suspiciousness.\n :return: report where the report is a dict object\n \"\"\"\n self.y_train_relabelled = np.copy(self.y_train) # Copy the data to avoid overwriting user objects\n # used for relabeling the data\n is_onehot = False\n if len(np.shape(self.y_train)) == 2:\n is_onehot = True\n\n logger.info(\"Performing Exclusionary Reclassification with a threshold of %s\", self.ex_re_threshold)\n logger.info(\"Data will be relabelled internally. Access the y_train_relabelled attribute to get new labels\")\n # Train a new classifier with the unsuspicious clusters\n cloned_classifier = (\n self.classifier.clone_for_refitting()\n ) # Get a classifier with the same training setup, but new weights\n filtered_x = self.x_train[np.array(self.is_clean_lst) == 1]\n filtered_y = self.y_train[np.array(self.is_clean_lst) == 1]\n\n if len(filtered_x) == 0:\n logger.warning(\"All of the data is marked as suspicious. Unable to perform exclusionary reclassification\")\n return report\n\n cloned_classifier.fit(filtered_x, filtered_y)\n\n # Test on the suspicious clusters\n n_train = len(self.x_train)\n indices_by_class = self._segment_by_class(np.arange(n_train), self.y_train)\n indicies_by_cluster: list[list[list]] = [\n [[] for _ in range(self.nb_clusters)] for _ in range(self.classifier.nb_classes)\n ]\n\n # Get all data in x_train in the right cluster\n for n_class, cluster_assignments in enumerate(self.clusters_by_class):\n for j, assigned_cluster in enumerate(cluster_assignments):\n indicies_by_cluster[n_class][assigned_cluster].append(indices_by_class[n_class][j])\n\n for n_class, _ in enumerate(self.poisonous_clusters):\n suspicious_clusters = np.where(np.array(self.poisonous_clusters[n_class]) == 1)[0]\n for cluster in suspicious_clusters:\n cur_indicies = indicies_by_cluster[n_class][cluster]\n predictions = cloned_classifier.predict(self.x_train[cur_indicies])\n\n predicted_as_class = [\n np.sum(np.argmax(predictions, axis=1) == i) for i in range(self.classifier.nb_classes)\n ]\n n_class_pred_count = predicted_as_class[n_class]\n predicted_as_class[n_class] = -1 * predicted_as_class[n_class] # Just to make the max simple\n other_class = np.argmax(predicted_as_class)\n other_class_pred_count = predicted_as_class[other_class]\n\n # Check if cluster is legit. If so, mark it as such\n if other_class_pred_count == 0 or n_class_pred_count / other_class_pred_count > self.ex_re_threshold:\n self.poisonous_clusters[n_class][cluster] = 0\n report[\"Class_\" + str(n_class)][\"cluster_\" + str(cluster)][\"suspicious_cluster\"] = False\n if \"suspicious_clusters\" in report.keys():\n report[\"suspicious_clusters\"] = report[\"suspicious_clusters\"] - 1\n for ind in cur_indicies:\n self.is_clean_lst[ind] = 1\n # Otherwise, add the exclusionary reclassification info to the report for the suspicious cluster\n else:\n report[\"Class_\" + str(n_class)][\"cluster_\" + str(cluster)][\"ExRe_Score\"] = (\n n_class_pred_count / other_class_pred_count\n )\n report[\"Class_\" + str(n_class)][\"cluster_\" + str(cluster)][\"Suspected_Source_class\"] = other_class\n # Also relabel the data\n if is_onehot:\n self.y_train_relabelled[cur_indicies, n_class] = 0\n self.y_train_relabelled[cur_indicies, other_class] = 1\n else:\n self.y_train_relabelled[cur_indicies] = other_class\n\n return report\n\n @staticmethod\n def relabel_poison_ground_truth(\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n x: np.ndarray,\n y_fix: np.ndarray,\n test_set_split: float = 0.7,\n tolerable_backdoor: float = 0.01,\n max_epochs: int = 50,\n batch_epochs: int = 10,\n ) -> tuple[float, \"CLASSIFIER_NEURALNETWORK_TYPE\"]:\n \"\"\"\n Revert poison attack by continue training the current classifier with `x`, `y_fix`. `test_set_split` determines\n the percentage in x that will be used as training set, while `1-test_set_split` determines how many data points\n to use for test set.\n\n :param classifier: Classifier to be fixed.\n :param x: Samples.\n :param y_fix: True label of `x_poison`.\n :param test_set_split: this parameter determine how much data goes to the training set.\n Here `test_set_split*len(y_fix)` determines the number of data points in `x_train`\n and `(1-test_set_split) * len(y_fix)` the number of data points in `x_test`.\n :param tolerable_backdoor: Threshold that determines what is the maximum tolerable backdoor success rate.\n :param max_epochs: Maximum number of epochs that the model will be trained.\n :param batch_epochs: Number of epochs to be trained before checking current state of model.\n :return: (improve_factor, classifier).\n \"\"\"\n # Split data into testing and training:\n n_train = int(len(x) * test_set_split)\n x_train, x_test = x[:n_train], x[n_train:]\n y_train, y_test = y_fix[:n_train], y_fix[n_train:]\n\n from tensorflow.keras.models import clone_model\n\n model = classifier._model\n forward_pass = classifier._forward_pass # type: ignore\n classifier._model = None\n classifier._forward_pass = None # type: ignore\n\n curr_classifier = copy.deepcopy(classifier)\n curr_model = clone_model(model)\n curr_model.set_weights(model.get_weights())\n curr_classifier._model = curr_model\n curr_classifier._forward_pass = forward_pass # type: ignore\n\n classifier._model = model\n classifier._forward_pass = forward_pass # type: ignore\n\n # Now train using y_fix:\n improve_factor, _ = train_remove_backdoor(\n curr_classifier,\n x_train,\n y_train,\n x_test,\n y_test,\n tolerable_backdoor=tolerable_backdoor,\n max_epochs=max_epochs,\n batch_epochs=batch_epochs,\n )\n\n # Only update classifier if there was an improvement:\n if improve_factor < 0:\n return 0, classifier\n\n return improve_factor, curr_classifier\n\n @staticmethod\n def relabel_poison_cross_validation(\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n x: np.ndarray,\n y_fix: np.ndarray,\n n_splits: int = 10,\n tolerable_backdoor: float = 0.01,\n max_epochs: int = 50,\n batch_epochs: int = 10,\n ) -> tuple[float, \"CLASSIFIER_NEURALNETWORK_TYPE\"]:\n \"\"\"\n Revert poison attack by continue training the current classifier with `x`, `y_fix`. `n_splits` determines the\n number of cross validation splits.\n\n :param classifier: Classifier to be fixed.\n :param x: Samples that were miss-labeled.\n :param y_fix: True label of `x`.\n :param n_splits: Determines how many splits to use in cross validation (only used if `cross_validation=True`).\n :param tolerable_backdoor: Threshold that determines what is the maximum tolerable backdoor success rate.\n :param max_epochs: Maximum number of epochs that the model will be trained.\n :param batch_epochs: Number of epochs to be trained before checking current state of model.\n :return: (improve_factor, classifier)\n \"\"\"\n from sklearn.model_selection import KFold\n\n # Train using cross validation\n k_fold = KFold(n_splits=n_splits)\n KFold(n_splits=n_splits, random_state=None, shuffle=True)\n\n curr_improvement = 0\n\n for train_index, test_index in k_fold.split(x):\n # Obtain partition:\n x_train, x_test = x[train_index], x[test_index]\n y_train, y_test = y_fix[train_index], y_fix[test_index]\n # Copy original model:\n\n from tensorflow.keras.models import clone_model\n\n model = classifier._model\n forward_pass = classifier._forward_pass # type: ignore\n classifier._model = None\n classifier._forward_pass = None # type: ignore\n\n curr_classifier = copy.deepcopy(classifier)\n curr_model = clone_model(model)\n curr_model.set_weights(model.get_weights())\n curr_classifier._model = curr_model\n curr_classifier._forward_pass = forward_pass # type: ignore\n\n classifier._model = model\n classifier._forward_pass = forward_pass # type: ignore\n\n new_improvement, fixed_classifier = train_remove_backdoor(\n curr_classifier,\n x_train,\n y_train,\n x_test,\n y_test,\n tolerable_backdoor=tolerable_backdoor,\n max_epochs=max_epochs,\n batch_epochs=batch_epochs,\n )\n if curr_improvement < new_improvement and new_improvement > 0:\n curr_improvement = new_improvement\n classifier = fixed_classifier\n logger.info(\"Selected as best model so far: %s\", curr_improvement)\n\n return curr_improvement, classifier\n\n def visualize_clusters(\n self, x_raw: np.ndarray, save: bool = True, folder: str = \".\", **kwargs\n ) -> list[list[np.ndarray]]:\n \"\"\"\n This function creates the sprite/mosaic visualization for clusters. When save=True,\n it also stores a sprite (mosaic) per cluster in art.config.ART_DATA_PATH.\n\n :param x_raw: Images used to train the classifier (before pre-processing).\n :param save: Boolean specifying if image should be saved.\n :param folder: Directory where the sprites will be saved inside art.config.ART_DATA_PATH folder.\n :param kwargs: a dictionary of cluster-analysis-specific parameters.\n :return: Array with sprite images sprites_by_class, where sprites_by_class[i][j] contains the\n sprite of class i cluster j.\n \"\"\"\n self.set_params(**kwargs)\n\n if not self.clusters_by_class:\n self.cluster_activations()\n\n x_raw_by_class = self._segment_by_class(x_raw, self.y_train)\n x_raw_by_cluster: list[list[np.ndarray]] = [ # type: ignore\n [[] for _ in range(self.nb_clusters)] for _ in range(self.classifier.nb_classes) # type: ignore\n ]\n\n # Get all data in x_raw in the right cluster\n for n_class, cluster in enumerate(self.clusters_by_class):\n for j, assigned_cluster in enumerate(cluster):\n x_raw_by_cluster[n_class][assigned_cluster].append(x_raw_by_class[n_class][j])\n\n # Now create sprites:\n sprites_by_class: list[list[np.ndarray]] = [ # type: ignore\n [[] for _ in range(self.nb_clusters)] for _ in range(self.classifier.nb_classes) # type: ignore\n ]\n for i, class_i in enumerate(x_raw_by_cluster):\n for j, images_cluster in enumerate(class_i):\n title = \"Class_\" + str(i) + \"_cluster_\" + str(j) + \"_clusterSize_\" + str(len(images_cluster))\n f_name = title + \".png\"\n f_name = os.path.join(folder, f_name)\n sprite = create_sprite(np.array(images_cluster))\n if save:\n save_image(sprite, f_name)\n sprites_by_class[i][j] = sprite\n\n return sprites_by_class\n\n def plot_clusters(self, save: bool = True, folder: str = \".\", **kwargs) -> None:\n \"\"\"\n Creates a 3D-plot to visualize each cluster is assigned a different color in the plot. When\n save=True, it also stores the 3D-plot per cluster in art.config.ART_DATA_PATH.\n\n :param save: Boolean specifying if image should be saved.\n :param folder: Directory where the sprites will be saved inside art.config.ART_DATA_PATH folder.\n :param kwargs: a dictionary of cluster-analysis-specific parameters.\n \"\"\"\n self.set_params(**kwargs)\n\n if not self.clusters_by_class:\n self.cluster_activations()\n\n # Get activations reduced to 3-components:\n separated_reduced_activations = []\n for activation in self.activations_by_class:\n reduced_activations = reduce_dimensionality(activation, nb_dims=3)\n separated_reduced_activations.append(reduced_activations)\n\n # For each class generate a plot:\n for class_id, (labels, coordinates) in enumerate(zip(self.clusters_by_class, separated_reduced_activations)):\n f_name = \"\"\n if save:\n f_name = os.path.join(folder, \"plot_class_\" + str(class_id) + \".png\")\n plot_3d(coordinates, labels, save=save, f_name=f_name)\n\n def _check_params(self):\n if self.nb_clusters <= 1:\n raise ValueError(\n \"Wrong number of clusters, should be greater or equal to 2. Provided: \" + str(self.nb_clusters)\n )\n if self.nb_dims <= 0:\n raise ValueError(\"Wrong number of dimensions.\")\n if self.clustering_method not in self.valid_clustering:\n raise ValueError(\"Unsupported clustering method: \" + self.clustering_method)\n if self.reduce not in self.valid_reduce:\n raise ValueError(\"Unsupported reduction method: \" + self.reduce)\n if self.cluster_analysis not in self.valid_analysis:\n raise ValueError(\"Unsupported method for cluster analysis method: \" + self.cluster_analysis)\n if self.generator and not isinstance(self.generator, DataGenerator):\n raise TypeError(\"Generator must a an instance of DataGenerator\")\n if self.ex_re_threshold is not None and self.ex_re_threshold <= 0:\n raise ValueError(\"Exclusionary reclassification threshold must be positive\")\n\n def _get_activations(self, x_train: np.ndarray | None = None) -> np.ndarray:\n \"\"\"\n Find activations from :class:`.Classifier`.\n \"\"\"\n logger.info(\"Getting activations\")\n\n if self.classifier.layer_names is not None:\n nb_layers = len(self.classifier.layer_names)\n else:\n raise ValueError(\"No layer names identified.\")\n protected_layer = nb_layers - 1\n\n if self.generator is not None and x_train is not None:\n activations = self.classifier.get_activations(\n x_train, layer=protected_layer, batch_size=self.generator.batch_size\n )\n else:\n activations = self.classifier.get_activations(self.x_train, layer=protected_layer, batch_size=128)\n\n # wrong way to get activations activations = self.classifier.predict(self.x_train)\n if isinstance(activations, np.ndarray):\n # flatten activations across batch\n activations = np.reshape(activations, (activations.shape[0], -1))\n nodes_last_layer = activations.shape[1]\n else:\n raise ValueError(\"activations is None or tensor.\")\n\n if nodes_last_layer <= self.TOO_SMALL_ACTIVATIONS:\n logger.warning(\n \"Number of activations in last hidden layer is too small. Method may not work properly. \" \"Size: %s\",\n str(nodes_last_layer),\n )\n return activations\n\n def _segment_by_class(self, data: np.ndarray, features: np.ndarray) -> list[np.ndarray]:\n \"\"\"\n Returns segmented data according to specified features.\n\n :param data: Data to be segmented.\n :param features: Features used to segment data, e.g., segment according to predicted label or to `y_train`.\n :return: Segmented data according to specified features.\n \"\"\"\n n_classes = self.classifier.nb_classes\n return segment_by_class(data, features, n_classes)\n\n\ndef measure_misclassification(\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\", x_test: np.ndarray, y_test: np.ndarray\n) -> float:\n \"\"\"\n Computes 1-accuracy given x_test and y_test\n\n :param classifier: Classifier to be used for predictions.\n :param x_test: Test set.\n :param y_test: Labels for test set.\n :return: 1-accuracy.\n \"\"\"\n predictions = np.argmax(classifier.predict(x_test), axis=1)\n return 1.0 - np.sum(predictions == np.argmax(y_test, axis=1)) / y_test.shape[0]\n\n\ndef train_remove_backdoor(\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_test: np.ndarray,\n y_test: np.ndarray,\n tolerable_backdoor: float,\n max_epochs: int,\n batch_epochs: int,\n) -> tuple:\n \"\"\"\n Trains the provider classifier until the tolerance or number of maximum epochs are reached.\n\n :param classifier: Classifier to be used for predictions.\n :param x_train: Training set.\n :param y_train: Labels used for training.\n :param x_test: Samples in test set.\n :param y_test: Labels in test set.\n :param tolerable_backdoor: Parameter that determines how many misclassifications are acceptable.\n :param max_epochs: maximum number of epochs to be run.\n :param batch_epochs: groups of epochs that will be run together before checking for termination.\n :return: (improve_factor, classifier).\n \"\"\"\n # Measure poison success in current model:\n initial_missed = measure_misclassification(classifier, x_test, y_test)\n\n curr_epochs = 0\n curr_missed = 1.0\n while curr_epochs < max_epochs and curr_missed > tolerable_backdoor:\n classifier.fit(x_train, y_train, nb_epochs=batch_epochs)\n curr_epochs += batch_epochs\n curr_missed = measure_misclassification(classifier, x_test, y_test)\n logger.info(\"Current epoch: %s\", curr_epochs)\n logger.info(\"Misclassifications: %s\", curr_missed)\n\n improve_factor = initial_missed - curr_missed\n return improve_factor, classifier\n\n\ndef cluster_activations(\n separated_activations: list[np.ndarray],\n nb_clusters: int = 2,\n nb_dims: int = 10,\n reduce: str = \"FastICA\",\n clustering_method: str = \"KMeans\",\n generator: DataGenerator | None = None,\n clusterer_new: MiniBatchKMeans | None = None,\n) -> tuple[list[np.ndarray], list[np.ndarray]]:\n \"\"\"\n Clusters activations and returns two arrays.\n 1) separated_clusters: where separated_clusters[i] is a 1D array indicating which cluster each data point\n in the class has been assigned.\n 2) separated_reduced_activations: activations with dimensionality reduced using the specified reduce method.\n\n :param separated_activations: List where separated_activations[i] is a np matrix for the ith class where\n each row corresponds to activations for a given data point.\n :param nb_clusters: number of clusters (defaults to 2 for poison/clean).\n :param nb_dims: number of dimensions to reduce activation to via PCA.\n :param reduce: Method to perform dimensionality reduction, default is FastICA.\n :param clustering_method: Clustering method to use, default is KMeans.\n :param generator: Whether the activations are a batch or full activations\n :return: (separated_clusters, separated_reduced_activations).\n :param clusterer_new: Whether the activations are a batch or full activations\n :return: (separated_clusters, separated_reduced_activations)\n \"\"\"\n separated_clusters = []\n separated_reduced_activations = []\n\n if clustering_method == \"KMeans\":\n clusterer = KMeans(n_clusters=nb_clusters)\n else:\n raise ValueError(f\"{clustering_method} clustering method not supported.\")\n\n for activation in separated_activations:\n # Apply dimensionality reduction\n nb_activations = np.shape(activation)[1]\n if nb_activations > nb_dims:\n # TODO: address issue where if fewer samples than nb_dims this fails\n reduced_activations = reduce_dimensionality(activation, nb_dims=nb_dims, reduce=reduce)\n else:\n logger.info(\n \"Dimensionality of activations = %i less than nb_dims = %i. Not applying dimensionality \" \"reduction.\",\n nb_activations,\n nb_dims,\n )\n reduced_activations = activation\n separated_reduced_activations.append(reduced_activations)\n\n # Get cluster assignments\n if generator is not None and clusterer_new is not None:\n clusterer_new = clusterer_new.partial_fit(reduced_activations)\n # NOTE: this may cause earlier predictions to be less accurate\n clusters = clusterer_new.predict(reduced_activations)\n else:\n clusters = clusterer.fit_predict(reduced_activations)\n separated_clusters.append(clusters)\n\n return separated_clusters, separated_reduced_activations\n\n\ndef reduce_dimensionality(activations: np.ndarray, nb_dims: int = 10, reduce: str = \"FastICA\") -> np.ndarray:\n \"\"\"\n Reduces dimensionality of the activations provided using the specified number of dimensions and reduction technique.\n\n :param activations: Activations to be reduced.\n :param nb_dims: number of dimensions to reduce activation to via PCA.\n :param reduce: Method to perform dimensionality reduction, default is FastICA.\n :return: Array with the reduced activations.\n \"\"\"\n\n from sklearn.decomposition import FastICA, PCA\n\n if reduce == \"FastICA\":\n projector = FastICA(n_components=nb_dims, max_iter=1000, tol=0.005)\n elif reduce == \"PCA\":\n projector = PCA(n_components=nb_dims)\n else:\n raise ValueError(f\"{reduce} dimensionality reduction method not supported.\")\n\n reduced_activations = projector.fit_transform(activations)\n return reduced_activations\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/clustering_analyzer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements methodologies to analyze clusters and determine whether they are poisonous.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\n\nclass ClusteringAnalyzer:\n \"\"\"\n Class for all methodologies implemented to analyze clusters and determine whether they are poisonous.\n \"\"\"\n\n @staticmethod\n def assign_class(clusters: np.ndarray, clean_clusters: np.ndarray, poison_clusters: np.ndarray) -> np.ndarray:\n \"\"\"\n Determines whether each data point in the class is in a clean or poisonous cluster\n\n :param clusters: `clusters[i]` indicates which cluster the i'th data point is in.\n :param clean_clusters: List containing the clusters designated as clean.\n :param poison_clusters: List containing the clusters designated as poisonous.\n :return: assigned_clean: `assigned_clean[i]` is a boolean indicating whether the ith data point is clean.\n \"\"\"\n assigned_clean = np.empty(np.shape(clusters))\n assigned_clean[np.isin(clusters, clean_clusters)] = 1\n assigned_clean[np.isin(clusters, poison_clusters)] = 0\n return assigned_clean\n\n def analyze_by_size(self, separated_clusters: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray, dict[str, int]]:\n \"\"\"\n Designates as poisonous the cluster with fewer items on it.\n\n :param separated_clusters: List where separated_clusters[i] is the cluster assignments for the ith class.\n :return: all_assigned_clean, summary_poison_clusters, report:\n where all_assigned_clean[i] is a 1D boolean array indicating whether\n a given data point was determined to be clean (as opposed to poisonous) and\n summary_poison_clusters: array, where summary_poison_clusters[i][j]=1 if cluster j of class i was\n classified as poison, otherwise 0\n report: Dictionary with summary of the analysis\n \"\"\"\n report: dict[str, Any] = {\n \"cluster_analysis\": \"smaller\",\n \"suspicious_clusters\": 0,\n }\n\n all_assigned_clean = []\n nb_classes = len(separated_clusters)\n nb_clusters = len(np.unique(separated_clusters[0]))\n summary_poison_clusters: np.ndarray = np.zeros((nb_classes, nb_clusters), dtype=object)\n\n for i, clusters in enumerate(separated_clusters):\n # assume that smallest cluster is poisonous and all others are clean\n sizes = np.bincount(clusters)\n total_dp_in_class = np.sum(sizes)\n poison_clusters = np.array([int(np.argmin(sizes))])\n clean_clusters = np.array(list(set(clusters) - set(poison_clusters)))\n\n for p_id in poison_clusters:\n summary_poison_clusters[i][p_id] = 1\n for c_id in clean_clusters:\n summary_poison_clusters[i][c_id] = 0\n\n assigned_clean = self.assign_class(clusters, clean_clusters, poison_clusters)\n all_assigned_clean.append(assigned_clean)\n\n # Generate report for this class:\n report_class = {}\n for cluster_id in range(nb_clusters):\n ptc = sizes[cluster_id] / total_dp_in_class\n susp = cluster_id in poison_clusters\n dict_i = dict(ptc_data_in_cluster=round(ptc, 2), suspicious_cluster=susp)\n\n dict_cluster: dict[str, dict[str, int]] = {\"cluster_\" + str(cluster_id): dict_i}\n report_class.update(dict_cluster)\n\n report[\"Class_\" + str(i)] = report_class\n\n report[\"suspicious_clusters\"] = report[\"suspicious_clusters\"] + np.sum(summary_poison_clusters)\n return np.asarray(all_assigned_clean, dtype=object), summary_poison_clusters, report\n\n def analyze_by_distance(\n self,\n separated_clusters: list[np.ndarray],\n separated_activations: list[np.ndarray],\n ) -> tuple[np.ndarray, np.ndarray, dict[str, int]]:\n \"\"\"\n Assigns a cluster as poisonous if its median activation is closer to the median activation for another class\n than it is to the median activation of its own class. Currently, this function assumes there are only two\n clusters per class.\n\n :param separated_clusters: List where separated_clusters[i] is the cluster assignments for the ith class.\n :param separated_activations: List where separated_activations[i] is a 1D array of [0,1] for [poison,clean].\n :return: all_assigned_clean, summary_poison_clusters, report:\n where all_assigned_clean[i] is a 1D boolean array indicating whether a given data point was determined\n to be clean (as opposed to poisonous) and summary_poison_clusters: array, where\n summary_poison_clusters[i][j]=1 if cluster j of class i was classified as poison, otherwise 0\n report: Dictionary with summary of the analysis.\n \"\"\"\n report: dict[str, Any] = {\"cluster_analysis\": 0.0}\n all_assigned_clean = []\n cluster_centers = []\n\n nb_classes = len(separated_clusters)\n nb_clusters = len(np.unique(separated_clusters[0]))\n summary_poison_clusters = np.zeros((nb_classes, nb_clusters))\n\n # assign centers\n for _, activations in enumerate(separated_activations):\n cluster_centers.append(np.median(activations, axis=0))\n\n for i, (clusters, activation) in enumerate(zip(separated_clusters, separated_activations)):\n clusters = np.array(clusters)\n\n cluster0_center = np.median(activation[np.where(clusters == 0)], axis=0)\n cluster1_center = np.median(activation[np.where(clusters == 1)], axis=0)\n\n cluster0_distance = np.linalg.norm(cluster0_center - cluster_centers[i])\n cluster1_distance = np.linalg.norm(cluster1_center - cluster_centers[i])\n\n cluster0_is_poison = False\n cluster1_is_poison = False\n\n dict_k = {}\n dict_cluster_0 = dict(cluster0_distance_to_its_class=str(cluster0_distance))\n dict_cluster_1 = dict(cluster1_distance_to_its_class=str(cluster1_distance))\n for k, center in enumerate(cluster_centers):\n if k == i:\n pass\n else:\n cluster0_distance_to_k = np.linalg.norm(cluster0_center - center)\n cluster1_distance_to_k = np.linalg.norm(cluster1_center - center)\n\n if cluster0_distance_to_k < cluster0_distance and cluster1_distance_to_k > cluster1_distance:\n cluster0_is_poison = True\n if cluster1_distance_to_k < cluster1_distance and cluster0_distance_to_k > cluster0_distance:\n cluster1_is_poison = True\n\n dict_cluster_0[\"distance_to_class_\" + str(k)] = str(cluster0_distance_to_k)\n dict_cluster_0[\"suspicious\"] = str(cluster0_is_poison)\n\n dict_cluster_1[\"distance_to_class_\" + str(k)] = str(cluster1_distance_to_k)\n dict_cluster_1[\"suspicious\"] = str(cluster1_is_poison)\n\n dict_k.update(dict_cluster_0)\n dict_k.update(dict_cluster_1)\n\n report_class = dict(cluster_0=dict_cluster_0, cluster_1=dict_cluster_1)\n report[\"Class_\" + str(i)] = report_class\n\n poison_clusters = []\n if cluster0_is_poison:\n poison_clusters.append(0)\n summary_poison_clusters[i][0] = 1\n else:\n summary_poison_clusters[i][0] = 0\n\n if cluster1_is_poison:\n poison_clusters.append(1)\n summary_poison_clusters[i][1] = 1\n else:\n summary_poison_clusters[i][1] = 0\n\n clean_clusters = np.array(list(set(clusters) - set(poison_clusters)))\n assigned_clean = self.assign_class(clusters, clean_clusters, np.array(poison_clusters))\n all_assigned_clean.append(assigned_clean)\n\n all_assigned_clean_array = np.asarray(all_assigned_clean, dtype=object)\n return all_assigned_clean_array, summary_poison_clusters, report\n\n def analyze_by_relative_size(\n self,\n separated_clusters: list[np.ndarray],\n size_threshold: float = 0.35,\n r_size: int = 2,\n ) -> tuple[np.ndarray, np.ndarray, dict[str, int]]:\n \"\"\"\n Assigns a cluster as poisonous if the smaller one contains less than threshold of the data.\n This method assumes only 2 clusters\n\n :param separated_clusters: List where `separated_clusters[i]` is the cluster assignments for the ith class.\n :param size_threshold: Threshold used to define when a cluster is substantially smaller.\n :param r_size: Round number used for size rate comparisons.\n :return: all_assigned_clean, summary_poison_clusters, report:\n where all_assigned_clean[i] is a 1D boolean array indicating whether a given data point was determined\n to be clean (as opposed to poisonous) and summary_poison_clusters: array, where\n summary_poison_clusters[i][j]=1 if cluster j of class i was classified as poison, otherwise 0\n report: Dictionary with summary of the analysis.\n \"\"\"\n size_threshold = round(size_threshold, r_size)\n report: dict[str, Any] = {\n \"cluster_analysis\": \"relative_size\",\n \"suspicious_clusters\": 0,\n \"size_threshold\": size_threshold,\n }\n\n all_assigned_clean = []\n nb_classes = len(separated_clusters)\n nb_clusters = len(np.unique(separated_clusters[0]))\n summary_poison_clusters = np.zeros((nb_classes, nb_clusters))\n\n for i, clusters in enumerate(separated_clusters):\n sizes = np.bincount(clusters)\n total_dp_in_class = np.sum(sizes)\n\n if np.size(sizes) > 2:\n raise ValueError(\" RelativeSizeAnalyzer does not support more than two clusters.\")\n percentages = np.round(sizes / float(np.sum(sizes)), r_size)\n poison_clusters = np.where(percentages < size_threshold)\n clean_clusters = np.where(percentages >= size_threshold)\n\n for p_id in poison_clusters[0]:\n summary_poison_clusters[i][p_id] = 1\n for c_id in clean_clusters[0]:\n summary_poison_clusters[i][c_id] = 0\n\n assigned_clean = self.assign_class(clusters, clean_clusters[0], poison_clusters[0])\n all_assigned_clean.append(assigned_clean)\n\n # Generate report for this class:\n report_class = {}\n for cluster_id in range(nb_clusters):\n ptc = sizes[cluster_id] / total_dp_in_class\n susp = cluster_id in poison_clusters\n dict_i = dict(ptc_data_in_cluster=round(ptc, 2), suspicious_cluster=susp)\n\n dict_cluster = {\"cluster_\" + str(cluster_id): dict_i}\n report_class.update(dict_cluster)\n\n report[\"Class_\" + str(i)] = report_class\n\n report[\"suspicious_clusters\"] = report[\"suspicious_clusters\"] + np.sum(summary_poison_clusters).item()\n return np.asarray(all_assigned_clean, dtype=object), summary_poison_clusters, report\n\n def analyze_by_silhouette_score(\n self,\n separated_clusters: list,\n reduced_activations_by_class: list,\n size_threshold: float = 0.35,\n silhouette_threshold: float = 0.1,\n r_size: int = 2,\n r_silhouette: int = 4,\n ) -> tuple[np.ndarray, np.ndarray, dict[str, int]]:\n \"\"\"\n Analyzes clusters to determine level of suspiciousness of poison based on the cluster's relative size\n and silhouette score.\n Computes a silhouette score for each class to determine how cohesive resulting clusters are.\n A low silhouette score indicates that the clustering does not fit the data well, and the class can be considered\n to be un-poisoned. Conversely, a high silhouette score indicates that the clusters reflect true splits in the\n data.\n The method concludes that a cluster is poison based on the silhouette score and the cluster relative size.\n If the relative size is too small, below a size_threshold and at the same time\n the silhouette score is higher than silhouette_threshold, the cluster is classified as poisonous.\n If the above thresholds are not provided, the default ones will be used.\n\n :param separated_clusters: List where `separated_clusters[i]` is the cluster assignments for the ith class.\n :param reduced_activations_by_class: List where separated_activations[i] is a 1D array of [0,1] for\n [poison,clean].\n :param size_threshold: (optional) threshold used to define when a cluster is substantially smaller. A default\n value is used if the parameter is not provided.\n :param silhouette_threshold: (optional) threshold used to define when a cluster is cohesive. Default\n value is used if the parameter is not provided.\n :param r_size: Round number used for size rate comparisons.\n :param r_silhouette: Round number used for silhouette rate comparisons.\n :return: all_assigned_clean, summary_poison_clusters, report:\n where all_assigned_clean[i] is a 1D boolean array indicating whether a given data point was determined\n to be clean (as opposed to poisonous) summary_poison_clusters: array, where\n summary_poison_clusters[i][j]=1 if cluster j of class j was classified as poison\n report: Dictionary with summary of the analysis.\n \"\"\"\n\n from sklearn.metrics import silhouette_score\n\n size_threshold = round(size_threshold, r_size)\n silhouette_threshold = round(silhouette_threshold, r_silhouette)\n report: dict[str, Any] = {\n \"cluster_analysis\": \"silhouette_score\",\n \"size_threshold\": str(size_threshold),\n \"silhouette_threshold\": str(silhouette_threshold),\n }\n all_assigned_clean = []\n nb_classes = len(separated_clusters)\n nb_clusters = len(np.unique(separated_clusters[0]))\n summary_poison_clusters = np.zeros((nb_classes, nb_clusters))\n\n for i, (clusters, activations) in enumerate(zip(separated_clusters, reduced_activations_by_class)):\n bins = np.bincount(clusters)\n if np.size(bins) > 2:\n raise ValueError(\"Analyzer does not support more than two clusters.\")\n percentages = np.round(bins / float(np.sum(bins)), r_size)\n poison_clusters = np.where(percentages < size_threshold)\n clean_clusters = np.where(percentages >= size_threshold)\n\n # Generate report for class\n silhouette_avg = round(silhouette_score(activations, clusters), r_silhouette)\n dict_i: dict[str, Any] = dict(\n sizes_clusters=str(bins),\n ptc_cluster=str(percentages),\n avg_silhouette_score=str(silhouette_avg),\n )\n\n if np.shape(poison_clusters)[1] != 0:\n # Relative size of the clusters is suspicious\n if silhouette_avg > silhouette_threshold:\n # In this case the cluster is considered poisonous\n clean_clusters = np.where(percentages < size_threshold)\n logger.info(\"computed silhouette score: %s\", silhouette_avg)\n dict_i.update(suspicious=True)\n else:\n poison_clusters = (np.array([[]]),)\n clean_clusters = np.where(percentages >= 0)\n dict_i.update(suspicious=False)\n else:\n # If relative size of the clusters is Not suspicious, we conclude it's not suspicious.\n dict_i.update(suspicious=False)\n\n report_class: dict[str, dict[str, bool]] = {\"class_\" + str(i): dict_i}\n\n for p_id in poison_clusters[0]:\n summary_poison_clusters[i][p_id] = 1\n for c_id in clean_clusters[0]:\n summary_poison_clusters[i][c_id] = 0\n\n assigned_clean = self.assign_class(clusters, clean_clusters[0], poison_clusters[0])\n all_assigned_clean.append(assigned_clean)\n report.update(report_class)\n\n return np.asarray(all_assigned_clean, dtype=object), summary_poison_clusters, report\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/ground_truth_evaluator.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements classes to evaluate the performance of poison detection methods.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport json\nimport logging\n\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\n\nclass GroundTruthEvaluator:\n \"\"\"\n Class to evaluate the performance of the poison detection method.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Evaluates ground truth constructor\n \"\"\"\n\n def analyze_correctness(\n self, assigned_clean_by_class: np.ndarray | list[int] | list[np.ndarray], is_clean_by_class: list\n ) -> tuple[np.ndarray, str]:\n \"\"\"\n For each training sample, determine whether the activation clustering method was correct.\n\n :param assigned_clean_by_class: Result of clustering.\n :param is_clean_by_class: is clean separated by class.\n :return: Two variables are returned:\n 1) all_errors_by_class[i]: an array indicating the correctness of each assignment\n in the ith class. Such that:\n all_errors_by_class[i] = 0 if marked poison, is poison\n all_errors_by_class[i] = 1 if marked clean, is clean\n all_errors_by_class[i] = 2 if marked poison, is clean\n all_errors_by_class[i] = 3 marked clean, is poison\n 2) Json object with confusion matrix per-class.\n \"\"\"\n all_errors_by_class = []\n poison = 0\n clean = 1\n dic_json = {}\n\n logger.debug(\"Error rates per class:\")\n for class_i, (assigned_clean, is_clean) in enumerate(zip(assigned_clean_by_class, is_clean_by_class)):\n errors = []\n for assignment, bl_var in zip(assigned_clean, is_clean):\n bl_var = int(bl_var)\n # marked poison, is poison = 0\n # true positive\n if assignment == poison and bl_var == poison:\n errors.append(0)\n\n # marked clean, is clean = 1\n # true negative\n elif assignment == clean and bl_var == clean:\n errors.append(1)\n\n # marked poison, is clean = 2\n # false positive\n elif assignment == poison and bl_var == clean:\n errors.append(2)\n\n # marked clean, is poison = 3\n # false negative\n elif assignment == clean and bl_var == poison:\n errors.append(3)\n else:\n raise Exception(\"Analyze_correctness entered wrong class\")\n\n errors_array = np.asarray(errors)\n logger.debug(\"-------------------%d---------------\", class_i)\n key_i = \"class_\" + str(class_i)\n matrix_i = self.get_confusion_matrix(errors_array)\n dic_json.update({key_i: matrix_i})\n all_errors_by_class.append(errors_array)\n\n all_errors_by_class_array = np.asarray(all_errors_by_class, dtype=object)\n conf_matrix_json = json.dumps(dic_json)\n\n return all_errors_by_class_array, conf_matrix_json\n\n def get_confusion_matrix(self, values: np.ndarray) -> dict:\n \"\"\"\n Computes and returns a json object that contains the confusion matrix for each class.\n\n :param values: Array indicating the correctness of each assignment in the ith class.\n :return: Json object with confusion matrix per-class.\n \"\"\"\n dic_class = {}\n true_positive = np.where(values == 0)[0].shape[0]\n true_negative = np.where(values == 1)[0].shape[0]\n false_positive = np.where(values == 2)[0].shape[0]\n false_negative = np.where(values == 3)[0].shape[0]\n\n tp_rate = self.calculate_and_print(true_positive, true_positive + false_negative, \"true-positive rate\")\n tn_rate = self.calculate_and_print(true_negative, false_positive + true_negative, \"true-negative rate\")\n fp_rate = self.calculate_and_print(false_positive, false_positive + true_negative, \"false-positive rate\")\n fn_rate = self.calculate_and_print(false_negative, true_positive + false_negative, \"false-negative rate\")\n\n dic_tp = dict(\n rate=round(tp_rate, 2),\n numerator=true_positive,\n denominator=(true_positive + false_negative),\n )\n if (true_positive + false_negative) == 0:\n dic_tp = dict(\n rate=-1,\n numerator=true_positive,\n denominator=(true_positive + false_negative),\n )\n\n dic_tn = dict(\n rate=round(tn_rate, 2),\n numerator=true_negative,\n denominator=(false_positive + true_negative),\n )\n if (false_positive + true_negative) == 0:\n dic_tn = dict(\n rate=-1,\n numerator=true_negative,\n denominator=(false_positive + true_negative),\n )\n\n dic_fp = dict(\n rate=round(fp_rate, 2),\n numerator=false_positive,\n denominator=(false_positive + true_negative),\n )\n if (false_positive + true_negative) == 0:\n dic_fp = dict(\n rate=-1,\n numerator=false_positive,\n denominator=(false_positive + true_negative),\n )\n\n dic_fn = dict(\n rate=round(fn_rate, 2),\n numerator=false_negative,\n denominator=(true_positive + false_negative),\n )\n if (true_positive + false_negative) == 0:\n dic_fn = dict(\n rate=-1,\n numerator=false_negative,\n denominator=(true_positive + false_negative),\n )\n\n dic_class.update(dict(TruePositive=dic_tp))\n dic_class.update(dict(TrueNegative=dic_tn))\n dic_class.update(dict(FalsePositive=dic_fp))\n dic_class.update(dict(FalseNegative=dic_fn))\n\n return dic_class\n\n @staticmethod\n def calculate_and_print(numerator: int, denominator: int, name: str) -> float:\n \"\"\"\n Computes and prints the rates based on the denominator provided.\n\n :param numerator: number used to compute the rate.\n :param denominator: number used to compute the rate.\n :param name: Rate name being computed e.g., false-positive rate.\n :return: Computed rate\n \"\"\"\n try:\n res = 100 * (numerator / float(denominator))\n logger.debug(\"%s: %d/%d=%.3g\", name, numerator, denominator, res)\n return res\n except ZeroDivisionError:\n logger.debug(\"%s: couldn't calculate %d/%d\", name, numerator, denominator)\n return 0.0\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/poison_filtering_defence.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for all poison filtering defences.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nimport sys\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\n# Ensure compatibility with Python 2 and 3 when using ABCMeta\nif sys.version_info >= (3, 4):\n ABC = abc.ABC\nelse:\n ABC = abc.ABCMeta(str(\"ABC\"), (), {})\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\n\nclass PoisonFilteringDefence(ABC):\n \"\"\"\n Base class for all poison filtering defences.\n \"\"\"\n\n defence_params = [\"classifier\"]\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\", x_train: np.ndarray, y_train: np.ndarray) -> None:\n \"\"\"\n Create an :class:`.ActivationDefence` object with the provided classifier.\n\n :param classifier: Model evaluated for poison.\n :param x_train: dataset used to train the classifier.\n :param y_train: labels used to train the classifier.\n \"\"\"\n self.classifier = classifier\n self.x_train = x_train\n self.y_train = y_train\n\n @abc.abstractmethod\n def detect_poison(self, **kwargs) -> tuple[dict, list[int]]:\n \"\"\"\n Detect poison.\n\n :param kwargs: Defence-specific parameters used by child classes.\n :return: Dictionary with report and list with items identified as poison.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def evaluate_defence(self, is_clean: np.ndarray, **kwargs) -> str:\n \"\"\"\n Evaluate the defence given the labels specifying if the data is poisoned or not.\n\n :param is_clean: 1-D array where is_clean[i]=1 means x_train[i] is clean and is_clean[i]=0 that it's poison.\n :param kwargs: Defence-specific parameters used by child classes.\n :return: JSON object with confusion matrix.\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and apply attack-specific checks before saving them as attributes.\n\n :param kwargs: A dictionary of defence-specific parameters.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.defence_params:\n setattr(self, key, value)\n self._check_params()\n\n def get_params(self) -> dict[str, Any]:\n \"\"\"\n Returns dictionary of parameters used to run defence.\n\n :return: Dictionary of parameters of the method.\n \"\"\"\n dictionary = {param: getattr(self, param) for param in self.defence_params}\n return dictionary\n\n def _check_params(self) -> None:\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/provenance_defense.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements methods performing poisoning detection based on data provenance.\n\n| Paper link: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8473440\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nfrom art.defences.detector.poison.ground_truth_evaluator import GroundTruthEvaluator\nfrom art.defences.detector.poison.poison_filtering_defence import PoisonFilteringDefence\nfrom art.utils import segment_by_class, performance_diff\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProvenanceDefense(PoisonFilteringDefence):\n \"\"\"\n Implements methods performing poisoning detection based on data provenance.\n\n | Paper link: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8473440\n \"\"\"\n\n defence_params = [\n \"classifier\",\n \"x_train\",\n \"y_train\",\n \"p_train\",\n \"x_val\",\n \"y_val\",\n \"eps\",\n \"perf_func\",\n \"pp_valid\",\n ]\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n x_train: np.ndarray,\n y_train: np.ndarray,\n p_train: np.ndarray,\n x_val: np.ndarray | None = None,\n y_val: np.ndarray | None = None,\n eps: float = 0.2,\n perf_func: str = \"accuracy\",\n pp_valid: float = 0.2,\n ) -> None:\n \"\"\"\n Create an :class:`.ProvenanceDefense` object with the provided classifier.\n\n :param classifier: Model evaluated for poison.\n :param x_train: dataset used to train the classifier.\n :param y_train: labels used to train the classifier.\n :param p_train: provenance features for each training data point as one hot vectors.\n :param x_val: Validation data for defense.\n :param y_val: Validation labels for defense.\n :param eps: Threshold for performance shift in suspicious data.\n :param perf_func: performance function used to evaluate effectiveness of defense.\n :param pp_valid: The percent of training data to use as validation data (for defense without validation data).\n \"\"\"\n super().__init__(classifier, x_train, y_train)\n self.p_train = p_train\n self.num_devices = self.p_train.shape[1]\n self.x_val = x_val\n self.y_val = y_val\n self.eps = eps\n self.perf_func = perf_func\n self.pp_valid = pp_valid\n self.assigned_clean_by_device: list[np.ndarray] = []\n self.is_clean_by_device: list[np.ndarray] = []\n self.errors_by_device: np.ndarray | None = None\n self.evaluator = GroundTruthEvaluator()\n self.is_clean_lst: np.ndarray | None = None\n self._check_params()\n\n def evaluate_defence(self, is_clean: np.ndarray, **kwargs) -> str:\n \"\"\"\n Returns confusion matrix.\n\n :param is_clean: Ground truth, where is_clean[i]=1 means that x_train[i] is clean and is_clean[i]=0 means\n x_train[i] is poisonous.\n :param kwargs: A dictionary of defence-specific parameters.\n :return: JSON object with confusion matrix.\n \"\"\"\n if is_clean is None or is_clean.size == 0:\n raise ValueError(\"is_clean was not provided while invoking evaluate_defence.\")\n self.set_params(**kwargs)\n\n if not self.assigned_clean_by_device:\n self.detect_poison()\n\n self.is_clean_by_device = segment_by_class(is_clean, self.p_train, self.num_devices)\n self.errors_by_device, conf_matrix_json = self.evaluator.analyze_correctness(\n self.assigned_clean_by_device, self.is_clean_by_device\n )\n return conf_matrix_json\n\n def detect_poison(self, **kwargs) -> tuple[dict[int, float], list[int]]:\n \"\"\"\n Returns poison detected and a report.\n\n :param kwargs: A dictionary of detection-specific parameters.\n :return: (report, is_clean_lst):\n where a report is a dict object that contains information specified by the provenance detection method\n where is_clean is a list, where is_clean_lst[i]=1 means that x_train[i]\n there is clean and is_clean_lst[i]=0, means that x_train[i] was classified as poison.\n :rtype: `tuple`\n \"\"\"\n self.set_params(**kwargs)\n\n if self.x_val is None:\n report = self.detect_poison_untrusted()\n else:\n report = self.detect_poison_partially_trusted()\n\n n_train = len(self.x_train)\n indices_by_provenance = segment_by_class(np.arange(n_train), self.p_train, self.num_devices)\n self.is_clean_lst = np.array([1] * n_train)\n\n for device in report:\n self.is_clean_lst[indices_by_provenance[device]] = 0 # type: ignore\n self.assigned_clean_by_device = segment_by_class(np.array(self.is_clean_lst), self.p_train, self.num_devices)\n\n return report, self.is_clean_lst # type: ignore\n\n def detect_poison_partially_trusted(self, **kwargs) -> dict[int, float]:\n \"\"\"\n Detect poison given trusted validation data\n\n :return: dictionary where keys are suspected poisonous device indices and values are performance differences\n \"\"\"\n self.set_params(**kwargs)\n\n if self.x_val is None or self.y_val is None:\n raise ValueError(\"Trusted data unavailable.\")\n\n suspected = {}\n unfiltered_data = np.copy(self.x_train)\n unfiltered_labels = np.copy(self.y_train)\n\n segments = segment_by_class(self.x_train, self.p_train, self.num_devices)\n for device_idx, segment in enumerate(segments):\n filtered_data, filtered_labels = self.filter_input(unfiltered_data, unfiltered_labels, segment)\n\n unfiltered_model = deepcopy(self.classifier)\n filtered_model = deepcopy(self.classifier)\n\n unfiltered_model.fit(unfiltered_data, unfiltered_labels)\n filtered_model.fit(filtered_data, filtered_labels)\n\n var_w = performance_diff(\n filtered_model,\n unfiltered_model,\n self.x_val,\n self.y_val,\n perf_function=self.perf_func,\n )\n if self.eps < var_w:\n suspected[device_idx] = var_w\n unfiltered_data = filtered_data\n unfiltered_labels = filtered_labels\n\n return suspected\n\n def detect_poison_untrusted(self, **kwargs) -> dict[int, float]:\n \"\"\"\n Detect poison given no trusted validation data\n\n :return: dictionary where keys are suspected poisonous device indices and values are performance differences\n \"\"\"\n self.set_params(**kwargs)\n\n suspected = {}\n (\n train_data,\n valid_data,\n train_labels,\n valid_labels,\n train_prov,\n valid_prov,\n ) = train_test_split(self.x_train, self.y_train, self.p_train, test_size=self.pp_valid)\n\n train_segments = segment_by_class(train_data, train_prov, self.num_devices)\n valid_segments = segment_by_class(valid_data, valid_prov, self.num_devices)\n\n for device_idx, (train_segment, valid_segment) in enumerate(zip(train_segments, valid_segments)):\n filtered_data, filtered_labels = self.filter_input(train_data, train_labels, train_segment)\n\n unfiltered_model = deepcopy(self.classifier)\n filtered_model = deepcopy(self.classifier)\n\n unfiltered_model.fit(train_data, train_labels)\n filtered_model.fit(filtered_data, filtered_labels)\n\n valid_non_device_data, valid_non_device_labels = self.filter_input(valid_data, valid_labels, valid_segment)\n var_w = performance_diff(\n filtered_model,\n unfiltered_model,\n valid_non_device_data,\n valid_non_device_labels,\n perf_function=self.perf_func,\n )\n\n if self.eps < var_w:\n suspected[device_idx] = var_w\n train_data = filtered_data\n train_labels = filtered_labels\n valid_data = valid_non_device_data\n valid_labels = valid_non_device_labels\n\n return suspected\n\n @staticmethod\n def filter_input(data: np.ndarray, labels: np.ndarray, segment: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Return the data and labels that are not part of a specified segment\n\n :param data: The data to segment.\n :param labels: The corresponding labels to segment\n :param segment:\n :return: Tuple of (filtered_data, filtered_labels).\n \"\"\"\n filter_mask = np.array([np.isin(data[i, :], segment, invert=True).any() for i in range(data.shape[0])])\n filtered_data = data[filter_mask]\n filtered_labels = labels[filter_mask]\n\n return filtered_data, filtered_labels\n\n def _check_params(self) -> None:\n if self.eps < 0:\n raise ValueError(\"Value of epsilon must be at least 0.\")\n\n if self.pp_valid < 0:\n raise ValueError(\"Value of pp_valid must be at least 0.\")\n\n if len(self.x_train) != len(self.y_train):\n raise ValueError(\"x_train and y_train do not match in shape.\")\n\n if len(self.x_train) != len(self.p_train):\n raise ValueError(\"Provenance features do not match data.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/roni.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Reject on Negative Impact (RONI) defense by Nelson et al. (2019)\n\n| Paper link: https://people.eecs.berkeley.edu/~tygar/papers/SML/misleading.learners.pdf\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nfrom art.defences.detector.poison.ground_truth_evaluator import GroundTruthEvaluator\nfrom art.defences.detector.poison.poison_filtering_defence import PoisonFilteringDefence\nfrom art.utils import performance_diff\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass RONIDefense(PoisonFilteringDefence):\n \"\"\"\n Close implementation based on description in Nelson\n 'Behavior of Machine Learning Algorithms in Adversarial Environments' Ch. 4.4\n\n | Textbook link: https://people.eecs.berkeley.edu/~adj/publications/paper-files/EECS-2010-140.pdf\n \"\"\"\n\n defence_params = [\n \"classifier\",\n \"x_train\",\n \"y_train\",\n \"x_val\",\n \"y_val\",\n \"perf_func\",\n \"calibrated\",\n \"eps\",\n ]\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_TYPE\",\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_val: np.ndarray,\n y_val: np.ndarray,\n perf_func: str | Callable = \"accuracy\",\n pp_cal: float = 0.2,\n pp_quiz: float = 0.2,\n calibrated: bool = True,\n eps: float = 0.1,\n ):\n \"\"\"\n Create an :class:`.RONIDefense` object with the provided classifier.\n\n :param classifier: Model evaluated for poison.\n :param x_train: Dataset used to train the classifier.\n :param y_train: Labels used to train the classifier.\n :param x_val: Trusted data points.\n :param y_train: Trusted data labels.\n :param perf_func: Performance function to use.\n :param pp_cal: Percent of training data used for calibration.\n :param pp_quiz: Percent of training data used for quiz set.\n :param calibrated: True if using the calibrated form of RONI.\n :param eps: performance threshold if using uncalibrated RONI.\n \"\"\"\n super().__init__(classifier, x_train, y_train)\n n_points = len(x_train)\n quiz_idx = np.random.randint(n_points, size=int(pp_quiz * n_points))\n self.calibrated = calibrated\n self.x_quiz = np.copy(self.x_train[quiz_idx])\n self.y_quiz = np.copy(self.y_train[quiz_idx])\n if self.calibrated:\n _, self.x_cal, _, self.y_cal = train_test_split(self.x_train, self.y_train, test_size=pp_cal, shuffle=True)\n self.eps = eps\n self.evaluator = GroundTruthEvaluator()\n self.x_val = x_val\n self.y_val = y_val\n self.perf_func = perf_func\n self.is_clean_lst: list[int] = []\n self._check_params()\n\n def evaluate_defence(self, is_clean: np.ndarray, **kwargs) -> str:\n \"\"\"\n Returns confusion matrix.\n\n :param is_clean: Ground truth, where is_clean[i]=1 means that x_train[i] is clean and is_clean[i]=0 means\n x_train[i] is poisonous.\n :param kwargs: A dictionary of defence-specific parameters.\n :return: JSON object with confusion matrix.\n \"\"\"\n self.set_params(**kwargs)\n if len(self.is_clean_lst) == 0:\n self.detect_poison()\n\n if is_clean is None or len(is_clean) != len(self.is_clean_lst):\n raise ValueError(\"Invalid value for is_clean.\")\n\n _, conf_matrix = self.evaluator.analyze_correctness([self.is_clean_lst], [is_clean]) # type: ignore\n return conf_matrix\n\n def detect_poison(self, **kwargs) -> tuple[dict, list[int]]:\n \"\"\"\n Returns poison detected and a report.\n\n :param kwargs: A dictionary of detection-specific parameters.\n :return: (report, is_clean_lst):\n where a report is a dict object that contains information specified by the provenance detection method\n where is_clean is a list, where is_clean_lst[i]=1 means that x_train[i]\n there is clean and is_clean_lst[i]=0, means that x_train[i] was classified as poison.\n \"\"\"\n self.set_params(**kwargs)\n\n x_suspect = self.x_train\n y_suspect = self.y_train\n x_trusted = self.x_val\n y_trusted = self.y_val\n\n self.is_clean_lst = [1 for _ in range(len(x_suspect))]\n report = {}\n\n before_classifier = deepcopy(self.classifier)\n before_classifier.fit(x_suspect, y_suspect)\n\n for idx in np.random.permutation(len(x_suspect)):\n x_i = x_suspect[idx]\n y_i = y_suspect[idx]\n\n after_classifier = deepcopy(before_classifier)\n after_classifier.fit(x=np.vstack([x_trusted, x_i]), y=np.vstack([y_trusted, y_i]))\n acc_shift = performance_diff(\n before_classifier,\n after_classifier,\n self.x_quiz,\n self.y_quiz,\n perf_function=self.perf_func,\n )\n # print(acc_shift, median, std_dev)\n if self.is_suspicious(before_classifier, acc_shift):\n self.is_clean_lst[idx] = 0\n report[idx] = acc_shift\n else:\n before_classifier = after_classifier\n x_trusted = np.vstack([x_trusted, x_i])\n y_trusted = np.vstack([y_trusted, y_i])\n\n return report, self.is_clean_lst\n\n def is_suspicious(self, before_classifier: \"CLASSIFIER_TYPE\", perf_shift: float) -> bool:\n \"\"\"\n Returns True if a given performance shift is suspicious\n\n :param before_classifier: The classifier without untrusted data.\n :param perf_shift: A shift in performance.\n :return: True if a given performance shift is suspicious, false otherwise.\n \"\"\"\n if self.calibrated:\n median, std_dev = self.get_calibration_info(before_classifier)\n return bool(perf_shift < median - 3 * std_dev)\n\n return bool(perf_shift < -self.eps)\n\n def get_calibration_info(self, before_classifier: \"CLASSIFIER_TYPE\") -> tuple[float, float]:\n \"\"\"\n Calculate the median and standard deviation of the accuracy shifts caused\n by the calibration set.\n\n :param before_classifier: The classifier trained without suspicious point.\n :return: A tuple consisting of `(median, std_dev)`.\n \"\"\"\n accs = []\n\n for x_c, y_c in zip(self.x_cal, self.y_cal):\n after_classifier = deepcopy(before_classifier)\n after_classifier.fit(x=np.vstack([self.x_val, x_c]), y=np.vstack([self.y_val, y_c]))\n accs.append(\n performance_diff(\n before_classifier,\n after_classifier,\n self.x_quiz,\n self.y_quiz,\n perf_function=self.perf_func,\n )\n )\n\n return float(np.median(accs)), float(np.std(accs))\n\n def _check_params(self) -> None:\n if len(self.x_train) != len(self.y_train):\n raise ValueError(\"`x_train` and `y_train` do not match shape.\")\n\n if self.eps < 0:\n raise ValueError(\"Value of `eps` must be at least 0.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/detector/poison/spectral_signature_defense.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements methods performing backdoor poisoning detection based on spectral signatures.\n\n| Paper link: https://papers.nips.cc/paper/8024-spectral-signatures-in-backdoor-attacks.pdf\n\n| Please keep in mind the limitations of defenses. For more information on the limitations of this\n specific defense, see https://arxiv.org/abs/1905.13409 .\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.detector.poison.ground_truth_evaluator import GroundTruthEvaluator\nfrom art.defences.detector.poison.poison_filtering_defence import PoisonFilteringDefence\n\nfrom art.utils import segment_by_class\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\n\nclass SpectralSignatureDefense(PoisonFilteringDefence):\n \"\"\"\n Method from Tran et al., 2018 performing poisoning detection based on Spectral Signatures\n \"\"\"\n\n defence_params = PoisonFilteringDefence.defence_params + [\n \"x_train\",\n \"y_train\",\n \"batch_size\",\n \"eps_multiplier\",\n \"expected_pp_poison\",\n ]\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\",\n x_train: np.ndarray,\n y_train: np.ndarray,\n expected_pp_poison: float = 0.33,\n batch_size: int = 128,\n eps_multiplier: float = 1.5,\n ) -> None:\n \"\"\"\n Create an :class:`.SpectralSignatureDefense` object with the provided classifier.\n\n :param classifier: Model evaluated for poison.\n :param x_train: Dataset used to train the classifier.\n :param y_train: Labels used to train the classifier.\n :param expected_pp_poison: The expected percentage of poison in the dataset\n :param batch_size: The batch size for predictions\n :param eps_multiplier: The multiplier to add to the previous expectation. Numbers higher than one represent\n a potentially higher false positive rate, but may detect more poison samples\n \"\"\"\n super().__init__(classifier, x_train, y_train)\n self.classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\" = classifier\n self.batch_size = batch_size\n self.eps_multiplier = eps_multiplier\n self.expected_pp_poison = expected_pp_poison\n self.y_train = y_train\n self.evaluator = GroundTruthEvaluator()\n self._check_params()\n\n def evaluate_defence(self, is_clean: np.ndarray, **kwargs) -> str:\n \"\"\"\n If ground truth is known, this function returns a confusion matrix in the form of a JSON object.\n\n :param is_clean: Ground truth, where is_clean[i]=1 means that x_train[i] is clean and is_clean[i]=0 means\n x_train[i] is poisonous.\n :param kwargs: A dictionary of defence-specific parameters.\n :return: JSON object with confusion matrix.\n \"\"\"\n if is_clean is None or is_clean.size == 0:\n raise ValueError(\"is_clean was not provided while invoking evaluate_defence.\")\n is_clean_by_class = segment_by_class(is_clean, self.y_train, self.classifier.nb_classes)\n _, predicted_clean = self.detect_poison()\n predicted_clean_by_class = segment_by_class(predicted_clean, self.y_train, self.classifier.nb_classes)\n\n _, conf_matrix_json = self.evaluator.analyze_correctness(predicted_clean_by_class, is_clean_by_class)\n\n return conf_matrix_json\n\n def detect_poison(self, **kwargs) -> tuple[dict, list[int]]:\n \"\"\"\n Returns poison detected and a report.\n\n :return: (report, is_clean_lst):\n where a report is a dictionary containing the index as keys the outlier score of suspected poisons as\n values where is_clean is a list, where is_clean_lst[i]=1 means that x_train[i] there is clean and\n is_clean_lst[i]=0, means that x_train[i] was classified as poison.\n \"\"\"\n self.set_params(**kwargs)\n\n if self.classifier.layer_names is not None:\n nb_layers = len(self.classifier.layer_names)\n else:\n raise ValueError(\"No layer names identified.\")\n features_x_poisoned = self.classifier.get_activations(\n self.x_train, layer=nb_layers - 1, batch_size=self.batch_size\n )\n if not isinstance(features_x_poisoned, np.ndarray):\n raise ValueError(\"Wrong type detected.\")\n\n if features_x_poisoned is not None:\n # flatten activations across batch\n features_x_poisoned = np.reshape(features_x_poisoned, (features_x_poisoned.shape[0], -1))\n features_split = segment_by_class(features_x_poisoned, self.y_train, self.classifier.nb_classes)\n else:\n raise ValueError(\"Activation are `None`.\")\n score_by_class = []\n keep_by_class = []\n\n for idx, feature in enumerate(features_split):\n # Check for empty list\n if len(feature):\n score = SpectralSignatureDefense.spectral_signature_scores(np.vstack(feature)) # type: ignore\n score_cutoff = np.quantile(score, max(1 - self.eps_multiplier * self.expected_pp_poison, 0.0))\n score_by_class.append(score)\n keep_by_class.append(score < score_cutoff)\n else:\n score_by_class.append([0]) # type: ignore\n keep_by_class.append([True])\n\n base_indices_by_class = segment_by_class(\n np.arange(self.y_train.shape[0]),\n self.y_train,\n self.classifier.nb_classes,\n )\n is_clean_lst = [0] * self.y_train.shape[0]\n report = {}\n\n for keep_booleans, all_scores, indices in zip(keep_by_class, score_by_class, base_indices_by_class):\n for keep_boolean, all_score, idx in zip(keep_booleans, all_scores, indices):\n if keep_boolean:\n is_clean_lst[idx] = 1\n else:\n report[idx] = all_score[0]\n\n return report, is_clean_lst\n\n def _check_params(self) -> None:\n if self.batch_size < 0:\n raise ValueError(\"Batch size must be positive integer. Unsupported batch size: \" + str(self.batch_size))\n if self.eps_multiplier < 0:\n raise ValueError(\"eps_multiplier must be positive. Unsupported value: \" + str(self.eps_multiplier))\n if self.expected_pp_poison < 0 or self.expected_pp_poison > 1:\n raise ValueError(\n \"expected_pp_poison must be between 0 and 1. Unsupported value: \" + str(self.expected_pp_poison)\n )\n\n @staticmethod\n def spectral_signature_scores(matrix_r: np.ndarray) -> np.ndarray:\n \"\"\"\n :param matrix_r: Matrix of feature representations.\n :return: Outlier scores for each observation based on spectral signature.\n \"\"\"\n matrix_m = matrix_r - np.mean(matrix_r, axis=0)\n # Following Algorithm #1 in paper, use SVD of centered features, not of covariance\n _, _, matrix_v = np.linalg.svd(matrix_m, full_matrices=False)\n eigs = matrix_v[:1]\n corrs = np.matmul(eigs, np.transpose(matrix_r))\n score = np.expand_dims(np.linalg.norm(corrs, axis=0), axis=1)\n return score\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing postprocessing defences against adversarial attacks.\n\"\"\"\n\nfrom art.defences.postprocessor.class_labels import ClassLabels\nfrom art.defences.postprocessor.gaussian_noise import GaussianNoise\nfrom art.defences.postprocessor.high_confidence import HighConfidence\nfrom art.defences.postprocessor.postprocessor import Postprocessor\nfrom art.defences.postprocessor.reverse_sigmoid import ReverseSigmoid\nfrom art.defences.postprocessor.rounded import Rounded\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/class_labels.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements class labels added to the classifier output.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass ClassLabels(Postprocessor):\n \"\"\"\n Implementation of a postprocessor based on adding class labels to classifier output.\n \"\"\"\n\n def __init__(self, apply_fit: bool = False, apply_predict: bool = True) -> None:\n \"\"\"\n Create a ClassLabels postprocessor.\n\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n\n def __call__(self, preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform model postprocessing and return postprocessed output.\n\n :param preds: model output to be postprocessed.\n :return: Postprocessed model output.\n \"\"\"\n class_labels = np.zeros_like(preds)\n if preds.shape[1] > 1:\n index_labels = np.argmax(preds, axis=1)\n class_labels[:, index_labels] = 1\n else:\n class_labels[preds > 0.5] = 1\n\n return class_labels\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/gaussian_noise.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Gaussian noise added to the classifier output.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.defences.postprocessor.postprocessor import Postprocessor\nfrom art.utils import is_probability\n\nlogger = logging.getLogger(__name__)\n\n\nclass GaussianNoise(Postprocessor):\n \"\"\"\n Implementation of a postprocessor based on adding Gaussian noise to classifier output.\n \"\"\"\n\n params = [\"scale\"]\n\n def __init__(self, scale: float = 0.2, apply_fit: bool = False, apply_predict: bool = True) -> None:\n \"\"\"\n Create a GaussianNoise postprocessor.\n\n :param scale: Standard deviation of the distribution.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.scale = scale\n self._check_params()\n\n def __call__(self, preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform model postprocessing and return postprocessed output.\n\n :param preds: model output to be postprocessed.\n :return: Postprocessed model output.\n \"\"\"\n # Generate random noise\n noise = np.random.normal(loc=0.0, scale=self.scale, size=preds.shape)\n\n # Add noise to model output\n post_preds = preds.copy()\n post_preds += noise\n\n if preds.shape[1] > 1:\n # Check if model output is logits or probability\n are_probability = [is_probability(x) for x in preds]\n all_probability = np.sum(are_probability) == preds.shape[0]\n\n # Finally normalize probability output\n if all_probability:\n post_preds[post_preds < 0.0] = 0.0\n sums = np.sum(post_preds, axis=1, keepdims=True)\n post_preds /= sums\n else:\n post_preds[post_preds < 0.0] = 0.0\n\n return post_preds\n\n def _check_params(self) -> None:\n if self.scale <= 0:\n raise ValueError(\"Standard deviation must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/high_confidence.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements confidence added to the classifier output.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass HighConfidence(Postprocessor):\n \"\"\"\n Implementation of a postprocessor based on selecting high confidence predictions to return as classifier output.\n \"\"\"\n\n params = [\"cutoff\"]\n\n def __init__(self, cutoff: float = 0.25, apply_fit: bool = False, apply_predict: bool = True) -> None:\n \"\"\"\n Create a HighConfidence postprocessor.\n\n :param cutoff: Minimal value for returned prediction output.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.cutoff = cutoff\n self._check_params()\n\n def __call__(self, preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform model postprocessing and return postprocessed output.\n\n :param preds: model output to be postprocessed.\n :return: Postprocessed model output.\n \"\"\"\n post_preds = preds.copy()\n post_preds[post_preds < self.cutoff] = 0.0\n\n return post_preds\n\n def _check_params(self) -> None:\n if self.cutoff <= 0:\n raise ValueError(\"Minimal value must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/postprocessor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for defences that post-process classifier output.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\n\nimport numpy as np\n\n\nclass Postprocessor(abc.ABC):\n \"\"\"\n Abstract base class for postprocessing defences. Postprocessing defences are not included in the loss function\n evaluation for loss gradients or the calculation of class gradients.\n \"\"\"\n\n params: list[str] = []\n\n def __init__(self, is_fitted: bool = False, apply_fit: bool = True, apply_predict: bool = True) -> None:\n \"\"\"\n Create a postprocessing object.\n\n Optionally, set attributes.\n \"\"\"\n self._is_fitted = bool(is_fitted)\n self._apply_fit = bool(apply_fit)\n self._apply_predict = bool(apply_predict)\n Postprocessor._check_params(self)\n\n @property\n def is_fitted(self) -> bool:\n \"\"\"\n Return the state of the postprocessing object.\n\n :return: `True` if the postprocessing model has been fitted (if this applies).\n \"\"\"\n return self._is_fitted\n\n @property\n def apply_fit(self) -> bool:\n \"\"\"\n Property of the defence indicating if it should be applied at training time.\n\n :return: `True` if the defence should be applied when fitting a model, `False` otherwise.\n \"\"\"\n return self._apply_fit\n\n @property\n def apply_predict(self) -> bool:\n \"\"\"\n Property of the defence indicating if it should be applied at test time.\n\n :return: `True` if the defence should be applied at prediction time, `False` otherwise.\n \"\"\"\n return self._apply_predict\n\n @abc.abstractmethod\n def __call__(self, preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform model postprocessing and return postprocessed output.\n\n :param preds: model output to be postprocessed.\n :return: Postprocessed model output.\n \"\"\"\n raise NotImplementedError\n\n def fit(self, preds: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the parameters of the postprocessor if it has any.\n\n :param preds: Training set to fit the postprocessor.\n :param kwargs: Other parameters.\n \"\"\"\n pass\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and apply checks before saving them as attributes.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.params:\n setattr(self, key, value)\n self._check_params()\n\n def _check_params(self) -> None:\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/reverse_sigmoid.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Reverse Sigmoid perturbation for the classifier output.\n\n| Paper link: https://arxiv.org/abs/1806.00054\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass ReverseSigmoid(Postprocessor):\n \"\"\"\n Implementation of a postprocessor based on adding the Reverse Sigmoid perturbation to classifier output.\n \"\"\"\n\n params = [\"beta\", \"gamma\"]\n\n def __init__(\n self,\n beta: float = 1.0,\n gamma: float = 0.1,\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create a ReverseSigmoid postprocessor.\n\n :param beta: A positive magnitude parameter.\n :param gamma: A positive dataset and model specific convergence parameter.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.beta = beta\n self.gamma = gamma\n self._check_params()\n\n def __call__(self, preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform model postprocessing and return postprocessed output.\n\n :param preds: model output to be postprocessed.\n :return: Postprocessed model output.\n \"\"\"\n clip_min = 1e-9\n clip_max = 1.0 - clip_min\n\n def sigmoid(var_z):\n return 1.0 / (1.0 + np.exp(-var_z))\n\n preds_clipped = np.clip(preds, clip_min, clip_max)\n\n if preds.shape[1] > 1:\n perturbation_r = self.beta * (sigmoid(-self.gamma * np.log((1.0 - preds_clipped) / preds_clipped)) - 0.5)\n preds_perturbed = preds - perturbation_r\n preds_perturbed = np.clip(preds_perturbed, 0.0, 1.0)\n alpha = 1.0 / np.sum(preds_perturbed, axis=-1, keepdims=True)\n reverse_sigmoid = alpha * preds_perturbed\n else:\n preds_1 = preds\n preds_2 = 1.0 - preds\n\n preds_clipped_1 = preds_clipped\n preds_clipped_2 = 1.0 - preds_clipped\n\n perturbation_r_1 = self.beta * (\n sigmoid(-self.gamma * np.log((1.0 - preds_clipped_1) / preds_clipped_1)) - 0.5\n )\n perturbation_r_2 = self.beta * (\n sigmoid(-self.gamma * np.log((1.0 - preds_clipped_2) / preds_clipped_2)) - 0.5\n )\n\n preds_perturbed_1 = preds_1 - perturbation_r_1\n preds_perturbed_2 = preds_2 - perturbation_r_2\n\n preds_perturbed_1 = np.clip(preds_perturbed_1, 0.0, 1.0)\n preds_perturbed_2 = np.clip(preds_perturbed_2, 0.0, 1.0)\n\n alpha = 1.0 / (preds_perturbed_1 + preds_perturbed_2)\n reverse_sigmoid = alpha * preds_perturbed_1\n\n return reverse_sigmoid\n\n def _check_params(self) -> None:\n if self.beta <= 0:\n raise ValueError(\"Magnitude parameter must be positive.\")\n\n if self.gamma <= 0:\n raise ValueError(\"Convergence parameter must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/postprocessor/rounded.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a rounding to the classifier output.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass Rounded(Postprocessor):\n \"\"\"\n Implementation of a postprocessor based on rounding classifier output.\n \"\"\"\n\n params = [\"decimals\"]\n\n def __init__(self, decimals: int = 3, apply_fit: bool = False, apply_predict: bool = True) -> None:\n \"\"\"\n Create a Rounded postprocessor.\n\n :param decimals: Number of decimal places after the decimal point.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.decimals = decimals\n self._check_params()\n\n def __call__(self, preds: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform model postprocessing and return postprocessed output.\n\n :param preds: model output to be postprocessed.\n :return: Postprocessed model output.\n \"\"\"\n return np.around(preds, decimals=self.decimals)\n\n def _check_params(self) -> None:\n if not isinstance(self.decimals, int) or self.decimals <= 0:\n raise ValueError(\"Number of decimal places must be a positive integer.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing preprocessing defences against adversarial attacks.\n\"\"\"\n\nfrom art.defences.preprocessor.cutmix.cutmix import CutMix\nfrom art.defences.preprocessor.cutmix.cutmix_pytorch import CutMixPyTorch\nfrom art.defences.preprocessor.cutmix.cutmix_tensorflow import CutMixTensorFlowV2\nfrom art.defences.preprocessor.cutout.cutout import Cutout\nfrom art.defences.preprocessor.cutout.cutout_pytorch import CutoutPyTorch\nfrom art.defences.preprocessor.cutout.cutout_tensorflow import CutoutTensorFlowV2\nfrom art.defences.preprocessor.feature_squeezing import FeatureSqueezing\nfrom art.defences.preprocessor.gaussian_augmentation import GaussianAugmentation\nfrom art.defences.preprocessor.jpeg_compression import JpegCompression\nfrom art.defences.preprocessor.label_smoothing import LabelSmoothing\nfrom art.defences.preprocessor.mixup.mixup import Mixup\nfrom art.defences.preprocessor.mixup.mixup_pytorch import MixupPyTorch\nfrom art.defences.preprocessor.mixup.mixup_tensorflow import MixupTensorFlowV2\nfrom art.defences.preprocessor.mp3_compression import Mp3Compression\nfrom art.defences.preprocessor.mp3_compression_pytorch import Mp3CompressionPyTorch\nfrom art.defences.preprocessor.pixel_defend import PixelDefend\nfrom art.defences.preprocessor.preprocessor import Preprocessor\nfrom art.defences.preprocessor.resample import Resample\nfrom art.defences.preprocessor.spatial_smoothing import SpatialSmoothing\nfrom art.defences.preprocessor.spatial_smoothing_pytorch import SpatialSmoothingPyTorch\nfrom art.defences.preprocessor.spatial_smoothing_tensorflow import SpatialSmoothingTensorFlowV2\nfrom art.defences.preprocessor.thermometer_encoding import ThermometerEncoding\nfrom art.defences.preprocessor.variance_minimization import TotalVarMin\nfrom art.defences.preprocessor.video_compression import VideoCompression\nfrom art.defences.preprocessor.video_compression_pytorch import VideoCompressionPyTorch\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/feature_squeezing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the feature squeezing defence in `FeatureSqueezing`.\n\n| Paper link: https://arxiv.org/abs/1704.01155\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence, see\n https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\n\nfrom art.utils import CLIP_VALUES_TYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass FeatureSqueezing(Preprocessor):\n \"\"\"\n Reduces the sensibility of the features of a sample.\n\n | Paper link: https://arxiv.org/abs/1704.01155\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"clip_values\", \"bit_depth\"]\n\n def __init__(\n self,\n clip_values: CLIP_VALUES_TYPE,\n bit_depth: int = 8,\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of feature squeezing.\n\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param bit_depth: The number of bits per channel for encoding the data.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.clip_values = clip_values\n self.bit_depth = bit_depth\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply feature squeezing to sample `x`.\n\n :param x: Sample to squeeze. `x` values are expected to be in the data range provided by `clip_values`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Squeezed sample.\n \"\"\"\n x_normalized = x - self.clip_values[0]\n x_normalized = x_normalized / (self.clip_values[1] - self.clip_values[0])\n\n max_value = np.rint(2**self.bit_depth - 1)\n res = np.rint(x_normalized * max_value) / max_value\n\n res = res * (self.clip_values[1] - self.clip_values[0])\n res = res + self.clip_values[0]\n\n return res, y\n\n def _check_params(self) -> None:\n if not isinstance(self.bit_depth, int) or self.bit_depth <= 0 or self.bit_depth > 64:\n raise ValueError(\"The bit depth must be between 1 and 64.\")\n\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/gaussian_augmentation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Gaussian augmentation defence in `GaussianAugmentation`.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass GaussianAugmentation(Preprocessor):\n \"\"\"\n Add Gaussian noise to a dataset in one of two ways: either add noise to each sample (keeping the size of the\n original dataset) or perform augmentation by keeping all original samples and adding noisy counterparts. When used\n as part of a :class:`.Classifier` instance, the defense will be applied automatically only when training if\n `augmentation` is true, and only when performing prediction otherwise.\n \"\"\"\n\n params = [\n \"sigma\",\n \"augmentation\",\n \"ratio\",\n \"clip_values\",\n \"_apply_fit\",\n \"_apply_predict\",\n ]\n\n def __init__(\n self,\n sigma: float = 1.0,\n augmentation: bool = True,\n ratio: float = 1.0,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n ):\n \"\"\"\n Initialize a Gaussian augmentation object.\n\n :param sigma: Standard deviation of Gaussian noise to be added.\n :param augmentation: If true, perform dataset augmentation using `ratio`, otherwise replace samples with noisy\n counterparts.\n :param ratio: Percentage of data augmentation. E.g. for a rate of 1, the size of the dataset will double.\n If `augmentation` is false, `ratio` value is ignored.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n if augmentation and not apply_fit and apply_predict:\n raise ValueError(\n \"If `augmentation` is `True`, then `apply_fit` must be `True` and `apply_predict` must be `False`.\"\n )\n if augmentation and not (apply_fit or apply_predict):\n raise ValueError(\"If `augmentation` is `True`, then `apply_fit` and `apply_predict` can't be both `False`.\")\n\n self.sigma = sigma\n self.augmentation = augmentation\n self.ratio = ratio\n self.clip_values = clip_values\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Augment the sample `(x, y)` with Gaussian noise. The result is either an extended dataset containing the\n original sample, as well as the newly created noisy samples (augmentation=True) or just the noisy counterparts\n to the original samples.\n\n :param x: Sample to augment with shape `(batch_size, width, height, depth)`.\n :param y: Labels for the sample. If this argument is provided, it will be augmented with the corresponded\n original labels of each sample point.\n :return: The augmented dataset and (if provided) corresponding labels.\n \"\"\"\n logger.info(\"Original dataset size: %d\", x.shape[0])\n\n # Select indices to augment\n if self.augmentation:\n size = int(x.shape[0] * self.ratio)\n indices = np.random.randint(0, x.shape[0], size=size)\n\n # Generate noisy samples\n x_aug = np.random.normal(x[indices], scale=self.sigma, size=(size,) + x.shape[1:]).astype(ART_NUMPY_DTYPE)\n x_aug = np.vstack((x, x_aug))\n if y is not None:\n y_aug = np.concatenate((y, y[indices]))\n else:\n y_aug = y\n logger.info(\"Augmented dataset size: %d\", x_aug.shape[0])\n else:\n x_aug = np.random.normal(x, scale=self.sigma, size=x.shape).astype(ART_NUMPY_DTYPE)\n y_aug = y\n logger.info(\"Created %i samples with Gaussian noise.\")\n\n if self.clip_values is not None:\n x_aug = np.clip(x_aug, self.clip_values[0], self.clip_values[1])\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.augmentation and self.ratio <= 0:\n raise ValueError(\"The augmentation ratio must be positive.\")\n\n if self.clip_values is not None:\n\n if len(self.clip_values) != 2:\n raise ValueError(\n \"`clip_values` should be a tuple of 2 floats or arrays containing the allowed data range.\"\n )\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/jpeg_compression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the JPEG compression defence `JpegCompression`.\n\n| Paper link: https://arxiv.org/abs/1705.02900, https://arxiv.org/abs/1608.00853\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence, see\n https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom io import BytesIO\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass JpegCompression(Preprocessor):\n \"\"\"\n Implement the JPEG compression defence approach.\n\n For input images or videos with 3 color channels the compression is applied in mode `RGB`\n (3x8-bit pixels, true color), for all other numbers of channels the compression is applied for each channel with\n mode `L` (8-bit pixels, black and white).\n\n | Paper link: https://arxiv.org/abs/1705.02900, https://arxiv.org/abs/1608.00853\n\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"quality\", \"channels_first\", \"clip_values\", \"verbose\"]\n\n def __init__(\n self,\n clip_values: \"CLIP_VALUES_TYPE\",\n quality: int = 50,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = True,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of JPEG compression.\n\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param quality: The image quality, on a scale from 1 (worst) to 95 (best). Values above 95 should be avoided.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.quality = quality\n self.channels_first = channels_first\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def _compress(self, x: np.ndarray, mode: str) -> np.ndarray:\n \"\"\"\n Apply JPEG compression to image input.\n \"\"\"\n from PIL import Image\n\n tmp_jpeg = BytesIO()\n x_image = Image.fromarray(x, mode=mode)\n x_image.save(tmp_jpeg, format=\"jpeg\", quality=self.quality)\n x_jpeg = np.array(Image.open(tmp_jpeg))\n tmp_jpeg.close()\n return x_jpeg\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply JPEG compression to sample `x`.\n\n For input images or videos with 3 color channels the compression is applied in mode `RGB`\n (3x8-bit pixels, true color), for all other numbers of channels the compression is applied for each channel with\n mode `L` (8-bit pixels, black and white).\n\n :param x: Sample to compress with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`. `x` values are expected to be in\n the data range [0, 1] or [0, 255].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: compressed sample.\n \"\"\"\n x_ndim = x.ndim\n if x_ndim not in [4, 5]:\n raise ValueError(\n \"Unrecognized input dimension. JPEG compression can only be applied to image and video data.\"\n )\n\n if x.min() < 0.0:\n raise ValueError(\n \"Negative values in input `x` detected. The JPEG compression defence requires unnormalized input.\"\n )\n\n # Swap channel index\n if self.channels_first and x_ndim == 4:\n # image shape NCHW to NHWC\n x = np.transpose(x, (0, 2, 3, 1))\n elif self.channels_first and x_ndim == 5:\n # video shape NCFHW to NFHWC\n x = np.transpose(x, (0, 2, 3, 4, 1))\n\n # insert temporal dimension to image data\n if x_ndim == 4:\n x = np.expand_dims(x, axis=1)\n\n # Convert into uint8\n if self.clip_values[1] == 1.0:\n x = x * 255\n x = x.astype(\"uint8\")\n\n # Compress one image at a time\n x_jpeg = x.copy()\n for idx in tqdm(np.ndindex(x.shape[:2]), desc=\"JPEG compression\", disable=not self.verbose): # type: ignore\n if x.shape[-1] == 3:\n x_jpeg[idx] = self._compress(x[idx], mode=\"RGB\")\n else:\n for i_channel in range(x.shape[-1]):\n x_channel = x[idx[0], idx[1], ..., i_channel]\n x_channel = self._compress(x_channel, mode=\"L\")\n x_jpeg[idx[0], idx[1], :, :, i_channel] = x_channel\n\n # Convert to ART dtype\n if self.clip_values[1] == 1.0:\n x_jpeg = x_jpeg / 255.0\n x_jpeg = x_jpeg.astype(ART_NUMPY_DTYPE)\n\n # remove temporal dimension for image data\n if x_ndim == 4:\n x_jpeg = np.squeeze(x_jpeg, axis=1)\n\n # Swap channel index\n if self.channels_first and x_jpeg.ndim == 4:\n # image shape NHWC to NCHW\n x_jpeg = np.transpose(x_jpeg, (0, 3, 1, 2))\n elif self.channels_first and x_ndim == 5:\n # video shape NFHWC to NCFHW\n x_jpeg = np.transpose(x_jpeg, (0, 4, 1, 2, 3))\n return x_jpeg, y\n\n def _check_params(self) -> None:\n if not isinstance(self.quality, int) or self.quality <= 0 or self.quality > 100:\n raise ValueError(\"Image quality must be a positive integer <= 100.\")\n\n if len(self.clip_values) != 2:\n raise ValueError(\"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\")\n\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid 'clip_values': min >= max.\")\n\n if self.clip_values[0] != 0:\n raise ValueError(\"'clip_values' min value must be 0.\")\n\n if self.clip_values[1] != 1.0 and self.clip_values[1] != 255:\n raise ValueError(\"'clip_values' max value must be either 1 or 255.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/label_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the label smoothing defence in `LabelSmoothing`. It computes a vector of smooth labels from a\nvector of hard labels.\n\n| Paper link: https://pdfs.semanticscholar.org/b5ec/486044c6218dd41b17d8bba502b32a12b91a.pdf\n\n| Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705 .\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass LabelSmoothing(Preprocessor):\n \"\"\"\n Computes a vector of smooth labels from a vector of hard ones. The hard labels have to contain ones for the\n correct classes and zeros for all the others. The remaining probability mass between `max_value` and 1 is\n distributed uniformly between the incorrect classes for each instance.\n\n\n | Paper link: https://pdfs.semanticscholar.org/b5ec/486044c6218dd41b17d8bba502b32a12b91a.pdf\n\n | Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705 .\n \"\"\"\n\n params = [\"max_value\"]\n\n def __init__(\n self,\n max_value: float = 0.9,\n apply_fit: bool = True,\n apply_predict: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of label smoothing.\n\n :param max_value: Value to affect to correct label\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.max_value = max_value\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply label smoothing.\n\n :param x: Input data, will not be modified by this method.\n :param y: Original vector of label probabilities (one-vs-rest).\n :return: Unmodified input data and the vector of smooth probabilities as correct labels.\n :raises `ValueError`: If no labels are provided.\n \"\"\"\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n min_value = (1 - self.max_value) / (y.shape[1] - 1)\n assert self.max_value >= min_value\n\n smooth_y = y.copy()\n smooth_y[smooth_y == 1.0] = self.max_value\n smooth_y[smooth_y == 0.0] = min_value\n return x, smooth_y\n\n def _check_params(self) -> None:\n if self.max_value <= 0 or self.max_value > 1:\n raise ValueError(\"The maximum value for correct labels must be between 0 and 1.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/mp3_compression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the MP3 compression defence `Mp3Compression`.\n\n| Paper link: https://arxiv.org/abs/1801.01944\n\n| Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom io import BytesIO\n\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass Mp3Compression(Preprocessor):\n \"\"\"\n Implement the MP3 compression defense approach.\n \"\"\"\n\n params = [\"channels_first\", \"sample_rate\", \"verbose\"]\n\n def __init__(\n self,\n sample_rate: int,\n channels_first: bool = False,\n apply_fit: bool = False,\n apply_predict: bool = True,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of MP3 compression.\n\n :param sample_rate: Specifies the sampling rate of sample.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.channels_first = channels_first\n self.sample_rate = sample_rate\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply MP3 compression to sample `x`.\n\n :param x: Sample to compress with shape `(batch_size, length, channel)` or an array of sample arrays with shape\n (length,) or (length, channel).\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Compressed sample.\n \"\"\"\n\n def wav_to_mp3(x, sample_rate):\n \"\"\"\n Apply MP3 compression to audio input of shape (samples, channel).\n \"\"\"\n from pydub import AudioSegment\n from scipy.io.wavfile import write\n\n x_dtype = x.dtype\n normalized = bool(x.min() >= -1.0 and x.max() <= 1.0)\n if x_dtype != np.int16 and not normalized:\n # input is not of type np.int16 and seems to be unnormalized. Therefore, casting to np.int16.\n x = x.astype(np.int16)\n elif x_dtype != np.int16 and normalized:\n # x is not of type np.int16 and seems to be normalized. Therefore, undoing normalization and\n # casting to np.int16.\n x = (x * 2**15).astype(np.int16)\n\n tmp_wav, tmp_mp3 = BytesIO(), BytesIO()\n write(tmp_wav, sample_rate, x)\n AudioSegment.from_wav(tmp_wav).export(tmp_mp3)\n audio_segment = AudioSegment.from_mp3(tmp_mp3)\n tmp_wav.close()\n tmp_mp3.close()\n x_mp3 = np.array(audio_segment.get_array_of_samples()).reshape((-1, audio_segment.channels))\n\n # WARNING: Sometimes we *still* need to manually resize x_mp3 to original length.\n # This should not be the case, e.g. see https://github.com/jiaaro/pydub/issues/474\n if x.shape[0] != x_mp3.shape[0]: # pragma: no cover\n logger.warning(\n \"Lengths original input and compressed output don't match. Truncating compressed result.\"\n )\n x_mp3 = x_mp3[: x.shape[0]]\n\n if normalized:\n # x was normalized. Therefore, normalizing x_mp3.\n x_mp3 = x_mp3 * 2**-15\n return x_mp3.astype(x_dtype)\n\n x_orig_type = x.dtype\n if x.dtype != object and x.ndim == 2:\n x = x.astype(object)\n\n if x.dtype != object and x.ndim != 3:\n raise ValueError(\"Mp3 compression can only be applied to temporal data across at least one channel.\")\n\n if x.dtype != object and self.channels_first:\n x = np.swapaxes(x, 1, 2)\n\n # apply mp3 compression per audio item\n x_mp3 = x.copy()\n for i, x_i in enumerate(tqdm(x, desc=\"MP3 compression\", disable=not self.verbose)):\n x_i_ndim_0 = x_i.ndim\n if x.dtype == object:\n if x_i.ndim == 1:\n x_i = np.expand_dims(x_i, axis=1)\n\n if x_i_ndim_0 == 2 and self.channels_first:\n x_i = np.swapaxes(x_i, 0, 1)\n\n x_i = wav_to_mp3(x_i, self.sample_rate)\n\n if x.dtype == object:\n if x_i_ndim_0 == 2 and self.channels_first:\n x_i = np.swapaxes(x_i, 0, 1)\n\n if x_i_ndim_0 == 1:\n x_i = np.squeeze(x_i)\n\n x_mp3[i] = x_i\n\n if x.dtype != object and self.channels_first:\n x_mp3 = np.swapaxes(x_mp3, 1, 2)\n\n if x_orig_type != object and x.dtype == object and x.ndim == 2: # noqa: E721\n x_mp3 = x_mp3.astype(x_orig_type)\n\n return x_mp3, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.sample_rate, int) and self.sample_rate > 0):\n raise ValueError(\"Sample rate be must a positive integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/mp3_compression_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a wrapper for MP3 compression defence.\n\n| Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom art.defences.preprocessor.mp3_compression import Mp3Compression\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\n\nlogger = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n\n import torch\n\n\nclass Mp3CompressionPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement the MP3 compression defense approach.\n \"\"\"\n\n params = [\"channels_first\", \"sample_rate\", \"verbose\"]\n\n def __init__(\n self,\n sample_rate: int,\n channels_first: bool = False,\n apply_fit: bool = False,\n apply_predict: bool = True,\n device_type: str = \"gpu\",\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of MP3 compression.\n\n :param sample_rate: Specifies the sampling rate of sample.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param verbose: Show progress bars.\n \"\"\"\n from torch.autograd import Function\n\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n self.channels_first = channels_first\n self.sample_rate = sample_rate\n self.verbose = verbose\n self._check_params()\n\n self.compression_numpy = Mp3Compression(\n sample_rate=sample_rate,\n channels_first=channels_first,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n verbose=verbose,\n )\n\n class CompressionPyTorchNumpy(Function): # pylint: disable=abstract-method\n \"\"\"\n Function running Preprocessor.\n \"\"\"\n\n @staticmethod\n def forward(ctx, input): # pylint: disable=redefined-builtin,arguments-differ\n numpy_input = input.detach().cpu().numpy()\n result, _ = self.compression_numpy(numpy_input)\n return input.new(result)\n\n @staticmethod\n def backward(ctx, grad_output):\n numpy_go = grad_output.cpu().numpy()\n # np.expand_dims(input, axis=[0, 2])\n result = self.compression_numpy.estimate_gradient(None, numpy_go)\n # result = result.squeeze()\n return grad_output.new(result)\n\n self._compression_pytorch_numpy = CompressionPyTorchNumpy\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply MP3 compression to sample `x`.\n\n :param x: Sample to compress with shape `(length, channel)` or an array of sample arrays with shape\n (length,) or (length, channel).\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Compressed sample.\n \"\"\"\n import torch\n\n ndim = x.ndim\n\n if ndim == 1:\n x = torch.unsqueeze(x, dim=0)\n if self.channels_first:\n dim = 1\n else:\n dim = 2\n x = torch.unsqueeze(x, dim=dim)\n\n x_compressed = self._compression_pytorch_numpy.apply(x)\n\n if ndim == 1:\n x_compressed = torch.squeeze(x_compressed)\n\n return x_compressed, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.sample_rate, int) and self.sample_rate > 0):\n raise ValueError(\"Sample rate be must a positive integer.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/pixel_defend.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implement the pixel defence in `PixelDefend`. It is based on PixelCNN that projects samples back to the data\nmanifold.\n\n| Paper link: https://arxiv.org/abs/1710.10766\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, CLASSIFIER_NEURALNETWORK_TYPE\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PixelDefend(Preprocessor):\n \"\"\"\n Implement the pixel defence approach. Defense based on PixelCNN that projects samples back to the data manifold.\n\n | Paper link: https://arxiv.org/abs/1710.10766\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"clip_values\", \"eps\", \"pixel_cnn\", \"verbose\"]\n\n def __init__(\n self,\n clip_values: \"CLIP_VALUES_TYPE\" = (0.0, 1.0),\n eps: int = 16,\n pixel_cnn: \"CLASSIFIER_NEURALNETWORK_TYPE\" | None = None,\n batch_size: int = 128,\n apply_fit: bool = False,\n apply_predict: bool = True,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of pixel defence.\n\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param eps: Defense parameter 0-255.\n :param pixel_cnn: Pre-trained PixelCNN model.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.clip_values = clip_values\n self.eps = eps\n self.batch_size = batch_size\n self.pixel_cnn = pixel_cnn\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply pixel defence to sample `x`.\n\n :param x: Sample to defense with shape `(batch_size, width, height, depth)`. `x` values are expected to be in\n the data range [0, 1].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Purified sample.\n \"\"\"\n # Convert into `uint8`\n original_shape = x.shape\n if self.pixel_cnn is not None:\n activations = self.pixel_cnn.get_activations(x, layer=-1, batch_size=self.batch_size)\n if isinstance(activations, np.ndarray):\n probs = activations.reshape((x.shape[0], -1, 256))\n else:\n raise ValueError(\"Activations are None.\")\n else:\n raise ValueError(\"No model received for `pixel_cnn`.\")\n\n x = x * 255\n x = x.astype(\"uint8\")\n x = x.reshape((x.shape[0], -1))\n\n # Start defence one image at a time\n for i, x_i in enumerate(tqdm(x, desc=\"PixelDefend\", disable=not self.verbose)):\n for feat_index in range(x.shape[1]):\n # Set up the search space\n f_probs = probs[i, feat_index, :]\n f_range = range(\n int(max(x_i[feat_index] - self.eps, 0)),\n int(min(x_i[feat_index] + self.eps, 255) + 1),\n )\n\n # Look in the search space\n best_prob = -1\n best_idx = -1\n for idx in f_range:\n if f_probs[idx] > best_prob:\n best_prob = f_probs[idx]\n best_idx = idx\n\n # Update result\n x_i[feat_index] = best_idx\n\n # Update in batch\n x[i] = x_i\n\n # Convert to old dtype\n x = x / 255.0\n x = x.astype(ART_NUMPY_DTYPE).reshape(original_shape)\n\n # Clip to clip_values\n x = np.clip(x, self.clip_values[0], self.clip_values[1])\n\n return x, y\n\n def _check_params(self) -> None:\n\n if not isinstance(self.eps, int) or self.eps < 0 or self.eps > 255:\n raise ValueError(\"The defense parameter must be between 0 and 255.\")\n\n from art.estimators.classification.classifier import ClassifierMixin\n from art.estimators.estimator import NeuralNetworkMixin\n\n if hasattr(self, \"pixel_cnn\") and not (\n isinstance(self.pixel_cnn, ClassifierMixin) and isinstance(self.pixel_cnn, NeuralNetworkMixin)\n ):\n raise TypeError(\"PixelCNN model must be of type Classifier.\")\n\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n if self.clip_values[0] != 0:\n raise ValueError(\"`clip_values` min value must be 0.\")\n\n if self.clip_values[1] != 1:\n raise ValueError(\"`clip_values` max value must be 1.\")\n\n if self.batch_size <= 0:\n raise ValueError(\"The batch size `batch_size` has to be positive.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/preprocessor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for defences that pre-process input data.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art import config\n\nif TYPE_CHECKING:\n import torch\n import tensorflow as tf\n\n\nclass Preprocessor(abc.ABC):\n \"\"\"\n Abstract base class for preprocessing defences.\n\n By default, the gradient is estimated using BPDA with the identity function.\n To modify, override `estimate_gradient`\n \"\"\"\n\n params: list[str] = []\n\n def __init__(self, is_fitted: bool = False, apply_fit: bool = True, apply_predict: bool = True) -> None:\n \"\"\"\n Create a preprocessing object.\n\n Optionally, set attributes.\n \"\"\"\n self._is_fitted = bool(is_fitted)\n self._apply_fit = bool(apply_fit)\n self._apply_predict = bool(apply_predict)\n\n @property\n def is_fitted(self) -> bool:\n \"\"\"\n Return the state of the preprocessing object.\n\n :return: `True` if the preprocessing model has been fitted (if this applies).\n \"\"\"\n return self._is_fitted\n\n @property\n def apply_fit(self) -> bool:\n \"\"\"\n Property of the defence indicating if it should be applied at training time.\n\n :return: `True` if the defence should be applied when fitting a model, `False` otherwise.\n \"\"\"\n return self._apply_fit\n\n @property\n def apply_predict(self) -> bool:\n \"\"\"\n Property of the defence indicating if it should be applied at test time.\n\n :return: `True` if the defence should be applied at prediction time, `False` otherwise.\n \"\"\"\n return self._apply_predict\n\n @abc.abstractmethod\n def __call__(self, x: np.ndarray, y: Any | None = None) -> tuple[np.ndarray, Any | None]:\n \"\"\"\n Perform data preprocessing and return preprocessed data as tuple.\n\n :param x: Dataset to be preprocessed.\n :param y: Labels to be preprocessed.\n :return: Preprocessed data.\n \"\"\"\n raise NotImplementedError\n\n def fit(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> None:\n \"\"\"\n Fit the parameters of the data preprocessor if it has any.\n\n :param x: Training set to fit the preprocessor.\n :param y: Labels for the training set.\n :param kwargs: Other parameters.\n \"\"\"\n pass\n\n def estimate_gradient(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Provide an estimate of the gradients of the defence for the backward pass. If the defence is not differentiable,\n this is an estimate of the gradient, most often replacing the computation performed by the defence with the\n identity function (the default).\n\n :param x: Input data for which the gradient is estimated. First dimension is the batch size.\n :param grad: Gradient value so far.\n :return: The gradient (estimate) of the defence.\n \"\"\"\n return grad\n\n def set_params(self, **kwargs) -> None: # pragma: no cover\n \"\"\"\n Take in a dictionary of parameters and apply checks before saving them as attributes.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.params:\n setattr(self, key, value)\n self._check_params()\n\n def _check_params(self) -> None: # pragma: no cover\n pass\n\n def forward(self, x: Any, y: Any = None) -> tuple[Any, Any]:\n \"\"\"\n Perform data preprocessing and return preprocessed data.\n\n :param x: Dataset to be preprocessed.\n :param y: Labels to be preprocessed.\n :return: Preprocessed data.\n \"\"\"\n raise NotImplementedError\n\n\nclass PreprocessorPyTorch(Preprocessor):\n \"\"\"\n Abstract base class for preprocessing defences implemented in PyTorch that support efficient preprocessor-chaining.\n \"\"\"\n\n def __init__(self, device_type: str = \"gpu\", **kwargs):\n import torch\n\n super().__init__(**kwargs)\n\n # Set device\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self._device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self._device = torch.device(f\"cuda:{cuda_idx}\")\n\n @abc.abstractmethod\n def forward(self, x: \"torch.Tensor\", y: Any | None = None) -> tuple[\"torch.Tensor\", Any | None]:\n \"\"\"\n Perform data preprocessing in PyTorch and return preprocessed data as tuple.\n\n :param x: Dataset to be preprocessed.\n :param y: Labels to be preprocessed.\n :return: Preprocessed data.\n \"\"\"\n raise NotImplementedError\n\n def estimate_forward(self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None) -> \"torch.Tensor\":\n \"\"\"\n Provide a differentiable estimate of the forward function, so that autograd can calculate gradients\n of the defence for the backward pass. If the defence is differentiable, just call `self.forward()`.\n If the defence is not differentiable and a differentiable estimate is not available, replace with\n an identity function.\n\n :param x: Dataset to be preprocessed.\n :param y: Labels to be preprocessed.\n :return: Preprocessed data.\n \"\"\"\n return self.forward(x, y=y)[0]\n\n @property\n def device(self):\n \"\"\"\n Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n return self._device\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply preprocessing to input `x` and labels `y`.\n\n :param x: Sample to smooth with shape `(batch_size, width, height, depth)`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Smoothed sample.\n \"\"\"\n import torch\n\n x_tensor = torch.tensor(x, device=self.device)\n if y is not None:\n y_tensor: torch.Tensor | None = torch.tensor(y, device=self.device)\n else:\n y_tensor = None\n\n with torch.no_grad():\n x_tensor, y_tensor = self.forward(x_tensor, y_tensor)\n\n x_result = x_tensor.cpu().numpy()\n if y_tensor is not None:\n y_result: np.ndarray | None = y_tensor.cpu().numpy()\n else:\n y_result = None\n return x_result, y_result\n\n # Backward compatibility.\n def estimate_gradient(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n import torch\n\n def get_gradient(x, grad):\n x = torch.tensor(x, device=self.device, requires_grad=True)\n grad = torch.tensor(grad, device=self.device)\n\n x_prime = self.estimate_forward(x)\n x_prime.backward(grad)\n x_grad = x.grad.detach().cpu().numpy()\n\n if x_grad.shape != x.shape:\n raise ValueError(f\"The input shape is {x.shape} while the gradient shape is {x_grad.shape}\")\n\n return x_grad\n\n if x.dtype == object:\n x_grad_list = []\n for i, x_i in enumerate(x):\n x_grad_list.append(get_gradient(x=x_i, grad=grad[i]))\n x_grad = np.empty(x.shape[0], dtype=object)\n x_grad[:] = list(x_grad_list)\n elif x.shape == grad.shape:\n x_grad = get_gradient(x=x, grad=grad)\n else:\n # Special case for loss gradients\n x_grad = np.zeros_like(grad)\n for i in range(grad.shape[1]):\n x_grad[:, i, ...] = get_gradient(x=x, grad=grad[:, i, ...])\n\n return x_grad\n\n\nclass PreprocessorTensorFlowV2(Preprocessor):\n \"\"\"\n Abstract base class for preprocessing defences implemented in TensorFlow v2 that support efficient\n preprocessor-chaining.\n \"\"\"\n\n @abc.abstractmethod\n def forward(self, x: \"tf.Tensor\", y: Any | None = None) -> tuple[\"tf.Tensor\", Any | None]:\n \"\"\"\n Perform data preprocessing in TensorFlow v2 and return preprocessed data as tuple.\n\n :param x: Dataset to be preprocessed.\n :param y: Labels to be preprocessed.\n :return: Preprocessed data.\n \"\"\"\n raise NotImplementedError\n\n def estimate_forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> \"tf.Tensor\":\n \"\"\"\n Provide a differentiable estimate of the forward function, so that autograd can calculate gradients\n of the defence for the backward pass. If the defence is differentiable, just call `self.forward()`.\n If the defence is not differentiable and a differentiable estimate is not available, replace with\n an identity function.\n\n :param x: Dataset to be preprocessed.\n :param y: Labels to be preprocessed.\n :return: Preprocessed data.\n \"\"\"\n return self.forward(x, y=y)[0]\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply preprocessing to input `x` and labels `y`.\n\n :param x: Sample to smooth with shape `(batch_size, width, height, depth)`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Smoothed sample.\n \"\"\"\n import tensorflow as tf\n\n x_tensor = tf.convert_to_tensor(x)\n if y is not None:\n y = tf.convert_to_tensor(y)\n\n x_tensor, y = self.forward(x_tensor, y)\n\n x_result = x_tensor.numpy()\n if y is not None:\n y = y.numpy()\n return x_result, y\n\n # Backward compatibility.\n def estimate_gradient(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n import tensorflow as tf\n\n def get_gradient(x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Helper function for estimate_gradient\n \"\"\"\n\n with tf.GradientTape() as tape:\n x = tf.convert_to_tensor(x, dtype=config.ART_NUMPY_DTYPE)\n tape.watch(x)\n grad = tf.convert_to_tensor(grad, dtype=config.ART_NUMPY_DTYPE)\n\n x_prime = self.estimate_forward(x)\n\n x_grad = tape.gradient(target=x_prime, sources=x, output_gradients=grad)\n\n x_grad = x_grad.numpy()\n if x_grad.shape != x.shape:\n raise ValueError(f\"The input shape is {x.shape} while the gradient shape is {x_grad.shape}\")\n\n return x_grad\n\n if x.dtype == object:\n x_grad_list = []\n for i, x_i in enumerate(x):\n x_grad_list.append(get_gradient(x=x_i, grad=grad[i]))\n x_grad = np.empty(x.shape[0], dtype=object)\n x_grad[:] = list(x_grad_list)\n elif x.shape == grad.shape:\n x_grad = get_gradient(x=x, grad=grad)\n else:\n # Special case for loss gradients\n x_grad = np.zeros_like(grad)\n for i in range(grad.shape[1]):\n x_grad[:, i, ...] = get_gradient(x=x, grad=grad[:, i, ...])\n\n return x_grad\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/resample.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the resampling defence `Resample`.\n\n| Paper link: https://arxiv.org/abs/1809.10875\n\n| Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass Resample(Preprocessor):\n \"\"\"\n Implement the resampling defense approach.\n\n Resampling implicitly consists of a step that applies a low-pass filter. The underlying filter in this\n implementation is a Windowed Sinc Interpolation function.\n \"\"\"\n\n params = [\"sr_original\", \"sr_new\", \"channels_first\"]\n\n def __init__(\n self,\n sr_original: int,\n sr_new: int,\n channels_first: bool = False,\n apply_fit: bool = False,\n apply_predict: bool = True,\n ):\n \"\"\"\n Create an instance of the resample preprocessor.\n\n :param sr_original: Original sampling rate of sample.\n :param sr_new: New sampling rate of sample.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.sr_original = sr_original\n self.sr_new = sr_new\n self.channels_first = channels_first\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Resample `x` to a new sampling rate.\n\n :param x: Sample to resample of shape `(batch_size, length, channel)` or `(batch_size, channel, length)`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Resampled audio sample.\n \"\"\"\n import resampy\n\n if x.ndim != 3:\n raise ValueError(\"Resampling can only be applied to temporal data across at least one channel.\")\n\n sample_index = 2 if self.channels_first else 1\n\n return resampy.resample(x, self.sr_original, self.sr_new, axis=sample_index, filter=\"sinc_window\"), y\n\n def _check_params(self) -> None:\n if not (isinstance(self.sr_original, int) and self.sr_original > 0):\n raise ValueError(\"Original sampling rate be must a positive integer.\")\n\n if not (isinstance(self.sr_new, int) and self.sr_new > 0):\n raise ValueError(\"New sampling rate be must a positive integer.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/spatial_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the local spatial smoothing defence in `SpatialSmoothing`.\n\n| Paper link: https://arxiv.org/abs/1704.01155\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom scipy.ndimage import median_filter\n\nfrom art.utils import CLIP_VALUES_TYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpatialSmoothing(Preprocessor):\n \"\"\"\n Implement the local spatial smoothing defence approach.\n\n | Paper link: https://arxiv.org/abs/1704.01155\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"window_size\", \"channels_first\", \"clip_values\"]\n\n def __init__(\n self,\n window_size: int = 3,\n channels_first: bool = False,\n clip_values: CLIP_VALUES_TYPE | None = None,\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of local spatial smoothing.\n\n :param channels_first: Set channels first or last.\n :param window_size: The size of the sliding window.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n\n self.channels_first = channels_first\n self.window_size = window_size\n self.clip_values = clip_values\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply local spatial smoothing to sample `x`.\n\n :param x: Sample to smooth with shape `(batch_size, width, height, depth)`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Smoothed sample.\n \"\"\"\n x_ndim = x.ndim\n if x_ndim not in [4, 5]:\n raise ValueError(\n \"Unrecognized input dimension. Spatial smoothing can only be applied to image and video data.\"\n )\n\n # get channel index\n channel_index = 1 if self.channels_first else x_ndim - 1\n\n filter_size = [self.window_size] * x_ndim\n # set filter_size at batch and channel indices to 1\n filter_size[0] = 1\n filter_size[channel_index] = 1\n # set filter_size at temporal index to 1\n if x_ndim == 5:\n # check if NCFHW or NFHWC\n temporal_index = 2 if self.channels_first else 1\n filter_size[temporal_index] = 1\n # Note median_filter:\n # * center pixel located lower right\n # * if window size even, use larger value (e.g. median(4,5)=5)\n result = median_filter(x, size=tuple(filter_size), mode=\"reflect\")\n\n if self.clip_values is not None:\n np.clip(result, self.clip_values[0], self.clip_values[1], out=result)\n\n return result, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.window_size, int) and self.window_size > 0):\n raise ValueError(\"Sliding window size must be a positive integer.\")\n\n if self.clip_values is not None and len(self.clip_values) != 2:\n raise ValueError(\"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\")\n\n if self.clip_values is not None and np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid 'clip_values': min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/spatial_smoothing_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the local spatial smoothing defence in `SpatialSmoothing` in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1704.01155\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpatialSmoothingPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement the local spatial smoothing defence approach in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1704.01155\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n def __init__(\n self,\n window_size: int = 3,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = False,\n apply_predict: bool = True,\n device_type: str = \"gpu\",\n ) -> None:\n \"\"\"\n Create an instance of local spatial smoothing.\n\n :param window_size: Size of spatial smoothing window.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n\n super().__init__(\n device_type=device_type,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n\n self.channels_first = channels_first\n self.window_size = window_size\n self.clip_values = clip_values\n self._check_params()\n\n from kornia.filters import MedianBlur\n\n class MedianBlurCustom(MedianBlur):\n \"\"\"\n An ongoing effort to reproduce the median blur function in SciPy.\n \"\"\"\n\n def __init__(self, kernel_size: tuple[int, int]) -> None:\n super().__init__(kernel_size)\n\n # Half-pad the input so that the output keeps the same shape.\n # * center pixel located lower right\n half_pad = [int(k % 2 == 0) for k in kernel_size]\n if hasattr(self, \"padding\"):\n # kornia < 0.5.0\n padding = self.padding\n else:\n # kornia >= 0.5.0\n from kornia.filters.median import _compute_zero_padding\n\n padding = _compute_zero_padding(kernel_size) # type: ignore\n self.p2d = [\n int(padding[-1]) + half_pad[-1], # type: ignore\n int(padding[-1]), # type: ignore\n int(padding[-2]) + half_pad[-2], # type: ignore\n int(padding[-2]), # type: ignore\n ]\n # PyTorch requires padding size should be less than the corresponding input dimension.\n\n if not hasattr(self, \"kernel\"):\n # kornia >= 0.5.0\n from kornia.filters.kernels import get_binary_kernel2d\n\n self.kernel = get_binary_kernel2d(kernel_size)\n\n # pylint: disable=redefined-builtin\n def forward(self, input: \"torch.Tensor\"): # type: ignore\n import torch\n import torch.nn.functional as F\n\n if not torch.is_tensor(input):\n raise TypeError(f\"Input type is not a torch.Tensor. Got {type(input)}\")\n if not len(input.shape) == 4:\n raise ValueError(f\"Invalid input shape, we expect BxCxHxW. Got: {input.shape}\")\n # prepare kernel\n batch_size, channels, height, width = input.shape\n kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype)\n # map the local window to single vector\n\n _input = input.reshape(batch_size * channels, 1, height, width)\n if input.dtype == torch.int64:\n # \"reflection_pad2d\" not implemented for 'Long'\n # \"reflect\" in scipy.ndimage.median_filter has no equivalence in F.pad.\n # \"reflect\" in PyTorch maps to \"mirror\" in scipy.ndimage.median_filter.\n _input = _input.to(torch.float32)\n _input = F.pad(_input, self.p2d, \"reflect\")\n _input = _input.to(torch.int64)\n else:\n _input = F.pad(_input, self.p2d, \"reflect\")\n\n features: torch.Tensor = F.conv2d(_input, kernel, stride=1)\n features = features.view(batch_size, channels, -1, height, width) # BxCx(K_h * K_w)xHxW\n\n # compute the median along the feature axis\n # * torch.median(), if window size even, use smaller value (e.g. median(4,5)=4)\n median: torch.Tensor = torch.median(features, dim=2)[0]\n return median\n\n self.median_blur = MedianBlurCustom(kernel_size=(self.window_size, self.window_size))\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply local spatial smoothing to sample `x`.\n \"\"\"\n import torch\n\n x_ndim = x.ndim\n\n # NHWC/NCFHW/NFHWC --> NCHW.\n if x_ndim == 4:\n if self.channels_first:\n x_nchw = x\n else:\n # NHWC --> NCHW\n x_nchw = x.permute(0, 3, 1, 2)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW --> NFCHW --> NCHW\n nb_clips, channels, clip_size, height, width = x.shape\n x_nchw = x.permute(0, 2, 1, 3, 4).reshape(nb_clips * clip_size, channels, height, width)\n else:\n # NFHWC --> NHWC --> NCHW\n nb_clips, clip_size, height, width, channels = x.shape\n x_nchw = x.reshape(nb_clips * clip_size, height, width, channels).permute(0, 3, 1, 2)\n else:\n raise ValueError(\n \"Unrecognized input dimension. Spatial smoothing can only be applied to image and video data.\"\n )\n\n x_nchw = self.median_blur(x_nchw)\n\n # NHWC/NCFHW/NFHWC <-- NCHW.\n if x_ndim == 4:\n if self.channels_first:\n x = x_nchw\n else:\n # NHWC <-- NCHW\n x = x_nchw.permute(0, 2, 3, 1)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW <-- NFCHW <-- NCHW\n x_nfchw = x_nchw.reshape(nb_clips, clip_size, channels, height, width)\n x = x_nfchw.permute(0, 2, 1, 3, 4)\n else:\n # NFHWC <-- NHWC <-- NCHW\n x_nhwc = x_nchw.permute(0, 2, 3, 1)\n x = x_nhwc.reshape(nb_clips, clip_size, height, width, channels)\n\n if self.clip_values is not None:\n x = x.clamp(min=torch.tensor(self.clip_values[0]), max=torch.tensor(self.clip_values[1]))\n\n return x, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.window_size, int) and self.window_size > 0):\n raise ValueError(\"Sliding window size must be a positive integer.\")\n\n if self.clip_values is not None and len(self.clip_values) != 2:\n raise ValueError(\"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\")\n\n if self.clip_values is not None and np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid 'clip_values': min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/spatial_smoothing_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the local spatial smoothing defence in `SpatialSmoothing` in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1704.01155\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpatialSmoothingTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n Implement the local spatial smoothing defence approach in TensorFlow v2.\n\n | Paper link: https://arxiv.org/abs/1704.01155\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n def __init__(\n self,\n window_size: int = 3,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of local spatial smoothing.\n\n :param window_size: Size of spatial smoothing window.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(apply_fit=apply_fit, apply_predict=apply_predict)\n\n self.channels_first = channels_first\n self.window_size = window_size\n self.clip_values = clip_values\n self._check_params()\n\n def forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Apply local spatial smoothing to sample `x`.\n \"\"\"\n import tensorflow as tf\n\n x_ndim = x.ndim\n\n if x_ndim == 4:\n x_nhwc = x\n elif x_ndim == 5:\n # NFHWC --> NHWC\n nb_clips, clip_size, height, width, channels = x.shape\n x_nhwc = tf.reshape(x, (nb_clips * clip_size, height, width, channels))\n else:\n raise ValueError(\n \"Unrecognized input dimension. Spatial smoothing can only be applied to image (NHWC) and video (NFHWC) \"\n \"data.\"\n )\n\n x_nhwc = median_filter2d(x=x_nhwc, filter_size=self.window_size, padding=\"REFLECT\")\n\n if x_ndim == 4:\n x = x_nhwc\n elif x_ndim == 5:\n # NFHWC <-- NHWC\n x = tf.reshape(x_nhwc, (nb_clips, clip_size, height, width, channels))\n\n if self.clip_values is not None:\n x = x.clip_by_value(min=self.clip_values[0], max=self.clip_values[1])\n\n return x, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.window_size, int) and self.window_size > 0):\n raise ValueError(\"Sliding window size must be a positive integer.\")\n\n if self.clip_values is not None and len(self.clip_values) != 2:\n raise ValueError(\"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\")\n\n if self.clip_values is not None and np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid 'clip_values': min >= max.\")\n\n if self.channels_first:\n raise ValueError(\"Only channels last input data is supported (`channels_first=False`)\")\n\n\ndef median_filter2d(x, filter_size=3, padding=\"REFLECT\"):\n \"\"\"\n Applies a 2D median filter to a 4D tensor.\n\n :param x: A 4D tensor of shape [batch, height, width, channels].\n :param filter_size: An odd integer specifying the size of the median filter window.\n :param padding: A string, either 'REFLECT' or 'CONSTANT', specifying the padding method.\n :return: A 4D tensor of the same shape as x, with the median filter applied.\n \"\"\"\n import tensorflow as tf\n\n if filter_size % 2 == 0:\n raise ValueError(\"filter_size must be an odd integer.\")\n\n pad_total = filter_size // 2\n if padding == \"REFLECT\":\n x_padded = tf.pad(x, [[0, 0], [pad_total, pad_total], [pad_total, pad_total], [0, 0]], mode=\"REFLECT\")\n elif padding == \"CONSTANT\":\n x_padded = tf.pad(x, [[0, 0], [pad_total, pad_total], [pad_total, pad_total], [0, 0]], mode=\"CONSTANT\")\n else:\n raise ValueError(\"Unsupported padding type. Use 'REFLECT' or 'CONSTANT'.\")\n\n patches = tf.image.extract_patches(\n images=x_padded,\n sizes=[1, filter_size, filter_size, 1],\n strides=[1, 1, 1, 1],\n rates=[1, 1, 1, 1],\n padding=\"VALID\",\n )\n\n k = filter_size * filter_size\n patches_reshaped = tf.reshape(patches, [-1, tf.shape(x)[1], tf.shape(x)[2], k, tf.shape(x)[3]])\n\n # Sort the patches along the k dimension (filter window)\n sorted_patches = tf.sort(patches_reshaped, axis=3)\n\n # Pick the median index\n median_idx = k // 2\n median = sorted_patches[:, :, :, median_idx, :]\n\n return median\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/thermometer_encoding.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the thermometer encoding defence `ThermometerEncoding`.\n\n| Paper link: https://openreview.net/forum?id=S18Su--CW\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\nfrom art.utils import to_categorical\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ThermometerEncoding(Preprocessor):\n \"\"\"\n Implement the thermometer encoding defence approach.\n\n | Paper link: https://openreview.net/forum?id=S18Su--CW\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"clip_values\", \"num_space\", \"channels_first\"]\n\n def __init__(\n self,\n clip_values: \"CLIP_VALUES_TYPE\",\n num_space: int = 10,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of thermometer encoding.\n\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param num_space: Number of evenly spaced levels within the interval of minimum and maximum clip values.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.clip_values = clip_values\n self.num_space = num_space\n self.channels_first = channels_first\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply thermometer encoding to sample `x`. The new axis with the encoding is added as last dimension.\n\n :param x: Sample to encode with shape `(batch_size, width, height, depth)`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Encoded sample with shape `(batch_size, width, height, depth x num_space)`.\n \"\"\"\n # First normalize the input to be in [0, 1]:\n np.clip(x, self.clip_values[0], self.clip_values[1], out=x)\n x = (x - self.clip_values[0]) / (self.clip_values[1] - self.clip_values[0])\n\n # Now apply the encoding:\n channel_index = 1 if self.channels_first else x.ndim - 1\n result = np.apply_along_axis(self._perchannel, channel_index, x)\n np.clip(result, 0, 1, out=result)\n return result.astype(ART_NUMPY_DTYPE), y\n\n def _perchannel(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply thermometer encoding to one channel.\n\n :param x: Sample to encode with shape `(batch_size, width, height)`.\n :return: Encoded sample with shape `(batch_size, width, height, num_space)`.\n \"\"\"\n pos = np.zeros(shape=x.shape)\n for i in range(1, self.num_space):\n pos[x > float(i) / self.num_space] += 1\n\n onehot_rep = to_categorical(pos.reshape(-1), self.num_space)\n\n for i in range(self.num_space - 1):\n onehot_rep[:, i] += np.sum(onehot_rep[:, i + 1 :], axis=1)\n\n return onehot_rep.flatten()\n\n def estimate_gradient(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Provide an estimate of the gradients of the defence for the backward pass. For thermometer encoding,\n the gradient estimate is the one used in https://arxiv.org/abs/1802.00420, where the thermometer encoding\n is replaced with a differentiable approximation:\n `g(x_{i,j,c})_k = min(max(x_{i,j,c} - k / self.num_space, 0), 1)`.\n\n :param x: Input data for which the gradient is estimated. First dimension is the batch size.\n :param grad: Gradient value so far.\n :return: The gradient (estimate) of the defence.\n \"\"\"\n if self.channels_first:\n x = np.transpose(x, (0,) + tuple(range(2, len(x.shape))) + (1,))\n grad = np.transpose(grad, (0,) + tuple(range(2, len(x.shape))) + (1,))\n\n thermometer_grad = np.zeros(x.shape[:-1] + (x.shape[-1] * self.num_space,))\n mask = np.array([x > k / self.num_space for k in range(self.num_space)])\n mask = np.moveaxis(mask, 0, -1)\n mask = mask.reshape(thermometer_grad.shape)\n thermometer_grad[mask] = 1\n\n grad = grad * thermometer_grad\n grad = np.reshape(grad, grad.shape[:-1] + (grad.shape[-1] // self.num_space, self.num_space))\n grad = np.sum(grad, -1)\n\n if self.channels_first:\n x = np.transpose(x, (0,) + (len(x.shape) - 1,) + tuple(range(1, len(x.shape) - 1)))\n grad = np.transpose(grad, (0,) + (len(x.shape) - 1,) + tuple(range(1, len(x.shape) - 1)))\n\n return grad / (self.clip_values[1] - self.clip_values[0])\n\n def _check_params(self) -> None:\n if not isinstance(self.num_space, int) or self.num_space <= 0:\n logger.error(\"Number of evenly spaced levels must be a positive integer.\")\n raise ValueError(\"Number of evenly spaced levels must be a positive integer.\")\n\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"first entry of `clip_values` should be strictly smaller than the second one.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/variance_minimization.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the total variance minimization defence `TotalVarMin`.\n\n| Paper link: https://openreview.net/forum?id=SyJ7ClWCb\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass TotalVarMin(Preprocessor):\n \"\"\"\n Implement the total variance minimization defence approach.\n\n | Paper link: https://openreview.net/forum?id=SyJ7ClWCb\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this\n defence, see https://arxiv.org/abs/1802.00420 . For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"prob\", \"norm\", \"lamb\", \"solver\", \"max_iter\", \"clip_values\", \"verbose\"]\n\n def __init__(\n self,\n prob: float = 0.3,\n norm: int = 2,\n lamb: float = 0.5,\n solver: str = \"L-BFGS-B\",\n max_iter: int = 10,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = False,\n apply_predict: bool = True,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of total variance minimization.\n\n :param prob: Probability of the Bernoulli distribution.\n :param norm: The norm (positive integer).\n :param lamb: The lambda parameter in the objective function.\n :param solver: Current support: `L-BFGS-B`, `CG`, `Newton-CG`.\n :param max_iter: Maximum number of iterations when performing optimization.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.prob = prob\n self.norm = norm\n self.lamb = lamb\n self.solver = solver\n self.max_iter = max_iter\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply total variance minimization to sample `x`.\n\n :param x: Sample to compress with shape `(batch_size, width, height, depth)`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Similar samples.\n \"\"\"\n if len(x.shape) == 2:\n raise ValueError(\n \"Feature vectors detected. Variance minimization can only be applied to data with spatial dimensions.\"\n )\n x_preproc = x.copy()\n\n # Minimize one input at a time\n for i, x_i in enumerate(tqdm(x_preproc, desc=\"Variance minimization\", disable=not self.verbose)):\n mask = (np.random.rand(*x_i.shape) < self.prob).astype(\"int\")\n x_preproc[i] = self._minimize(x_i, mask)\n\n if self.clip_values is not None:\n np.clip(x_preproc, self.clip_values[0], self.clip_values[1], out=x_preproc)\n\n return x_preproc.astype(ART_NUMPY_DTYPE), y\n\n def _minimize(self, x: np.ndarray, mask: np.ndarray) -> np.ndarray:\n \"\"\"\n Minimize the total variance objective function.\n\n :param x: Original image.\n :param mask: A matrix that decides which points are kept.\n :return: A new image.\n \"\"\"\n z_min = x.copy()\n\n for i in range(x.shape[2]):\n res = minimize(\n self._loss_func,\n z_min[:, :, i].flatten(),\n (x[:, :, i], mask[:, :, i], self.norm, self.lamb),\n method=self.solver,\n jac=self._deri_loss_func,\n options={\"maxiter\": self.max_iter},\n )\n z_min[:, :, i] = np.reshape(res.x, z_min[:, :, i].shape)\n\n return z_min\n\n @staticmethod\n def _loss_func(z_init: np.ndarray, x: np.ndarray, mask: np.ndarray, norm: int, lamb: float) -> float:\n \"\"\"\n Loss function to be minimized.\n\n :param z_init: Initial guess.\n :param x: Original image.\n :param mask: A matrix that decides which points are kept.\n :param norm: The norm (positive integer).\n :param lamb: The lambda parameter in the objective function.\n :return: Loss value.\n \"\"\"\n res = np.sqrt(np.power(z_init - x.flatten(), 2).dot(mask.flatten()))\n z_init = np.reshape(z_init, x.shape)\n res += lamb * np.linalg.norm(z_init[1:, :] - z_init[:-1, :], norm, axis=1).sum()\n res += lamb * np.linalg.norm(z_init[:, 1:] - z_init[:, :-1], norm, axis=0).sum()\n\n return res\n\n @staticmethod\n def _deri_loss_func(z_init: np.ndarray, x: np.ndarray, mask: np.ndarray, norm: int, lamb: float) -> float:\n \"\"\"\n Derivative of loss function to be minimized.\n\n :param z_init: Initial guess.\n :param x: Original image.\n :param mask: A matrix that decides which points are kept.\n :param norm: The norm (positive integer).\n :param lamb: The lambda parameter in the objective function.\n :return: Derivative value.\n \"\"\"\n # First compute the derivative of the first component of the loss function\n nor1 = np.sqrt(np.power(z_init - x.flatten(), 2).dot(mask.flatten()))\n nor1 = max(nor1, 1e-06)\n der1 = ((z_init - x.flatten()) * mask.flatten()) / (nor1 * 1.0)\n\n # Then compute the derivative of the second component of the loss function\n z_init = np.reshape(z_init, x.shape)\n\n if norm == 1:\n z_d1 = np.sign(z_init[1:, :] - z_init[:-1, :])\n z_d2 = np.sign(z_init[:, 1:] - z_init[:, :-1])\n else:\n z_d1_norm = np.power(np.linalg.norm(z_init[1:, :] - z_init[:-1, :], norm, axis=1), norm - 1)\n z_d2_norm = np.power(np.linalg.norm(z_init[:, 1:] - z_init[:, :-1], norm, axis=0), norm - 1)\n z_d1_norm[z_d1_norm < 1e-6] = 1e-6\n z_d2_norm[z_d2_norm < 1e-6] = 1e-6\n z_d1_norm = np.repeat(z_d1_norm[:, np.newaxis], z_init.shape[1], axis=1)\n z_d2_norm = np.repeat(z_d2_norm[np.newaxis, :], z_init.shape[0], axis=0)\n z_d1 = norm * np.power(z_init[1:, :] - z_init[:-1, :], norm - 1) / z_d1_norm\n z_d2 = norm * np.power(z_init[:, 1:] - z_init[:, :-1], norm - 1) / z_d2_norm\n\n der2 = np.zeros(z_init.shape)\n der2[:-1, :] -= z_d1\n der2[1:, :] += z_d1\n der2[:, :-1] -= z_d2\n der2[:, 1:] += z_d2\n der2 = lamb * der2.flatten()\n\n # Total derivative\n return der1 + der2\n\n def _check_params(self) -> None:\n if not isinstance(self.prob, (float, int)) or self.prob < 0.0 or self.prob > 1.0:\n logger.error(\"Probability must be between 0 and 1.\")\n raise ValueError(\"Probability must be between 0 and 1.\")\n\n if not isinstance(self.norm, int) or self.norm <= 0:\n logger.error(\"Norm must be a positive integer.\")\n raise ValueError(\"Norm must be a positive integer.\")\n\n if self.solver not in (\"L-BFGS-B\", \"CG\", \"Newton-CG\"):\n logger.error(\"Current support only L-BFGS-B, CG, Newton-CG.\")\n raise ValueError(\"Current support only L-BFGS-B, CG, Newton-CG.\")\n\n if not isinstance(self.max_iter, int) or self.max_iter <= 0:\n logger.error(\"Number of iterations must be a positive integer.\")\n raise ValueError(\"Number of iterations must be a positive integer.\")\n\n if self.clip_values is not None:\n\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/video_compression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a wrapper for video compression defence with FFmpeg.\n\n| Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport os\nfrom tempfile import TemporaryDirectory\n\nimport warnings\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art import config\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass VideoCompression(Preprocessor):\n \"\"\"\n Implement FFmpeg wrapper for video compression defence based on H.264/MPEG-4 AVC.\n\n Video compression uses H.264 video encoding. The video quality is controlled with the constant rate factor\n parameter. More information on the constant rate factor: https://trac.ffmpeg.org/wiki/Encode/H.264.\n \"\"\"\n\n params = [\"video_format\", \"constant_rate_factor\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n *,\n video_format: str,\n constant_rate_factor: int = 28,\n channels_first: bool = False,\n apply_fit: bool = False,\n apply_predict: bool = True,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of VideoCompression.\n\n :param video_format: Specify one of supported video file extensions, e.g. `avi`, `mp4` or `mkv`.\n :param constant_rate_factor: Specify constant rate factor (range 0 to 51, where 0 is lossless).\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.video_format = video_format\n self.constant_rate_factor = constant_rate_factor\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply video compression to sample `x`.\n\n :param x: Sample to compress of shape NCFHW or NFHWC. `x` values are expected to be either in range [0, 1] or\n [0, 255].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Compressed sample.\n \"\"\"\n\n def compress_video(x: np.ndarray, video_format: str, constant_rate_factor: int, dir_: str = \"\"):\n \"\"\"\n Apply video compression to video input of shape (frames, height, width, channel).\n \"\"\"\n import ffmpeg\n\n video_path = os.path.join(dir_, f\"tmp_video.{video_format}\")\n _, height, width, _ = x.shape\n\n if (height % 2) != 0 or (width % 2) != 0:\n warnings.warn(\"Codec might require even number of pixels in height and width.\")\n\n # numpy to local video file\n process = (\n ffmpeg.input(\"pipe:\", format=\"rawvideo\", pix_fmt=\"rgb24\", s=f\"{width}x{height}\")\n .output(video_path, pix_fmt=\"yuv420p\", vcodec=\"libx264\", crf=constant_rate_factor)\n .overwrite_output()\n .run_async(pipe_stdin=True, quiet=True)\n )\n process.stdin.write(x.flatten().astype(np.uint8).tobytes())\n process.stdin.close()\n process.wait()\n\n # local video file to numpy\n stdout, _ = (\n ffmpeg.input(video_path)\n .output(\"pipe:\", format=\"rawvideo\", pix_fmt=\"rgb24\")\n .run(capture_stdout=True, quiet=True)\n )\n return np.frombuffer(stdout, np.uint8).reshape(x.shape)\n\n if x.ndim != 5:\n raise ValueError(\"Video compression can only be applied to spatio-temporal data.\")\n\n if self.channels_first:\n x = np.transpose(x, (0, 2, 3, 4, 1))\n\n # apply video compression per video item\n scale = 1\n if x.min() >= 0 and x.max() <= 1.0:\n scale = 255\n\n x_compressed = x.copy()\n with TemporaryDirectory(dir=config.ART_DATA_PATH) as tmp_dir:\n for i, x_i in enumerate(tqdm(x, desc=\"Video compression\", disable=not self.verbose)):\n x_i *= scale\n x_compressed[i] = compress_video(x_i, self.video_format, self.constant_rate_factor, dir_=tmp_dir)\n\n x_compressed = x_compressed / scale\n x_compressed = x_compressed.astype(x.dtype)\n\n if self.channels_first:\n x_compressed = np.transpose(x_compressed, (0, 4, 1, 2, 3))\n\n return x_compressed, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.constant_rate_factor, int) and 0 <= self.constant_rate_factor < 52):\n raise ValueError(\"Constant rate factor must be an integer in the range [0, 51].\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/video_compression_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a wrapper for video compression defence with FFmpeg.\n\n| Please keep in mind the limitations of defences. For details on how to evaluate classifier security in general,\n see https://arxiv.org/abs/1902.06705.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\nfrom art.defences.preprocessor.video_compression import VideoCompression\n\nlogger = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n\n import torch\n\n\nclass VideoCompressionPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement FFmpeg wrapper for video compression defence based on H.264/MPEG-4 AVC.\n\n Video compression uses H.264 video encoding. The video quality is controlled with the constant rate factor\n parameter. More information on the constant rate factor: https://trac.ffmpeg.org/wiki/Encode/H.264.\n \"\"\"\n\n params = [\"video_format\", \"constant_rate_factor\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n *,\n video_format: str,\n constant_rate_factor: int = 28,\n channels_first: bool = False,\n apply_fit: bool = False,\n apply_predict: bool = True,\n device_type: str = \"gpu\",\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of VideoCompression.\n\n :param video_format: Specify one of supported video file extensions, e.g. `avi`, `mp4` or `mkv`.\n :param constant_rate_factor: Specify constant rate factor (range 0 to 51, where 0 is lossless).\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param verbose: Show progress bars.\n \"\"\"\n from torch.autograd import Function\n\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n self.video_format = video_format\n self.constant_rate_factor = constant_rate_factor\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n self.compression_numpy = VideoCompression(\n video_format=video_format,\n constant_rate_factor=constant_rate_factor,\n channels_first=channels_first,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n verbose=verbose,\n )\n\n class CompressionPyTorchNumpy(Function): # pylint: disable=abstract-method\n \"\"\"\n Function running Preprocessor.\n \"\"\"\n\n @staticmethod\n def forward(ctx, input): # pylint: disable=redefined-builtin,arguments-differ\n numpy_input = input.detach().cpu().numpy()\n result, _ = self.compression_numpy(numpy_input)\n return input.new(result)\n\n @staticmethod\n def backward(ctx, grad_output):\n numpy_go = grad_output.cpu().numpy()\n result = self.compression_numpy.estimate_gradient(None, numpy_go)\n return grad_output.new(result)\n\n self._compression_pytorch_numpy = CompressionPyTorchNumpy\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply video compression to sample `x`.\n\n :param x: Sample to compress of shape NCFHW or NFHWC. `x` values are expected to be either in range [0, 1] or\n [0, 255].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Compressed sample.\n \"\"\"\n scale = 1\n if x.min() >= 0 and x.max() <= 1.0:\n scale = 255\n x = x * scale\n x_compressed = self._compression_pytorch_numpy.apply(x)\n x_compressed = x_compressed / scale\n return x_compressed, y\n\n def _check_params(self) -> None:\n if not (isinstance(self.constant_rate_factor, int) and 0 <= self.constant_rate_factor < 52):\n raise ValueError(\"Constant rate factor must be an integer in the range [0, 51].\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/cutmix/cutmix.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the CutMix data augmentation defence.\n\n| Paper link: https://arxiv.org/abs/1905.04899\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.defences.preprocessor.preprocessor import Preprocessor\nfrom art.utils import to_categorical\n\nlogger = logging.getLogger(__name__)\n\n\nclass CutMix(Preprocessor):\n \"\"\"\n Implement the CutMix data augmentation defence approach.\n\n | Paper link: https://arxiv.org/abs/1905.04899\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"num_classes\", \"alpha\", \"probability\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n num_classes: int,\n alpha: float = 1.0,\n probability: float = 0.5,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of a CutMix data augmentation object.\n\n :param num_classes: The number of classes used for one-hot encoding.\n :param alpha: The hyperparameter for sampling the combination ratio.\n :param probability: The probability of applying CutMix per sample.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.num_classes = num_classes\n self.alpha = alpha\n self.probability = probability\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply CutMix data augmentation to sample `x`.\n\n :param x: Sample to augment with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`.\n :param y: Labels of `x` either one-hot or multi-hot encoded of shape `(nb_samples, nb_classes)`\n or class indices of shape `(nb_samples,)`.\n :return: Data augmented sample. The returned labels will be probability vectors of shape\n `(nb_samples, nb_classes)`.\n \"\"\"\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n # convert labels to one-hot encoding\n if len(y.shape) == 2:\n y_one_hot = y\n elif len(y.shape) == 1:\n y_one_hot = to_categorical(y, self.num_classes)\n else:\n raise ValueError(\n \"Shape of labels not recognised. \"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, nb_classes)\"\n )\n\n x_ndim = len(x.shape)\n\n # NCHW/NHWC/NCFHW --> NFHWC\n if x_ndim == 4:\n if self.channels_first:\n # NCHW --> NHWC --> NFHWC\n x_nhwc = np.transpose(x, (0, 2, 3, 1))\n x_nfhwc = np.expand_dims(x_nhwc, axis=1)\n else:\n # NHWC --> NFHWC\n x_nfhwc = np.expand_dims(x, axis=1)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW --> NFHWC\n x_nfhwc = np.transpose(x, (0, 2, 3, 4, 1))\n else:\n # NFHWC\n x_nfhwc = x\n else:\n raise ValueError(\"Unrecognized input dimension. CutMix can only be applied to image and video data.\")\n\n n, _, height, width, _ = x_nfhwc.shape\n x_aug = x_nfhwc.copy()\n y_aug = y_one_hot.copy()\n\n # sample the combination ratio from the Beta distribution\n lmb = np.random.beta(self.alpha, self.alpha)\n cut_ratio = np.sqrt(1.0 - lmb)\n cut_height = int(height * cut_ratio)\n cut_width = int(width * cut_ratio)\n\n # randomly choose indices for samples to mix\n indices = np.random.permutation(n)\n\n # generate a random bounding box per image\n for idx1, idx2 in enumerate(tqdm(indices, desc=\"CutMix\", disable=not self.verbose)):\n prob = np.random.rand()\n if prob < self.probability:\n # uniform sampling\n center_y = np.random.randint(height)\n center_x = np.random.randint(width)\n bby1 = np.clip(center_y - cut_height // 2, 0, height)\n bbx1 = np.clip(center_x - cut_width // 2, 0, width)\n bby2 = np.clip(center_y + cut_height // 2, 0, height)\n bbx2 = np.clip(center_x + cut_width // 2, 0, width)\n\n # insert image bounding box\n x_aug[idx1, :, bbx1:bbx2, bby1:bby2, :] = x_nfhwc[idx2, :, bbx1:bbx2, bby1:bby2, :]\n # mix labels\n y_aug[idx1] = lmb * y_aug[idx1] + (1.0 - lmb) * y_one_hot[idx2]\n\n x_nfhwc = x_aug\n\n # NCHW/NHWC/NCFHW <-- NFHWC\n if x_ndim == 4:\n if self.channels_first:\n # NHWC <-- NCHW <-- NFHWC\n x_nhwc = np.squeeze(x_nfhwc, axis=1)\n x_aug = np.transpose(x_nhwc, (0, 3, 1, 2))\n else:\n # NHWC <-- NFHWC\n x_aug = np.squeeze(x_nfhwc, axis=1)\n elif x_ndim == 5: # lgtm [py/redundant-comparison]\n if self.channels_first:\n # NCFHW <-- NFHWC\n x_aug = np.transpose(x_nfhwc, (0, 4, 1, 2, 3))\n else:\n # NFHWC\n x_aug = x_nfhwc\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.num_classes <= 0:\n raise ValueError(\"The number of classes must be positive\")\n\n if self.alpha <= 0:\n raise ValueError(\"The combination ratio sampling parameter must be positive.\")\n\n if self.probability < 0 or self.probability > 1:\n raise ValueError(\"The CutMix probability must be between 0 and 1.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/cutmix/cutmix_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the CutMix data augmentation defence.\n\n| Paper link: https://arxiv.org/abs/1905.04899\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass CutMixPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement the CutMix data augmentation defence approach in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1905.04899\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"num_classes\", \"alpha\", \"probability\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n num_classes: int,\n alpha: float = 1.0,\n probability: float = 0.5,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = False,\n device_type: str = \"gpu\",\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of a CutMix data augmentation object.\n\n :param num_classes: The number of classes used for one-hot encoding.\n :param alpha: The hyperparameter for sampling the combination ratio.\n :param probability: The probability of applying CutMix per sample.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n self.num_classes = num_classes\n self.alpha = alpha\n self.probability = probability\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply CutMix data augmentation to sample `x`.\n\n :param x: Sample to augment with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`.\n :param y: Labels of `x` either one-hot or multi-hot encoded of shape `(nb_samples, nb_classes)`\n or class indices of shape `(nb_samples,)`.\n :return: Data augmented sample. The returned labels will be probability vectors of shape\n `(nb_samples, nb_classes)`.\n \"\"\"\n import torch\n\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n # convert labels to one-hot encoding\n if len(y.shape) == 2:\n y_one_hot = y\n elif len(y.shape) == 1:\n y_one_hot = torch.nn.functional.one_hot(y, self.num_classes)\n else:\n raise ValueError(\n \"Shape of labels not recognised. \"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, nb_classes)\"\n )\n\n x_ndim = len(x.shape)\n\n # NCHW/NHWC/NFHWC --> NCFHW\n if x_ndim == 4:\n if self.channels_first:\n # NCHW --> NCFHW\n x_ncfhw = torch.unsqueeze(x, dim=2)\n else:\n # NHWC --> NCHW --> NCFHW\n x_nchw = torch.permute(x, (0, 3, 1, 2))\n x_ncfhw = torch.unsqueeze(x_nchw, dim=2)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW\n x_ncfhw = x\n else:\n # NFHWC --> NCFHW\n x_ncfhw = torch.permute(x, (0, 4, 1, 2, 3))\n else:\n raise ValueError(\"Unrecognized input dimension. CutMix can only be applied to image and video data.\")\n\n n, _, _, height, width = x_ncfhw.shape\n x_aug = x_ncfhw.clone()\n y_aug = y_one_hot.clone().float()\n\n # sample the combination ratio from the Beta distribution\n lmb = np.random.beta(self.alpha, self.alpha)\n cut_ratio = np.sqrt(1.0 - lmb)\n cut_height = int(height * cut_ratio)\n cut_width = int(width * cut_ratio)\n\n # randomly choose indices for samples to mix\n indices = torch.randperm(n, device=x.device)\n\n # generate a random bounding box per image\n for idx1, idx2 in enumerate(tqdm(indices, desc=\"CutMix\", disable=not self.verbose)):\n prob = np.random.rand()\n if prob < self.probability:\n # uniform sampling\n center_x = torch.randint(0, height, (1,))\n center_y = torch.randint(0, width, (1,))\n bby1 = torch.clamp(center_y - cut_height // 2, 0, height)\n bbx1 = torch.clamp(center_x - cut_width // 2, 0, width)\n bby2 = torch.clamp(center_y + cut_height // 2, 0, height)\n bbx2 = torch.clamp(center_x + cut_width // 2, 0, width)\n\n # insert image bounding box\n x_aug[idx1, :, :, bbx1:bbx2, bby1:bby2] = x_ncfhw[idx2, :, :, bbx1:bbx2, bby1:bby2] # type: ignore\n # mix labels\n y_aug[idx1] = lmb * y_aug[idx1] + (1.0 - lmb) * y_one_hot[idx2] # type: ignore\n\n x_ncfhw = x_aug\n\n # NCHW/NHWC/NFHWC <-- NCFHW\n if x_ndim == 4:\n if self.channels_first:\n # NCHW <-- NCFHW\n x_aug = torch.squeeze(x_ncfhw, dim=2)\n else:\n # NHWC <-- NCHW <-- NCFHW\n x_nchw = torch.squeeze(x_ncfhw, dim=2)\n x_aug = torch.permute(x_nchw, (0, 2, 3, 1))\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW\n x_aug = x_ncfhw\n else:\n # NFHWC <-- NCFHW\n x_aug = torch.permute(x_ncfhw, (0, 2, 3, 4, 1))\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.num_classes <= 0:\n raise ValueError(\"The number of classes must be positive\")\n\n if self.alpha <= 0:\n raise ValueError(\"The combination ratio sampling parameter must be positive.\")\n\n if self.probability < 0 or self.probability > 1:\n raise ValueError(\"The CutMix probability must be between 0 and 1.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/cutmix/cutmix_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the CutMix data augmentation defence in TensorFlow.\n\n| Paper link: https://arxiv.org/abs/1905.04899\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass CutMixTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n Implement the CutMix data augmentation defence approach in TensorFlow v2.\n\n | Paper link: https://arxiv.org/abs/1905.04899\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"num_classes\", \"alpha\", \"probability\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n num_classes: int,\n alpha: float = 1.0,\n probability: float = 0.5,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of a CutMix data augmentation object.\n\n :param num_classes: The number of classes used for one-hot encoding.\n :param alpha: The hyperparameter for sampling the combination ratio.\n :param probability: The probability of applying CutMix per sample.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.num_classes = num_classes\n self.alpha = alpha\n self.probability = probability\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Apply CutMix data augmentation to sample `x`.\n\n :param x: Sample to augment with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`.\n :param y: Labels of `x` either one-hot or multi-hot encoded of shape `(nb_samples, nb_classes)`\n or class indices of shape `(nb_samples,)`.\n :return: Data augmented sample. The returned labels will be probability vectors of shape\n `(nb_samples, nb_classes)`.\n \"\"\"\n import tensorflow as tf\n\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n # convert labels to one-hot encoding\n if len(y.shape) == 2:\n y_one_hot = y\n elif len(y.shape) == 1:\n y_one_hot = tf.one_hot(y, self.num_classes, on_value=1.0, off_value=0.0)\n else:\n raise ValueError(\n \"Shape of labels not recognised. \"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, nb_classes)\"\n )\n\n x_ndim = len(x.shape)\n\n # NCHW/NHWC/NCFHW --> NFHWC\n if x_ndim == 4:\n if self.channels_first:\n # NCHW --> NHWC --> NFHWC\n x_nhwc = tf.transpose(x, (0, 2, 3, 1))\n x_nfhwc = tf.expand_dims(x_nhwc, axis=1)\n else:\n # NHWC --> NFHWC\n x_nfhwc = tf.expand_dims(x, axis=1)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW --> NFHWC\n x_nfhwc = tf.transpose(x, (0, 2, 3, 4, 1))\n else:\n # NFHWC\n x_nfhwc = x\n else:\n raise ValueError(\"Unrecognized input dimension. CutMix can only be applied to image and video data.\")\n\n n, _, height, width, _ = x_nfhwc.shape\n x_aug = tf.Variable(x_nfhwc, trainable=False)\n y_aug = tf.Variable(y_one_hot, trainable=False)\n\n # sample the combination ratio from the Beta distribution\n lmb = np.random.beta(self.alpha, self.alpha)\n cut_ratio = np.sqrt(1.0 - lmb)\n cut_height = int(height * cut_ratio)\n cut_width = int(width * cut_ratio)\n\n # randomly choose indices for samples to mix\n indices = tf.random.shuffle(tf.range(n))\n\n # generate a random bounding box per image\n for idx1, idx2 in enumerate(tqdm(indices, desc=\"CutMix\", disable=not self.verbose)):\n prob = np.random.rand()\n if prob < self.probability:\n # uniform sampling\n center_y = tf.random.uniform(shape=[], maxval=height, dtype=tf.int32)\n center_x = tf.random.uniform(shape=[], maxval=width, dtype=tf.int32)\n bby1 = tf.clip_by_value(center_y - cut_height // 2, 0, height)\n bbx1 = tf.clip_by_value(center_x - cut_width // 2, 0, width)\n bby2 = tf.clip_by_value(center_y + cut_height // 2, 0, height)\n bbx2 = tf.clip_by_value(center_x + cut_width // 2, 0, width)\n\n # insert image bounding box\n x_aug[idx1, :, bbx1:bbx2, bby1:bby2, :].assign(x_nfhwc[idx2, :, bbx1:bbx2, bby1:bby2, :])\n # mix labels\n y_aug[idx1].assign(lmb * y_aug[idx1] + (1.0 - lmb) * y_one_hot[idx2])\n\n x_nfhwc = tf.convert_to_tensor(x_aug)\n y_aug = tf.convert_to_tensor(y_aug)\n\n # NCHW/NHWC/NCFHW <-- NFHWC\n if x_ndim == 4:\n if self.channels_first:\n # NHWC <-- NCHW <-- NFHWC\n x_nhwc = tf.squeeze(x_nfhwc, axis=1)\n x_aug = tf.transpose(x_nhwc, (0, 3, 1, 2))\n else:\n # NHWC <-- NFHWC\n x_aug = tf.squeeze(x_nfhwc, axis=1)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW <-- NFHWC\n x_aug = tf.transpose(x_nfhwc, (0, 4, 1, 2, 3))\n else:\n # NFHWC\n x_aug = x_nfhwc\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.num_classes <= 0:\n raise ValueError(\"The number of classes must be positive\")\n\n if self.alpha <= 0:\n raise ValueError(\"The combination ratio sampling parameter must be positive.\")\n\n if self.probability < 0 or self.probability > 1:\n raise ValueError(\"The CutMix probability must be between 0 and 1.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/cutout/cutout.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Cutout data augmentation defence.\n\n| Paper link: https://arxiv.org/abs/1708.04552\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.defences.preprocessor.preprocessor import Preprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass Cutout(Preprocessor):\n \"\"\"\n Implement the Cutout data augmentation defence approach.\n\n | Paper link: https://arxiv.org/abs/1708.04552\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"length\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n length: int,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of a Cutout data augmentation object.\n\n :param length: Maximum length of the bounding box.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.length = length\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply Cutout data augmentation to sample `x`.\n\n :param x: Sample to cut out with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`.\n `x` values are expected to be in the data range [0, 1] or [0, 255].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Data augmented sample.\n \"\"\"\n x_ndim = len(x.shape)\n\n # NCHW/NCFHW/NFHWC --> NHWC\n if x_ndim == 4:\n if self.channels_first:\n # NCHW --> NHWC\n x_nhwc = np.transpose(x, (0, 2, 3, 1))\n else:\n # NHWC\n x_nhwc = x\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW --> NFHWC --> NHWC\n nb_clips, channels, clip_size, height, width = x.shape\n x_nfhwc = np.transpose(x, (0, 2, 3, 4, 1))\n x_nhwc = np.reshape(x_nfhwc, (nb_clips * clip_size, height, width, channels))\n else:\n # NFHWC --> NHWC\n nb_clips, clip_size, height, width, channels = x.shape\n x_nhwc = np.reshape(x, (nb_clips * clip_size, height, width, channels))\n else:\n raise ValueError(\"Unrecognized input dimension. Cutout can only be applied to image and video data.\")\n\n n, height, width, _ = x_nhwc.shape\n x_nhwc = x_nhwc.copy()\n\n # generate a random bounding box per image\n for idx in trange(n, desc=\"Cutout\", disable=not self.verbose):\n # uniform sampling\n center_y = np.random.randint(height)\n center_x = np.random.randint(width)\n bby1 = np.clip(center_y - self.length // 2, 0, height)\n bbx1 = np.clip(center_x - self.length // 2, 0, width)\n bby2 = np.clip(center_y + self.length // 2, 0, height)\n bbx2 = np.clip(center_x + self.length // 2, 0, width)\n\n # zero out the bounding box\n x_nhwc[idx, bbx1:bbx2, bby1:bby2, :] = 0\n\n # NCHW/NCFHW/NFHWC <-- NHWC\n if x_ndim == 4:\n if self.channels_first:\n # NHWC <-- NCHW\n x_aug = np.transpose(x_nhwc, (0, 3, 1, 2))\n else:\n # NHWC\n x_aug = x_nhwc\n elif x_ndim == 5: # lgtm [py/redundant-comparison]\n if self.channels_first:\n # NCFHW <-- NFHWC <-- NHWC\n x_nfhwc = np.reshape(x_nhwc, (nb_clips, clip_size, height, width, channels))\n x_aug = np.transpose(x_nfhwc, (0, 4, 1, 2, 3))\n else:\n # NFHWC <-- NHWC\n x_aug = np.reshape(x_nhwc, (nb_clips, clip_size, height, width, channels))\n\n return x_aug, y\n\n def _check_params(self) -> None:\n if self.length <= 0:\n raise ValueError(\"Bounding box length must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/cutout/cutout_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Cutout data augmentation defence in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1708.04552\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import trange\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass CutoutPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement the Cutout data augmentation defence approach in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1708.04552\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"length\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n length: int,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = False,\n device_type: str = \"gpu\",\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of a Cutout data augmentation object.\n\n :param length: Maximum length of the bounding box.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n self.length = length\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply Cutout data augmentation to sample `x`.\n\n :param x: Sample to cut out with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`.\n `x` values are expected to be in the data range [0, 1] or [0, 255].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Data augmented sample.\n \"\"\"\n import torch # lgtm [py/repeated-import]\n\n x_ndim = len(x.shape)\n\n # NHWC/NCFHW/NFHWC --> NCHW.\n if x_ndim == 4:\n if self.channels_first:\n # NCHW\n x_nchw = x\n else:\n # NHWC --> NCHW\n x_nchw = x.permute(0, 3, 1, 2)\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW --> NFCHW --> NCHW\n nb_clips, channels, clip_size, height, width = x.shape\n x_nchw = x.permute(0, 2, 1, 3, 4).reshape(nb_clips * clip_size, channels, height, width)\n else:\n # NFHWC --> NHWC --> NCHW\n nb_clips, clip_size, height, width, channels = x.shape\n x_nchw = x.reshape(nb_clips * clip_size, height, width, channels).permute(0, 3, 1, 2)\n else:\n raise ValueError(\"Unrecognized input dimension. Cutout can only be applied to image and video data.\")\n\n n, _, height, width = x_nchw.shape\n x_nchw = x_nchw.clone()\n\n # generate a random bounding box per image\n for idx in trange(n, desc=\"Cutout\", disable=not self.verbose):\n # uniform sampling\n center_x = torch.randint(0, height, (1,))\n center_y = torch.randint(0, width, (1,))\n bby1 = torch.clamp(center_y - self.length // 2, 0, height)\n bbx1 = torch.clamp(center_x - self.length // 2, 0, width)\n bby2 = torch.clamp(center_y + self.length // 2, 0, height)\n bbx2 = torch.clamp(center_x + self.length // 2, 0, width)\n\n # zero out the bounding box\n x_nchw[idx, :, bbx1:bbx2, bby1:bby2] = 0 # type: ignore\n\n # NHWC/NCFHW/NFHWC <-- NCHW.\n if x_ndim == 4:\n if self.channels_first:\n # NCHW\n x_aug = x_nchw\n else:\n # NHWC <-- NCHW\n x_aug = x_nchw.permute(0, 2, 3, 1)\n elif x_ndim == 5: # lgtm [py/redundant-comparison]\n if self.channels_first:\n # NCFHW <-- NFCHW <-- NCHW\n x_nfchw = x_nchw.reshape(nb_clips, clip_size, channels, height, width)\n x_aug = x_nfchw.permute(0, 2, 1, 3, 4)\n else:\n # NFHWC <-- NHWC <-- NCHW\n x_nhwc = x_nchw.permute(0, 2, 3, 1)\n x_aug = x_nhwc.reshape(nb_clips, clip_size, height, width, channels)\n\n return x_aug, y\n\n def _check_params(self) -> None:\n if self.length <= 0:\n raise ValueError(\"Bounding box length must be positive.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/cutout/cutout_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Cutout data augmentation defence in TensorFlow.\n\n| Paper link: https://arxiv.org/abs/1708.04552\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass CutoutTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n Implement the Cutout data augmentation defence approach in TensorFlow v2.\n\n | Paper link: https://arxiv.org/abs/1708.04552\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"length\", \"channels_first\", \"verbose\"]\n\n def __init__(\n self,\n length: int,\n channels_first: bool = False,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of a Cutout data augmentation object.\n\n :param length: Maximum length of the bounding box.\n :param channels_first: Set channels first or last.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.length = length\n self.channels_first = channels_first\n self.verbose = verbose\n self._check_params()\n\n def forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Apply Cutout data augmentation to sample `x`.\n\n :param x: Sample to cut out with shape of `NCHW`, `NHWC`, `NCFHW` or `NFHWC`.\n `x` values are expected to be in the data range [0, 1] or [0, 255].\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Data augmented sample.\n \"\"\"\n import tensorflow as tf # lgtm [py/repeated-import]\n\n x_ndim = len(x.shape)\n\n # NCHW/NCFHW/NFHWC --> NHWC\n if x_ndim == 4:\n if self.channels_first:\n # NCHW --> NHWC\n x_nhwc = tf.transpose(x, (0, 2, 3, 1))\n else:\n # NHWC\n x_nhwc = x\n elif x_ndim == 5:\n if self.channels_first:\n # NCFHW --> NFHWC --> NHWC\n nb_clips, channels, clip_size, height, width = x.shape\n x_nfhwc = tf.transpose(x, (0, 2, 3, 4, 1))\n x_nhwc = tf.reshape(x_nfhwc, (nb_clips * clip_size, height, width, channels))\n else:\n # NFHWC --> NHWC\n nb_clips, clip_size, height, width, channels = x.shape\n x_nhwc = tf.reshape(x, (nb_clips * clip_size, height, width, channels))\n else:\n raise ValueError(\"Unrecognized input dimension. Cutout can only be applied to image and video data.\")\n\n # round down length to be divisible by 2\n length = self.length if self.length % 2 == 0 else max(self.length - 1, 2)\n\n # apply random cutout\n x_nhwc = random_cutout(x_nhwc, (length, length))\n\n # NCHW/NCFHW/NFHWC <-- NHWC\n if x_ndim == 4:\n if self.channels_first:\n # NHWC <-- NCHW\n x_aug = tf.transpose(x_nhwc, (0, 3, 1, 2))\n else:\n # NHWC\n x_aug = x_nhwc\n elif x_ndim == 5: # lgtm [py/redundant-comparison]\n if self.channels_first:\n # NCFHW <-- NFHWC <-- NHWC\n x_nfhwc = tf.reshape(x_nhwc, (nb_clips, clip_size, height, width, channels))\n x_aug = tf.transpose(x_nfhwc, (0, 4, 1, 2, 3))\n else:\n # NFHWC <-- NHWC\n x_aug = tf.reshape(x_nhwc, (nb_clips, clip_size, height, width, channels))\n\n return x_aug, y\n\n def _check_params(self) -> None:\n if self.length <= 0:\n raise ValueError(\"Bounding box length must be positive.\")\n\n\ndef random_cutout(x_nhwc, mask_size, seed=None):\n \"\"\"\n Transformation of an input image by applying a random cutout mask.\n\n :param x_nhwc: Input samples of shape `(batch_size, height, width, channels)`.\n :param mask_size: A tuple of two integers `(mask_height, mask_width)` specifying the cutout size.\n :param seed: Optional. A tensor of shape `(2,)` for stateless random seed. If `None`, a random seed is generated.\n :return: Samples with the random cutout mask applied, of the same shape as the input.\n \"\"\"\n import tensorflow as tf\n\n batch_size, height, width, channels = tf.unstack(tf.shape(x_nhwc))\n mask_height, mask_width = mask_size\n\n if seed is None:\n seed = tf.random.uniform([2], maxval=10000, dtype=tf.int32)\n\n # Sample top-left corners for cutouts\n top = tf.random.stateless_uniform(\n [batch_size], minval=0, maxval=height - mask_height + 1, seed=seed, dtype=tf.int32\n )\n left = tf.random.stateless_uniform(\n [batch_size], minval=0, maxval=width - mask_width + 1, seed=seed + 1, dtype=tf.int32\n )\n\n # Create masks\n mask = tf.ones([batch_size, height, width, 1], dtype=x_nhwc.dtype)\n\n for i in tf.range(batch_size):\n mask = tf.tensor_scatter_nd_update(\n mask,\n indices=[[i]],\n updates=[\n tf.tensor_scatter_nd_update(\n mask[i],\n indices=tf.reshape(\n tf.stack(\n tf.meshgrid(\n tf.range(top[i], top[i] + mask_height),\n tf.range(left[i], left[i] + mask_width),\n indexing=\"ij\",\n ),\n axis=-1,\n ),\n [-1, 2],\n ),\n updates=tf.zeros([mask_height * mask_width, 1], dtype=x_nhwc.dtype),\n )\n ],\n )\n\n return x_nhwc * mask\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/mixup/mixup.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Mixup data augmentation defence.\n\n| Paper link: https://arxiv.org/abs/1710.09412\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import Preprocessor\nfrom art.utils import to_categorical\n\nlogger = logging.getLogger(__name__)\n\n\nclass Mixup(Preprocessor):\n \"\"\"\n Implement the Mixup data augmentation defence approach.\n\n | Paper link: https://arxiv.org/abs/1710.09412\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"num_classes\", \"alpha\", \"num_mix\"]\n\n def __init__(\n self,\n num_classes: int,\n alpha: float = 1.0,\n num_mix: int = 2,\n apply_fit: bool = True,\n apply_predict: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of a Mixup data augmentation object.\n\n :param num_classes: The number of classes used for one-hot encoding.\n :param alpha: The hyperparameter for the mixing interpolation strength.\n :param num_mix: The number of samples to mix for k-way Mixup.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.num_classes = num_classes\n self.alpha = alpha\n self.num_mix = num_mix\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply Mixup data augmentation to feature data `x` and labels `y`.\n\n :param x: Feature data to augment with shape `(batch_size, ...)`.\n :param y: Labels of `x` either one-hot or multi-hot encoded of shape `(nb_samples, nb_classes)`\n or class indices of shape `(nb_samples,)`.\n :return: Data augmented sample. The returned labels will be probability vectors of shape\n `(nb_samples, nb_classes)`.\n :raises `ValueError`: If no labels are provided.\n \"\"\"\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n # convert labels to one-hot encoding\n if len(y.shape) == 2:\n y_one_hot = y\n elif len(y.shape) == 1:\n y_one_hot = to_categorical(y, self.num_classes)\n else:\n raise ValueError(\n \"Shape of labels not recognised. \"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, nb_classes)\"\n )\n\n n = x.shape[0]\n\n # sample the mixing factor from the Dirichlet distribution\n lmbs = np.random.dirichlet([self.alpha] * self.num_mix)\n\n x_aug = lmbs[0] * x\n y_aug = lmbs[0] * y_one_hot\n for lmb in lmbs[1:]:\n # randomly choose indices for samples to mix\n indices = np.random.permutation(n)\n x_aug = x_aug + lmb * x[indices]\n y_aug = y_aug + lmb * y_one_hot[indices]\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.num_classes <= 0:\n raise ValueError(\"The number of classes must be positive\")\n\n if self.alpha <= 0:\n raise ValueError(\"The mixing interpolation strength must be positive.\")\n\n if self.num_mix < 2:\n raise ValueError(\"The number of samples to mix must be at least 2.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/mixup/mixup_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Mixup data augmentation defence in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1710.09412\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass MixupPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement the Mixup data augmentation defence approach in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1710.09412\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"num_classes\", \"alpha\", \"num_mix\"]\n\n def __init__(\n self,\n num_classes: int,\n alpha: float = 1.0,\n num_mix: int = 2,\n apply_fit: bool = True,\n apply_predict: bool = False,\n device_type: str = \"gpu\",\n ) -> None:\n \"\"\"\n Create an instance of a Mixup data augmentation object.\n\n :param num_classes: The number of classes used for one-hot encoding.\n :param alpha: The hyperparameter for the mixing interpolation strength.\n :param num_mix: The number of samples to mix for k-way Mixup.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n self.num_classes = num_classes\n self.alpha = alpha\n self.num_mix = num_mix\n self._check_params()\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply Mixup data augmentation to feature data `x` and labels `y`.\n\n :param x: Feature data to augment with shape `(batch_size, ...)`.\n :param y: Labels of `x` either one-hot or multi-hot encoded of shape `(nb_samples, nb_classes)`\n or class indices of shape `(nb_samples,)`.\n :return: Data augmented sample. The returned labels will be probability vectors of shape\n `(nb_samples, nb_classes)`.\n :raises `ValueError`: If no labels are provided.\n \"\"\"\n import torch # lgtm [py/repeated-import]\n\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n # convert labels to one-hot encoding\n if len(y.shape) == 2:\n y_one_hot = y\n elif len(y.shape) == 1:\n y_one_hot = torch.nn.functional.one_hot(y, self.num_classes)\n else:\n raise ValueError(\n \"Shape of labels not recognised. \"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, nb_classes)\"\n )\n\n n = x.shape[0]\n\n # sample the mixing factor from the Dirichlet distribution\n lmbs = np.random.dirichlet([self.alpha] * self.num_mix)\n\n x_aug = lmbs[0] * x\n y_aug = lmbs[0] * y_one_hot\n for lmb in lmbs[1:]:\n # randomly choose indices for samples to mix\n indices = torch.randperm(n, device=x.device)\n x_aug = x_aug + lmb * x[indices]\n y_aug = y_aug + lmb * y_one_hot[indices]\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.num_classes <= 0:\n raise ValueError(\"The number of classes must be positive\")\n\n if self.alpha <= 0:\n raise ValueError(\"The mixing interpolation strength must be positive.\")\n\n if self.num_mix < 2:\n raise ValueError(\"The number of samples to mix must be at least 2.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/preprocessor/mixup/mixup_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the Mixup data augmentation defence in TensorFlow.\n\n| Paper link: https://arxiv.org/abs/1710.09412\n\n| Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass MixupTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n Implement the Mixup data augmentation defence approach in TensorFlow v2.\n\n | Paper link: https://arxiv.org/abs/1710.09412\n\n | Please keep in mind the limitations of defences. For more information on the limitations of this defence,\n see https://arxiv.org/abs/1803.09868 . For details on how to evaluate classifier security in general, see\n https://arxiv.org/abs/1902.06705\n \"\"\"\n\n params = [\"num_classes\", \"alpha\", \"num_mix\"]\n\n def __init__(\n self,\n num_classes: int,\n alpha: float = 1.0,\n num_mix: int = 2,\n apply_fit: bool = True,\n apply_predict: bool = False,\n ) -> None:\n \"\"\"\n Create an instance of a Mixup data augmentation object.\n\n :param num_classes: The number of classes used for one-hot encoding.\n :param alpha: The hyperparameter for the mixing interpolation strength.\n :param num_mix: The number of samples to mix for k-way Mixup.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.num_classes = num_classes\n self.alpha = alpha\n self.num_mix = num_mix\n self._check_params()\n\n def forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Apply Mixup data augmentation to feature data `x` and labels `y`.\n\n :param x: Feature data to augment with shape `(batch_size, ...)`.\n :param y: Labels of `x` either one-hot or multi-hot encoded of shape `(nb_samples, nb_classes)`\n or class indices of shape `(nb_samples,)`.\n :return: Data augmented sample. The returned labels will be probability vectors of shape\n `(nb_samples, nb_classes)`.\n :raises `ValueError`: If no labels are provided.\n \"\"\"\n import tensorflow as tf # lgtm [py/repeated-import]\n\n if y is None:\n raise ValueError(\"Labels `y` cannot be None.\")\n\n # convert labels to one-hot encoding\n if len(y.shape) == 2:\n y_one_hot = y\n elif len(y.shape) == 1:\n y_one_hot = tf.one_hot(y, self.num_classes, on_value=1.0, off_value=0.0)\n else:\n raise ValueError(\n \"Shape of labels not recognised. \"\n \"Please provide labels in shape (nb_samples,) or (nb_samples, nb_classes)\"\n )\n\n n = x.shape[0]\n\n # sample the mixing factor from the Dirichlet distribution\n lmbs = np.random.dirichlet([self.alpha] * self.num_mix)\n\n x_aug = lmbs[0] * x\n y_aug = lmbs[0] * y_one_hot\n for lmb in lmbs[1:]:\n # randomly choose indices for samples to mix\n indices = tf.random.shuffle(tf.range(n))\n x_aug = x_aug + lmb * tf.gather(x, indices, axis=None)\n y_aug = y_aug + lmb * tf.gather(y_one_hot, indices, axis=None)\n\n return x_aug, y_aug\n\n def _check_params(self) -> None:\n if self.num_classes <= 0:\n raise ValueError(\"The number of classes must be positive\")\n\n if self.alpha <= 0:\n raise ValueError(\"The mixing interpolation strength must be positive.\")\n\n if self.num_mix < 2:\n raise ValueError(\"The number of samples to mix must be at least 2.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing train-based defences against adversarial attacks.\n\"\"\"\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.defences.trainer.adversarial_trainer import AdversarialTrainer\nfrom art.defences.trainer.certified_adversarial_trainer_pytorch import AdversarialTrainerCertifiedPytorch\nfrom art.defences.trainer.ibp_certified_trainer_pytorch import AdversarialTrainerCertifiedIBPPyTorch\nfrom art.defences.trainer.adversarial_trainer_madry_pgd import AdversarialTrainerMadryPGD\nfrom art.defences.trainer.adversarial_trainer_fbf import AdversarialTrainerFBF\nfrom art.defences.trainer.adversarial_trainer_fbf_pytorch import AdversarialTrainerFBFPyTorch\nfrom art.defences.trainer.adversarial_trainer_trades import AdversarialTrainerTRADES\nfrom art.defences.trainer.adversarial_trainer_trades_pytorch import AdversarialTrainerTRADESPyTorch\nfrom art.defences.trainer.adversarial_trainer_awp import AdversarialTrainerAWP\nfrom art.defences.trainer.adversarial_trainer_awp_pytorch import AdversarialTrainerAWPPyTorch\nfrom art.defences.trainer.adversarial_trainer_oaat import AdversarialTrainerOAAT\nfrom art.defences.trainer.adversarial_trainer_oaat_pytorch import AdversarialTrainerOAATPyTorch\nfrom art.defences.trainer.dp_instahide_trainer import DPInstaHideTrainer\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements adversarial training based on a model and one or multiple attack methods. It incorporates\noriginal adversarial training, ensemble adversarial training, training on all adversarial data and other common setups.\nIf multiple attacks are specified, they are rotated for each batch. If the specified attacks have as target a different\nmodel, then the attack is transferred. The `ratio` determines how many of the clean samples in each batch are replaced\nwith their adversarial counterpart.\n\n.. warning:: Both successful and unsuccessful adversarial samples are used for training. In the case of\n unbounded attacks (e.g., DeepFool), this can result in invalid (very noisy) samples being included.\n\n| Paper link: https://arxiv.org/abs/1705.07204\n\n| Please keep in mind the limitations of defences. While adversarial training is widely regarded as a promising,\n principled approach to making classifiers more robust (see https://arxiv.org/abs/1802.00420), very careful\n evaluations are required to assess its effectiveness case by case (see https://arxiv.org/abs/1902.06705).\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange, tqdm\n\nfrom art.defences.trainer.trainer import Trainer\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n from art.attacks.attack import EvasionAttack\n from art.data_generators import DataGenerator\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialTrainer(Trainer):\n \"\"\"\n Class performing adversarial training based on a model architecture and one or multiple attack methods.\n\n Incorporates original adversarial training, ensemble adversarial training (https://arxiv.org/abs/1705.07204),\n training on all adversarial data and other common setups. If multiple attacks are specified, they are rotated\n for each batch. If the specified attacks have as target a different model, then the attack is transferred. The\n `ratio` determines how many of the clean samples in each batch are replaced with their adversarial counterpart.\n\n .. warning:: Both successful and unsuccessful adversarial samples are used for training. In the case of\n unbounded attacks (e.g., DeepFool), this can result in invalid (very noisy) samples being included.\n\n | Paper link: https://arxiv.org/abs/1705.07204\n\n | Please keep in mind the limitations of defences. While adversarial training is widely regarded as a promising,\n principled approach to making classifiers more robust (see https://arxiv.org/abs/1802.00420), very careful\n evaluations are required to assess its effectiveness case by case (see https://arxiv.org/abs/1902.06705).\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n attacks: \"EvasionAttack\" | list[\"EvasionAttack\"],\n ratio: float = 0.5,\n ) -> None:\n \"\"\"\n Create an :class:`.AdversarialTrainer` instance.\n\n :param classifier: Model to train adversarially.\n :param attacks: attacks to use for data augmentation in adversarial training\n :param ratio: The proportion of samples in each batch to be replaced with their adversarial counterparts.\n Setting this value to 1 allows to train only on adversarial samples.\n \"\"\"\n from art.attacks.attack import EvasionAttack\n\n super().__init__(classifier=classifier)\n if isinstance(attacks, EvasionAttack):\n self.attacks = [attacks]\n elif isinstance(attacks, list):\n self.attacks = attacks\n else:\n raise ValueError(\"Only EvasionAttack instances or list of attacks supported.\")\n\n if ratio <= 0 or ratio > 1:\n raise ValueError(\"The `ratio` of adversarial samples in each batch has to be between 0 and 1.\")\n self.ratio = ratio\n\n self._precomputed_adv_samples: list[np.ndarray | None] = []\n self.x_augmented: np.ndarray | None = None\n self.y_augmented: np.ndarray | None = None\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Train a model adversarially using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n logger.info(\"Performing adversarial training using %i attacks.\", len(self.attacks))\n if generator.size is None:\n raise ValueError(\"Generator size is required and cannot be None.\")\n batch_size = generator.batch_size\n nb_batches = int(np.ceil(generator.size / batch_size)) # type: ignore\n ind = np.arange(generator.size)\n attack_id = 0\n\n # Precompute adversarial samples for transferred attacks\n logged = False\n self._precomputed_adv_samples = []\n for attack in tqdm(self.attacks, desc=\"Precompute adversarial examples.\"):\n if \"verbose\" in attack.attack_params:\n attack.set_params(verbose=False)\n if \"targeted\" in attack.attack_params and attack.targeted: # type: ignore\n raise NotImplementedError(\"Adversarial training with targeted attacks is currently not implemented\")\n\n if attack.estimator != self._classifier:\n if not logged:\n logger.info(\"Precomputing transferred adversarial samples.\")\n logged = True\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch, y_batch = generator.get_batch()\n x_adv_batch = attack.generate(x_batch, y=y_batch)\n if batch_id == 0:\n next_precomputed_adv_samples = x_adv_batch\n else:\n next_precomputed_adv_samples = np.append(next_precomputed_adv_samples, x_adv_batch, axis=0)\n self._precomputed_adv_samples.append(next_precomputed_adv_samples)\n else:\n self._precomputed_adv_samples.append(None)\n\n for _ in trange(nb_epochs, desc=\"Adversarial training epochs\"):\n # Shuffle the indices of precomputed examples\n np.random.shuffle(ind)\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch, y_batch = generator.get_batch()\n x_batch = x_batch.copy()\n\n # Choose indices to replace with adversarial samples\n attack = self.attacks[attack_id]\n if \"verbose\" in attack.attack_params:\n attack.set_params(verbose=False)\n\n # If source and target models are the same, craft fresh adversarial samples\n if attack.estimator == self._classifier:\n nb_adv = int(np.ceil(self.ratio * x_batch.shape[0]))\n\n if self.ratio < 1:\n adv_ids = np.random.choice(x_batch.shape[0], size=nb_adv, replace=False)\n else:\n adv_ids = np.array(list(range(x_batch.shape[0])))\n np.random.shuffle(adv_ids)\n\n x_batch[adv_ids] = attack.generate(x_batch[adv_ids], y=y_batch[adv_ids])\n\n # Otherwise, use precomputed adversarial samples\n else:\n batch_size_current = min(batch_size, generator.size - batch_id * batch_size)\n nb_adv = int(np.ceil(self.ratio * batch_size_current))\n if self.ratio < 1:\n adv_ids = np.random.choice(batch_size_current, size=nb_adv, replace=False)\n else:\n adv_ids = np.array(list(range(batch_size_current)))\n np.random.shuffle(adv_ids)\n\n x_adv = self._precomputed_adv_samples[attack_id]\n if x_adv is not None:\n x_adv = x_adv[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, generator.size)]][\n adv_ids\n ]\n x_batch[adv_ids] = x_adv\n\n # Fit batch\n self._classifier.fit(\n x_batch, y_batch, nb_epochs=1, batch_size=x_batch.shape[0], verbose=False, **kwargs\n )\n attack_id = (attack_id + 1) % len(self.attacks)\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Train a model adversarially. See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n logger.info(\"Performing adversarial training using %i attacks.\", len(self.attacks))\n nb_batches = int(np.ceil(len(x) / batch_size))\n ind = np.arange(len(x))\n attack_id = 0\n\n # Precompute adversarial samples for transferred attacks\n logged = False\n self._precomputed_adv_samples = []\n for attack in tqdm(self.attacks, desc=\"Precompute adv samples\"):\n if \"verbose\" in attack.attack_params:\n attack.set_params(verbose=False)\n if \"targeted\" in attack.attack_params and attack.targeted: # type: ignore\n raise NotImplementedError(\"Adversarial training with targeted attacks is currently not implemented\")\n\n if attack.estimator != self._classifier:\n if not logged:\n logger.info(\"Precomputing transferred adversarial samples.\")\n logged = True\n self._precomputed_adv_samples.append(attack.generate(x, y=y))\n else:\n self._precomputed_adv_samples.append(None)\n\n for _ in trange(nb_epochs, desc=\"Adversarial training epochs\"):\n # Shuffle the examples\n np.random.shuffle(ind)\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch = x[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]].copy()\n y_batch = y[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n\n # Choose indices to replace with adversarial samples\n nb_adv = int(np.ceil(self.ratio * x_batch.shape[0]))\n attack = self.attacks[attack_id]\n if \"verbose\" in attack.attack_params:\n attack.set_params(verbose=False)\n if self.ratio < 1:\n adv_ids = np.random.choice(x_batch.shape[0], size=nb_adv, replace=False)\n else:\n adv_ids = np.array(list(range(x_batch.shape[0])))\n np.random.shuffle(adv_ids)\n\n # If source and target models are the same, craft fresh adversarial samples\n if attack.estimator == self._classifier:\n x_batch[adv_ids] = attack.generate(x_batch[adv_ids], y=y_batch[adv_ids])\n\n # Otherwise, use precomputed adversarial samples\n else:\n x_adv = self._precomputed_adv_samples[attack_id]\n if x_adv is not None:\n x_adv = x_adv[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]][\n adv_ids\n ]\n x_batch[adv_ids] = x_adv\n\n # Fit batch\n self._classifier.fit(\n x_batch, y_batch, nb_epochs=1, batch_size=x_batch.shape[0], verbose=False, **kwargs\n )\n attack_id = (attack_id + 1) % len(self.attacks)\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n return self._classifier.predict(x, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_awp.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements adversarial training with Adversarial Weight Perturbation (AWP) protocol.\n\n| Paper link: https://proceedings.neurips.cc/paper/2020/file/1ef91c212e30e14bf125e9374262401f-Paper.pdf\n\n| It was noted that this protocol uses double perturbation mechanism i.e, perturbation on the input samples and then\nperturbation on the model parameters. Consequently, framework specific implementations are being provided in ART.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.attacks.attack import EvasionAttack\nfrom art.data_generators import DataGenerator\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nclass AdversarialTrainerAWP(Trainer):\n \"\"\"\n This is abstract class for different backend-specific implementations of AWP protocol\n for adversarial training.\n\n | Paper link: https://proceedings.neurips.cc/paper/2020/file/1ef91c212e30e14bf125e9374262401f-Paper.pdf\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n proxy_classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n attack: EvasionAttack,\n mode: str = \"PGD\",\n gamma: float = 0.01,\n beta: float = 6.0,\n warmup: int = 0,\n ):\n \"\"\"\n Create an :class:`.AdversarialTrainerAWP` instance.\n\n :param classifier: Model to train adversarially.\n :param proxy_classifier: Model for adversarial weight perturbation.\n :param attack: attack to use for data augmentation in adversarial training\n :param mode: mode determining the optimization objective of base adversarial training and weight perturbation\n step\n :param gamma: The scaling factor controlling norm of weight perturbation relative to model parameters norm\n :param beta: The scaling factor controlling tradeoff between clean loss and adversarial loss for TRADES protocol\n :param warmup: The number of epochs after which weight perturbation is applied\n \"\"\"\n self._attack = attack\n self._proxy_classifier = proxy_classifier\n self._mode = mode\n self._gamma = gamma\n self._beta = beta\n self._warmup = warmup\n self._apply_wp = False\n super().__init__(classifier)\n\n @abc.abstractmethod\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with AWP. See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def fit_generator(\n self,\n generator: DataGenerator,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with AWP using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n return self._classifier.predict(x, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_awp_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis is a PyTorch implementation of the Adversarial Weight Perturbation (AWP) protocol.\n\n| Paper link: https://proceedings.neurips.cc/paper/2020/file/1ef91c212e30e14bf125e9374262401f-Paper.pdf\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport time\nfrom typing import TYPE_CHECKING\n\nfrom collections import OrderedDict\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.defences.trainer.adversarial_trainer_awp import AdversarialTrainerAWP\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.data_generators import DataGenerator\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\nEPS = 1e-8 # small value required for avoiding division by zero and for KLDivLoss to make probability vector non-zero\n\n\nclass AdversarialTrainerAWPPyTorch(AdversarialTrainerAWP):\n \"\"\"\n Class performing adversarial training following Adversarial Weight Perturbation (AWP) protocol.\n\n | Paper link: https://proceedings.neurips.cc/paper/2020/file/1ef91c212e30e14bf125e9374262401f-Paper.pdf\n \"\"\"\n\n def __init__(\n self,\n classifier: PyTorchClassifier,\n proxy_classifier: PyTorchClassifier,\n attack: EvasionAttack,\n mode: str,\n gamma: float,\n beta: float,\n warmup: int,\n ):\n \"\"\"\n Create an :class:`.AdversarialTrainerAWPPyTorch` instance.\n\n :param classifier: Model to train adversarially.\n :param proxy_classifier: Model for adversarial weight perturbation.\n :param attack: attack to use for data augmentation in adversarial training.\n :param mode: mode determining the optimization objective of base adversarial training and weight perturbation\n step\n :param gamma: The scaling factor controlling norm of weight perturbation relative to model parameters' norm.\n :param beta: The scaling factor controlling tradeoff between clean loss and adversarial loss for TRADES protocol\n :param warmup: The number of epochs after which weight perturbation is applied\n \"\"\"\n super().__init__(classifier, proxy_classifier, attack, mode, gamma, beta, warmup)\n self._classifier: PyTorchClassifier\n self._proxy_classifier: PyTorchClassifier\n self._attack: EvasionAttack\n self._mode: str\n self.gamma: float\n self._beta: float\n self._warmup: int\n self._apply_wp: bool\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with AWP protocol.\n See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param scheduler: Learning rate scheduler to run at the end of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n import torch\n\n logger.info(\"Performing adversarial training with AWP with %s protocol\", self._mode)\n\n if (scheduler is not None) and (not isinstance(scheduler, torch.optim.lr_scheduler._LRScheduler)):\n raise ValueError(\"Invalid Pytorch scheduler is provided for adversarial training.\")\n\n best_acc_adv_test = 0\n nb_batches = int(np.ceil(len(x) / batch_size))\n ind = np.arange(len(x))\n\n logger.info(\"Adversarial Training AWP with %s\", self._mode)\n y = check_and_transform_label_format(y, nb_classes=self.classifier.nb_classes)\n\n for i_epoch in trange(nb_epochs, desc=f\"Adversarial Training AWP with {self._mode} - Epochs\"):\n\n if i_epoch >= self._warmup:\n self._apply_wp = True\n # Shuffle the examples\n np.random.shuffle(ind)\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch = x[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]].copy()\n y_batch = y[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n\n _train_loss, _train_acc, _train_n = self._batch_process(x_batch, y_batch)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n if scheduler:\n scheduler.step()\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n (x_test, y_test) = validation_data\n y_test = check_and_transform_label_format(y_test, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed_test, y_preprocessed_test = self._classifier._apply_preprocessing(\n x_test,\n y_test,\n fit=True,\n )\n # pylint: enable=protected-access\n output_clean = np.argmax(self.predict(x_preprocessed_test), axis=1)\n nb_correct_clean = np.sum(output_clean == np.argmax(y_preprocessed_test, axis=1))\n x_test_adv = self._attack.generate(x_preprocessed_test, y=y_preprocessed_test)\n output_adv = np.argmax(self.predict(x_test_adv), axis=1)\n nb_correct_adv = np.sum(output_adv == np.argmax(y_preprocessed_test, axis=1))\n\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv (tr): %.4f acc-clean (val): %.4f acc-adv (val): %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n nb_correct_clean / x_test.shape[0],\n nb_correct_adv / x_test.shape[0],\n )\n\n # save last checkpoint\n if i_epoch + 1 == nb_epochs:\n self._classifier.save(filename=f\"awp_{self._mode.lower()}_epoch_{i_epoch}\")\n\n # save best checkpoint\n if nb_correct_adv / x_test.shape[0] > best_acc_adv_test:\n self._classifier.save(filename=f\"awp_{self._mode.lower()}_epoch_best\")\n best_acc_adv_test = nb_correct_adv / x_test.shape[0]\n\n else:\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def fit_generator(\n self,\n generator: DataGenerator,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n nb_epochs: int = 20,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with AWP protocol using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param nb_epochs: Number of epochs to use for trainings.\n :param scheduler: Learning rate scheduler to run at the end of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n import torch\n\n logger.info(\"Performing adversarial training with AWP with %s protocol\", self._mode)\n\n if (scheduler is not None) and (not isinstance(scheduler, torch.optim.lr_scheduler._LRScheduler)):\n raise ValueError(\"Invalid Pytorch scheduler is provided for adversarial training.\")\n\n size = generator.size\n batch_size = generator.batch_size\n if size is not None:\n nb_batches = int(np.ceil(size / batch_size))\n else:\n raise ValueError(\"Size is None.\")\n\n logger.info(\"Adversarial Training AWP with %s\", self._mode)\n\n best_acc_adv_test = 0\n for i_epoch in trange(nb_epochs, desc=f\"Adversarial Training AWP with {self._mode} - Epochs\"):\n\n if i_epoch >= self._warmup:\n self._apply_wp = True\n\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for _ in range(nb_batches):\n # Create batch data\n x_batch, y_batch = generator.get_batch()\n x_batch = x_batch.copy()\n\n _train_loss, _train_acc, _train_n = self._batch_process(x_batch, y_batch)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n if scheduler:\n scheduler.step()\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n (x_test, y_test) = validation_data\n y_test = check_and_transform_label_format(y_test, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed_test, y_preprocessed_test = self._classifier._apply_preprocessing(\n x_test,\n y_test,\n fit=True,\n )\n # pylint: enable=protected-access\n output_clean = np.argmax(self.predict(x_preprocessed_test), axis=1)\n nb_correct_clean = np.sum(output_clean == np.argmax(y_preprocessed_test, axis=1))\n x_test_adv = self._attack.generate(x_preprocessed_test, y=y_preprocessed_test)\n output_adv = np.argmax(self.predict(x_test_adv), axis=1)\n nb_correct_adv = np.sum(output_adv == np.argmax(y_preprocessed_test, axis=1))\n\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv (tr): %.4f acc-clean (val): %.4f acc-adv (val): %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n nb_correct_clean / x_test.shape[0],\n nb_correct_adv / x_test.shape[0],\n )\n # save last checkpoint\n if i_epoch + 1 == nb_epochs:\n self._classifier.save(filename=f\"awp_{self._mode.lower()}_epoch_{i_epoch}\")\n\n # save best checkpoint\n if nb_correct_adv / x_test.shape[0] > best_acc_adv_test:\n self._classifier.save(filename=f\"awp_{self._mode.lower()}_epoch_best\")\n best_acc_adv_test = nb_correct_adv / x_test.shape[0]\n\n else:\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def _batch_process(self, x_batch: np.ndarray, y_batch: np.ndarray) -> tuple[float, float, float]:\n \"\"\"\n Perform the operations of AWP for a batch of data.\n See class documentation for more information on the exact procedure.\n\n :param x_batch: batch of x.\n :param y_batch: batch of y.\n :return: Tuple containing batch data loss, batch data accuracy and number of samples in the batch\n \"\"\"\n import torch\n from torch import nn\n import torch.nn.functional as F\n\n if self._classifier.optimizer is None:\n raise ValueError(\"Optimizer of classifier is currently None, but is required for adversarial training.\")\n\n if self._proxy_classifier.optimizer is None:\n raise ValueError(\n \"Optimizer of proxy classifier is currently None, but is required for adversarial training.\"\n )\n\n self._classifier.model.train(mode=False)\n x_batch_pert = self._attack.generate(x_batch, y=y_batch)\n\n # Apply preprocessing\n y_batch = check_and_transform_label_format(y_batch, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed, y_preprocessed = self._classifier._apply_preprocessing(x_batch, y_batch, fit=True)\n x_preprocessed_pert, _ = self._classifier._apply_preprocessing(x_batch_pert, y_batch, fit=True)\n\n # Check label shape\n if self._classifier._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n i_batch = torch.from_numpy(x_preprocessed).to(self._classifier.device)\n i_batch_pert = torch.from_numpy(x_preprocessed_pert).to(self._classifier.device)\n o_batch = torch.from_numpy(y_preprocessed).to(self._classifier.device)\n\n self._classifier.model.train(mode=True)\n\n if self._apply_wp:\n w_perturb = self._weight_perturbation(x_batch=i_batch, x_batch_pert=i_batch_pert, y_batch=o_batch)\n list_keys = list(w_perturb.keys())\n self._modify_classifier(self._classifier, list_keys, w_perturb, op=\"add\")\n\n # Zero the parameter gradients\n self._classifier.optimizer.zero_grad()\n\n if self._mode.lower() == \"pgd\":\n # Perform prediction\n model_outputs_pert = self._classifier.model(i_batch_pert)\n loss = self._classifier.loss(model_outputs_pert, o_batch)\n\n elif self._mode.lower() == \"trades\":\n n = x_batch.shape[0]\n # Perform prediction\n model_outputs = self._classifier.model(i_batch)\n model_outputs_pert = self._classifier.model(i_batch_pert)\n\n # Form the loss function\n loss_clean = self._classifier.loss(model_outputs, o_batch)\n loss_kl = (1.0 / n) * nn.KLDivLoss(reduction=\"sum\")(\n F.log_softmax(model_outputs_pert, dim=1), torch.clamp(F.softmax(model_outputs, dim=1), min=EPS)\n )\n loss = loss_clean + self._beta * loss_kl\n\n else:\n raise ValueError(\n \"Incorrect mode provided for base adversarial training. 'mode' must be among 'PGD' and 'TRADES'.\"\n )\n\n loss.backward()\n\n self._classifier.optimizer.step()\n\n if self._apply_wp:\n self._modify_classifier(self._classifier, list_keys, w_perturb, op=\"subtract\")\n\n train_loss = loss.item() * o_batch.size(0)\n train_acc = (model_outputs_pert.max(1)[1] == o_batch).sum().item()\n train_n = o_batch.size(0)\n\n self._classifier.model.train(mode=False)\n\n return train_loss, train_acc, train_n\n\n def _weight_perturbation(\n self, x_batch: \"torch.Tensor\", x_batch_pert: \"torch.Tensor\", y_batch: \"torch.Tensor\"\n ) -> dict[str, \"torch.Tensor\"]:\n \"\"\"\n Calculate wight perturbation for a batch of data.\n See class documentation for more information on the exact procedure.\n\n :param x_batch: batch of x.\n :param x_batch_pert: batch of x with perturbations.\n :param y_batch: batch of y.\n :return: dict containing names of classifier model's layers as keys and parameters as values\n \"\"\"\n import torch\n from torch import nn\n import torch.nn.functional as F\n\n w_perturb = OrderedDict()\n params_dict, _ = self._calculate_model_params(self._classifier)\n list_keys = list(params_dict.keys())\n self._proxy_classifier.model.load_state_dict(self._classifier.model.state_dict())\n self._proxy_classifier.model.train(mode=True)\n\n if self._mode.lower() == \"pgd\":\n # Perform prediction\n model_outputs_pert = self._proxy_classifier.model(x_batch_pert)\n loss = -self._proxy_classifier.loss(model_outputs_pert, y_batch)\n elif self._mode.lower() == \"trades\":\n n = x_batch.shape[0]\n # Perform prediction\n model_outputs = self._proxy_classifier.model(x_batch)\n model_outputs_pert = self._proxy_classifier.model(x_batch_pert)\n loss_clean = self._proxy_classifier.loss(model_outputs, y_batch)\n loss_kl = (1.0 / n) * nn.KLDivLoss(reduction=\"sum\")(\n F.log_softmax(model_outputs_pert, dim=1), torch.clamp(F.softmax(model_outputs, dim=1), min=EPS)\n )\n loss = -1.0 * (loss_clean + self._beta * loss_kl)\n\n else:\n raise ValueError(\n \"Incorrect mode provided for base adversarial training. 'mode' must be among 'PGD' and 'TRADES'.\"\n )\n\n self._proxy_classifier.optimizer.zero_grad()\n loss.backward()\n self._proxy_classifier.optimizer.step()\n\n params_dict_proxy, _ = self._calculate_model_params(self._proxy_classifier)\n\n for name in list_keys:\n perturbation = params_dict_proxy[name][\"param\"] - params_dict[name][\"param\"]\n perturbation = torch.reshape(perturbation, list(params_dict[name][\"size\"]))\n scale = params_dict[name][\"norm\"] / (perturbation.norm() + EPS)\n w_perturb[name] = scale * perturbation\n\n return w_perturb\n\n @staticmethod\n def _calculate_model_params(\n p_classifier: PyTorchClassifier,\n ) -> tuple[dict[str, dict[str, \"torch.Tensor\"]], \"torch.Tensor\"]:\n \"\"\"\n Calculates a given model's different layers' parameters' shape and norm, and model parameter norm.\n\n :param p_classifier: model for awp protocol.\n :return: Tuple with first element a dictionary with model parameters' names as keys and a nested dictionary\n as value. The nested dictionary contains model parameters, model parameters' size, model parameters' norms.\n The second element of tuple denotes norm of all model parameters\n \"\"\"\n import torch\n\n params_dict: dict[str, dict[str, \"torch.Tensor\"]] = OrderedDict()\n list_params = []\n for name, param in p_classifier.model.state_dict().items():\n if len(param.size()) <= 1:\n continue\n if \"weight\" in name:\n temp_param = param.reshape(-1)\n list_params.append(temp_param)\n params_dict[name] = OrderedDict()\n params_dict[name][\"param\"] = temp_param\n params_dict[name][\"size\"] = param.size()\n params_dict[name][\"norm\"] = temp_param.norm()\n\n model_all_params = torch.cat(list_params)\n model_all_params_norm = model_all_params.norm()\n return params_dict, model_all_params_norm\n\n def _modify_classifier(\n self, p_classifier: PyTorchClassifier, list_keys: list[str], w_perturb: dict[str, \"torch.Tensor\"], op: str\n ) -> None:\n \"\"\"\n Modify the model's weight parameters according to the weight perturbations.\n\n :param p_classifier: model for awp protocol.\n :param list_keys: List of model parameters' names\n :param w_perturb: dictionary containing model parameters' names as keys and model parameters as values\n :param op: controls whether weight perturbation will be added or subtracted from model parameters\n \"\"\"\n import torch\n\n if op.lower() == \"add\":\n c_mult = 1.0\n elif op.lower() == \"subtract\":\n c_mult = -1.0\n else:\n raise ValueError(\"Incorrect op provided for weight perturbation. 'op' must be among 'add' and 'subtract'.\")\n with torch.no_grad():\n for name, param in p_classifier.model.named_parameters():\n if name in list_keys:\n param.add_(c_mult * self._gamma * w_perturb[name])\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_fbf.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements adversarial training with Fast is better than free protocol.\n\n| Paper link: https://openreview.net/forum?id=BJx040EFvH\n\n| It was noted that this protocol is sensitive to the use of techniques like data augmentation, gradient clipping,\n and learning rate schedules. Consequently, framework specific implementations are being provided in ART.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.trainer.trainer import Trainer\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n from art.data_generators import DataGenerator\n\n\nclass AdversarialTrainerFBF(Trainer, abc.ABC):\n \"\"\"\n This is abstract class for different backend-specific implementations of Fast is Better than Free protocol\n for adversarial training.\n\n | Paper link: https://openreview.net/forum?id=BJx040EFvH\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n eps: int | float = 8,\n ):\n \"\"\"\n Create an :class:`.AdversarialTrainerFBF` instance.\n\n :param classifier: Model to train adversarially.\n :param eps: Maximum perturbation that the attacker can introduce.\n \"\"\"\n self._eps = eps\n super().__init__(classifier)\n\n @abc.abstractmethod\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with FBF. See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs):\n \"\"\"\n Train a model adversarially using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n return self._classifier.predict(x, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_fbf_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis is a PyTorch implementation of the Fast is better than free protocol.\n\n| Paper link: https://openreview.net/forum?id=BJx040EFvH\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport time\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.trainer.adversarial_trainer_fbf import AdversarialTrainerFBF\nfrom art.utils import random_sphere\n\nif TYPE_CHECKING:\n from art.data_generators import DataGenerator\n from art.estimators.classification.pytorch import PyTorchClassifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialTrainerFBFPyTorch(AdversarialTrainerFBF):\n \"\"\"\n Class performing adversarial training following Fast is Better Than Free protocol.\n\n | Paper link: https://openreview.net/forum?id=BJx040EFvH\n\n | The effectiveness of this protocol is found to be sensitive to the use of techniques like\n data augmentation, gradient clipping and learning rate schedules. Optionally, the use of\n mixed precision arithmetic operation via apex library can significantly reduce the training\n time making this one of the fastest adversarial training protocol.\n \"\"\"\n\n def __init__(self, classifier: \"PyTorchClassifier\", eps: int | float = 8, use_amp: bool = False):\n \"\"\"\n Create an :class:`.AdversarialTrainerFBFPyTorch` instance.\n\n :param classifier: Model to train adversarially.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param use_amp: Boolean that decides if apex should be used for mixed precision arithmetic during training\n \"\"\"\n super().__init__(classifier, eps)\n self._classifier: \"PyTorchClassifier\"\n self._use_amp = use_amp\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with FBF protocol.\n See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n logger.info(\"Performing adversarial training with Fast is better than Free protocol\")\n\n nb_batches = int(np.ceil(len(x) / batch_size))\n ind = np.arange(len(x))\n\n def lr_schedule(step_t):\n return np.interp([step_t], [0, nb_epochs * 2 // 5, nb_epochs], [0, 0.21, 0])[0]\n\n logger.info(\"Adversarial Training FBF\")\n\n for i_epoch in trange(nb_epochs, desc=\"Adversarial Training FBF - Epochs\"):\n # Shuffle the examples\n np.random.shuffle(ind)\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n l_r = lr_schedule(i_epoch + (batch_id + 1) / nb_batches)\n\n # Create batch data\n x_batch = x[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]].copy()\n y_batch = y[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n\n _train_loss, _train_acc, _train_n = self._batch_process(x_batch, y_batch, l_r)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n (x_test, y_test) = validation_data\n output = np.argmax(self.predict(x_test), axis=1)\n nb_correct_pred = np.sum(output == np.argmax(y_test, axis=1))\n logger.info(\n \"epoch: %s time(s): %.1f l_r: %.4f loss: %.4f acc(tr): %.4f acc(val): %.4f\",\n i_epoch,\n train_time - start_time,\n l_r,\n train_loss / train_n,\n train_acc / train_n,\n nb_correct_pred / x_test.shape[0],\n )\n else:\n logger.info(\n \"epoch: %s time(s): %.1f l_r %.4f loss: %.4f acc: %.4f\",\n i_epoch,\n train_time - start_time,\n l_r,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs):\n \"\"\"\n Train a model adversarially with FBF protocol using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n logger.info(\"Performing adversarial training with Fast is better than Free protocol\")\n size = generator.size\n batch_size = generator.batch_size\n if size is not None:\n nb_batches = int(np.ceil(size / batch_size))\n else:\n raise ValueError(\"Size is None.\")\n\n def lr_schedule(step_t):\n return np.interp([step_t], [0, nb_epochs * 2 // 5, nb_epochs], [0, 0.21, 0])[0]\n\n logger.info(\"Adversarial Training FBF\")\n\n for i_epoch in trange(nb_epochs, desc=\"Adversarial Training FBF - Epochs\"):\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n l_r = lr_schedule(i_epoch + (batch_id + 1) / nb_batches)\n\n # Create batch data\n x_batch, y_batch = generator.get_batch()\n x_batch = x_batch.copy()\n\n _train_loss, _train_acc, _train_n = self._batch_process(x_batch, y_batch, l_r)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n train_time = time.time()\n logger.info(\n \"epoch: %s time(s): %.1f l_r: %.4f loss: %.4f acc: %.4f\",\n i_epoch,\n train_time - start_time,\n l_r,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def _batch_process(self, x_batch: np.ndarray, y_batch: np.ndarray, l_r: float) -> tuple[float, float, float]:\n \"\"\"\n Perform the operations of FBF for a batch of data.\n See class documentation for more information on the exact procedure.\n\n :param x_batch: batch of x.\n :param y_batch: batch of y.\n :param l_r: learning rate for the optimisation step.\n \"\"\"\n import torch\n\n if self._classifier._optimizer is None:\n raise ValueError(\"Optimizer of classifier is currently None, but is required for adversarial training.\")\n\n n = x_batch.shape[0]\n m = np.prod(x_batch.shape[1:]).item()\n delta = random_sphere(n, m, self._eps, np.inf).reshape(x_batch.shape).astype(ART_NUMPY_DTYPE)\n delta_grad = self._classifier.loss_gradient(x_batch + delta, y_batch)\n delta = np.clip(delta + 1.25 * self._eps * np.sign(delta_grad), -self._eps, +self._eps)\n if self._classifier.clip_values is not None:\n x_batch_pert = np.clip(x_batch + delta, self._classifier.clip_values[0], self._classifier.clip_values[1])\n else:\n x_batch_pert = x_batch + delta\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._classifier._apply_preprocessing(x_batch_pert, y_batch, fit=True)\n\n # Check label shape\n if self._classifier._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n i_batch = torch.from_numpy(x_preprocessed).to(self._classifier._device)\n o_batch = torch.from_numpy(y_preprocessed).to(self._classifier._device)\n\n # Zero the parameter gradients\n self._classifier._optimizer.zero_grad()\n\n # Perform prediction\n model_outputs = self._classifier._model(i_batch)\n\n # Form the loss function\n loss = self._classifier._loss(model_outputs[-1], o_batch)\n\n self._classifier._optimizer.param_groups[0].update(lr=l_r)\n\n # Actual training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._classifier._optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n # clip the gradients\n torch.nn.utils.clip_grad_norm_(self._classifier._model.parameters(), 0.5)\n self._classifier._optimizer.step()\n\n train_loss = loss.item() * o_batch.size(0)\n train_acc = (model_outputs[0].max(1)[1] == o_batch).sum().item()\n train_n = o_batch.size(0)\n\n return train_loss, train_acc, train_n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_madry_pgd.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements adversarial training following Madry's Protocol.\n\n| Paper link: https://arxiv.org/abs/1706.06083\n\n| Please keep in mind the limitations of defences. While adversarial training is widely regarded as a promising,\n principled approach to making classifiers more robust (see https://arxiv.org/abs/1802.00420), very careful\n evaluations are required to assess its effectiveness case by case (see https://arxiv.org/abs/1902.06705).\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.defences.trainer.adversarial_trainer import AdversarialTrainer\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialTrainerMadryPGD(Trainer):\n \"\"\"\n Class performing adversarial training following Madry's Protocol.\n\n | Paper link: https://arxiv.org/abs/1706.06083\n\n | Please keep in mind the limitations of defences. While adversarial training is widely regarded as a promising,\n principled approach to making classifiers more robust (see https://arxiv.org/abs/1802.00420), very careful\n evaluations are required to assess its effectiveness case by case (see https://arxiv.org/abs/1902.06705).\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n nb_epochs: int | None = 205,\n batch_size: int | None = 128,\n eps: int | float = 8,\n eps_step: int | float = 2,\n max_iter: int = 7,\n num_random_init: int = 1,\n ) -> None:\n \"\"\"\n Create an :class:`.AdversarialTrainerMadryPGD` instance.\n\n Default values are for CIFAR-10 in pixel range 0-255.\n\n :param classifier: Classifier to train adversarially.\n :param nb_epochs: Number of training epochs.\n :param batch_size: Size of the batch on which adversarial samples are generated.\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: The maximum number of iterations.\n :param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0\n starting at the original input.\n \"\"\"\n super().__init__(classifier=classifier) # type: ignore\n self.batch_size = batch_size\n self.nb_epochs = nb_epochs\n\n # Setting up adversary and perform adversarial training:\n self.attack = ProjectedGradientDescent(\n classifier,\n eps=eps,\n eps_step=eps_step,\n max_iter=max_iter,\n num_random_init=num_random_init,\n )\n\n self.trainer = AdversarialTrainer(classifier, self.attack, ratio=1.0) # type: ignore\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: np.ndarray | None = None,\n batch_size: int | None = None,\n nb_epochs: int | None = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Train a model adversarially. See class documentation for more information on the exact procedure.\n\n :param x: Training data.\n :param y: Labels for the training data.\n :param validation_data: Validation data.\n :param batch_size: Size of batches. Overwrites batch_size defined in __init__ if not None.\n :param nb_epochs: Number of epochs to use for trainings. Overwrites nb_epochs defined in __init__ if not None.\n :param kwargs: Dictionary of framework-specific arguments.\n \"\"\"\n batch_size_fit: int\n if batch_size is not None:\n batch_size_fit = batch_size\n elif self.batch_size is not None:\n batch_size_fit = self.batch_size\n else:\n raise ValueError(\"Please provide value for `batch_size`.\")\n\n if nb_epochs is not None:\n nb_epochs_fit: int = nb_epochs\n elif self.nb_epochs is not None:\n nb_epochs_fit = self.nb_epochs\n else:\n raise ValueError(\"Please provide value for `nb_epochs`.\")\n\n self.trainer.fit(\n x, y, validation_data=validation_data, nb_epochs=nb_epochs_fit, batch_size=batch_size_fit, **kwargs\n )\n\n def get_classifier(self) -> \"CLASSIFIER_LOSS_GRADIENTS_TYPE\":\n return self.trainer.get_classifier()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_oaat.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements adversarial training with Oracle Aligned Adversarial Training (OAAT) protocol\nfor adversarial training for defence against larger perturbations.\n\n| Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18\n\n| It was noted that this protocol uses double perturbation mechanism i.e, perturbation on the input samples and then\nperturbation on the model parameters. Consequently, framework specific implementations are being provided in ART.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.attacks.attack import EvasionAttack\nfrom art.data_generators import DataGenerator\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nclass AdversarialTrainerOAAT(Trainer):\n \"\"\"\n This is abstract class for different backend-specific implementations of OAAT protocol.\n\n | Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n proxy_classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n lpips_classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n list_avg_models: Sequence[\"CLASSIFIER_LOSS_GRADIENTS_TYPE\"],\n attack: EvasionAttack,\n train_params: dict,\n ):\n \"\"\"\n Create an :class:`.AdversarialTrainerOAAT` instance.\n\n :param classifier: Model to train adversarially.\n :param proxy_classifier: Model for adversarial weight perturbation.\n :param lpips_classifier: Weight averaging model for calculating activations.\n :param list_avg_models: List of models for weight averaging.\n :param attack: attack to use for data augmentation in adversarial training\n :param train_params: parameters' dictionary related to adversarial training\n \"\"\"\n self._attack = attack\n self._proxy_classifier = proxy_classifier\n self._lpips_classifier = lpips_classifier\n self._list_avg_models = list_avg_models\n self._train_params = train_params\n self._apply_wp = False\n self._apply_lpips_pert = False\n super().__init__(classifier)\n\n @abc.abstractmethod\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with OAAT. See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def fit_generator(\n self,\n generator: DataGenerator,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with OAAT using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n return self._classifier.predict(x, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_oaat_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis is a PyTorch implementation of the Oracle Aligned Adversarial Training (OAAT) protocol\nfor adversarial training for defence against larger perturbations.\n\n| Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections import OrderedDict\nimport logging\nimport os\nimport time\nfrom typing import TYPE_CHECKING\n\nimport six\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art import config\nfrom art.defences.trainer.adversarial_trainer_oaat import AdversarialTrainerOAAT\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.data_generators import DataGenerator\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import check_and_transform_label_format, random_sphere\nfrom art.config import ART_NUMPY_DTYPE\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\nEPS = 1e-8 # small value required for avoiding division by zero and for KLDivLoss to make probability vector non-zero\n\n\nclass AdversarialTrainerOAATPyTorch(AdversarialTrainerOAAT):\n \"\"\"\n Class performing adversarial training following Oracle Aligned Adversarial Training (OAAT) protocol.\n\n | Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18\n \"\"\"\n\n def __init__(\n self,\n classifier: PyTorchClassifier,\n proxy_classifier: PyTorchClassifier,\n lpips_classifier: PyTorchClassifier,\n list_avg_models: list[PyTorchClassifier],\n attack: EvasionAttack,\n train_params: dict,\n ):\n \"\"\"\n Create an :class:`.AdversarialTrainerOAATPyTorch` instance.\n\n :param classifier: Model to train adversarially.\n :param proxy_classifier: Model for adversarial weight perturbation.\n :param lpips_classifier: Weight averaging model for calculating activations.\n :param list_avg_models: List of models for weight averaging.\n :param attack: attack to use for data augmentation in adversarial training.\n :param train_params: training parameters' dictionary related to adversarial training\n \"\"\"\n super().__init__(classifier, proxy_classifier, lpips_classifier, list_avg_models, attack, train_params)\n self._classifier: PyTorchClassifier\n self._proxy_classifier: PyTorchClassifier\n self._lpips_classifier: PyTorchClassifier\n self._list_avg_models: list[PyTorchClassifier]\n self._attack: EvasionAttack\n self._train_params: dict\n self._apply_wp: bool\n self._apply_lpips_pert: bool\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with OAAT protocol.\n See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n import torch\n\n logger.info(\"Performing adversarial training with OAAT protocol\")\n\n best_acc_adv_test = 0\n nb_batches = int(np.ceil(len(x) / batch_size))\n ind = np.arange(len(x))\n\n logger.info(\"Adversarial Training OAAT\")\n\n if (len(self._train_params[\"list_swa_epoch\"]) != len(self._train_params[\"list_swa_tau\"])) or (\n len(self._train_params[\"list_swa_epoch\"]) != len(self._list_avg_models)\n ):\n raise ValueError(\n \"number of elements of list_swa_epoch must be same as of \" \"list_swa_tau and list_avg_models.\"\n )\n\n beta_init = self._train_params[\"beta\"]\n y = check_and_transform_label_format(y, nb_classes=self.classifier.nb_classes)\n\n for i_epoch in trange(nb_epochs, desc=\"Adversarial Training OAAT - Epochs\"):\n\n if i_epoch >= self._train_params[\"awp_warmup\"]:\n self._apply_wp = True\n\n if i_epoch == (int(3 * nb_epochs / 4)):\n self._classifier._optimizer = torch.optim.SGD(\n self._classifier.model.parameters(),\n lr=self._train_params[\"lr\"],\n momentum=self._train_params[\"momentum\"],\n weight_decay=self._train_params[\"weight_decay\"],\n )\n\n if isinstance(self._classifier.optimizer, torch.optim.SGD):\n\n if self._train_params[\"oaat_warmup\"] == 1:\n if i_epoch < 10:\n self.update_learning_rate(self._classifier.optimizer, i_epoch, nb_epochs, lr_schedule=\"linear\")\n else:\n self.update_learning_rate(\n self._classifier.optimizer,\n i_epoch,\n nb_epochs,\n lr_schedule=self._train_params[\"lr_schedule\"],\n )\n else:\n\n self.update_learning_rate(\n self._classifier.optimizer, i_epoch, nb_epochs, lr_schedule=self._train_params[\"lr_schedule\"]\n )\n\n if i_epoch > (nb_epochs // 4):\n self._train_params[\"i_epsilon\"] = i_epoch * self._train_params[\"epsilon\"] / nb_epochs\n\n if self._train_params[\"i_epsilon\"] > self._train_params[\"alternate_iter_eps\"]:\n self._apply_lpips_pert = True\n\n load_swa_model_tau = self._train_params[\"load_swa_model_tau\"]\n file_name = f\"oaat_swa_tau_{load_swa_model_tau}.model\"\n if self._train_params[\"models_path\"] is None:\n full_path_load = os.path.join(config.ART_DATA_PATH, file_name)\n else:\n full_path_load = os.path.join(self._train_params[\"models_path\"], file_name)\n if os.path.isfile(full_path_load):\n self._lpips_classifier._model._model.load_state_dict(torch.load(full_path_load))\n else:\n raise ValueError(\"Invalid path/file for weight average model is provided for adversarial training.\")\n\n self._lpips_classifier.model.train(mode=False)\n self._lpips_classifier.model.to(self._classifier.device)\n\n self._train_params[\"alpha\"] = self._train_params[\"alpha\"] - self._train_params[\"mixup_alpha\"] / (\n nb_epochs - int(3 * nb_epochs / 4) + 1\n )\n self._train_params[\"i_lpips_weight\"] = (\n self._train_params[\"lpips_weight\"]\n * (i_epoch - int(3 * nb_epochs / 4))\n / (nb_epochs - int(3 * nb_epochs / 4))\n )\n self._train_params[\"beta\"] = beta_init + (self._train_params[\"beta_final\"] - beta_init) * (\n i_epoch - int(3 * nb_epochs / 4)\n ) / (nb_epochs - int(3 * nb_epochs / 4))\n\n # Shuffle the examples\n np.random.shuffle(ind)\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch = x[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]].copy()\n y_batch = y[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n\n _train_loss, _train_acc, _train_n = self._batch_process(i_epoch, nb_epochs, batch_id, x_batch, y_batch)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n (x_test, y_test) = validation_data\n y_test = check_and_transform_label_format(y_test, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed_test, y_preprocessed_test = self._classifier._apply_preprocessing(\n x_test,\n y_test,\n fit=True,\n )\n # pylint: enable=protected-access\n output_clean = np.argmax(self.predict(x_preprocessed_test), axis=1)\n nb_correct_clean = np.sum(output_clean == np.argmax(y_preprocessed_test, axis=1))\n self._attack.set_params(\n eps=self._train_params[\"epsilon\"],\n eps_step=self._train_params[\"epsilon\"] / 4.0,\n max_iter=self._train_params[\"max_iter\"],\n )\n x_test_adv = self._attack.generate(x_preprocessed_test, y=y_preprocessed_test)\n\n x_preprocessed_test_adv, y_preprocessed_test = self._classifier._apply_preprocessing(\n x_test_adv,\n y_test,\n fit=True,\n )\n # pylint: enable=protected-access\n output_adv = np.argmax(self.predict(x_preprocessed_test_adv), axis=1)\n nb_correct_adv = np.sum(output_adv == np.argmax(y_preprocessed_test, axis=1))\n\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv (tr): %.4f acc-clean (val): %.4f acc-adv (val): %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n nb_correct_clean / x_test.shape[0],\n nb_correct_adv / x_test.shape[0],\n )\n\n # save last checkpoint\n if i_epoch + 1 == nb_epochs:\n self._classifier.save(filename=f\"oaat_epoch_{i_epoch}\", path=self._train_params[\"models_path\"])\n\n # save best checkpoint\n if nb_correct_adv / x_test.shape[0] > best_acc_adv_test:\n self._classifier.save(filename=\"oaat_epoch_best\", path=self._train_params[\"models_path\"])\n best_acc_adv_test = nb_correct_adv / x_test.shape[0]\n\n else:\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n if i_epoch > self._train_params[\"swa_save_epoch\"] - 1:\n for epoch_swa, tau_val, p_classifier in zip(\n self._train_params[\"list_swa_epoch\"], self._train_params[\"list_swa_tau\"], self._list_avg_models\n ):\n if epoch_swa <= i_epoch:\n file_name = f\"oaat_swa_tau_{tau_val}.model\"\n if self._train_params[\"models_path\"] is None:\n full_path = os.path.join(config.ART_DATA_PATH, file_name)\n else:\n full_path = os.path.join(self._train_params[\"models_path\"], file_name)\n\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # disable pylint because access to _modules required\n torch.save(p_classifier._model._model.state_dict(), full_path)\n\n def fit_generator(\n self,\n generator: DataGenerator,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with OAAT protocol using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n import torch\n\n logger.info(\"Performing adversarial training with OAAT protocol\")\n\n size = generator.size\n batch_size = generator.batch_size\n if size is not None:\n nb_batches = int(np.ceil(size / batch_size))\n else:\n raise ValueError(\"Size is None.\")\n\n logger.info(\"Adversarial Training OAAT\")\n\n if (len(self._train_params[\"list_swa_epoch\"]) != len(self._train_params[\"list_swa_tau\"])) or (\n len(self._train_params[\"list_swa_epoch\"]) != len(self._list_avg_models)\n ):\n raise ValueError(\n \"number of elements of list_swa_epoch must be same as of \" \"list_swa_tau and list_avg_models.\"\n )\n\n beta_init = self._train_params[\"beta\"]\n best_acc_adv_test = 0\n for i_epoch in trange(nb_epochs, desc=\"Adversarial Training OAAT - Epochs\"):\n\n if i_epoch >= self._train_params[\"awp_warmup\"]:\n self._apply_wp = True\n\n if i_epoch == (int(3 * nb_epochs / 4)):\n self._classifier._optimizer = torch.optim.SGD(\n self._classifier.model.parameters(),\n lr=self._train_params[\"lr\"],\n momentum=self._train_params[\"momentum\"],\n weight_decay=self._train_params[\"weight_decay\"],\n )\n\n if isinstance(self._classifier.optimizer, torch.optim.SGD):\n\n if self._train_params[\"oaat_warmup\"] == 1:\n if i_epoch < 10:\n self.update_learning_rate(self._classifier.optimizer, i_epoch, nb_epochs, lr_schedule=\"linear\")\n else:\n self.update_learning_rate(\n self._classifier.optimizer,\n i_epoch,\n nb_epochs,\n lr_schedule=self._train_params[\"lr_schedule\"],\n )\n else:\n\n self.update_learning_rate(\n self._classifier.optimizer, i_epoch, nb_epochs, lr_schedule=self._train_params[\"lr_schedule\"]\n )\n\n if i_epoch > (nb_epochs // 4):\n self._train_params[\"i_epsilon\"] = i_epoch * self._train_params[\"epsilon\"] / nb_epochs\n\n if self._train_params[\"i_epsilon\"] > self._train_params[\"alternate_iter_eps\"]:\n self._apply_lpips_pert = True\n\n load_swa_model_tau = self._train_params[\"load_swa_model_tau\"]\n file_name = f\"oaat_swa_tau_{load_swa_model_tau}.model\"\n if self._train_params[\"models_path\"] is None:\n full_path_load = os.path.join(config.ART_DATA_PATH, file_name)\n else:\n full_path_load = os.path.join(self._train_params[\"models_path\"], file_name)\n if os.path.isfile(full_path_load):\n self._lpips_classifier._model._model.load_state_dict(torch.load(full_path_load))\n else:\n raise ValueError(\"Invalid path/file for weight average model is provided for adversarial training.\")\n\n self._lpips_classifier.model.train(mode=False)\n self._lpips_classifier.model.to(self._classifier.device)\n\n self._train_params[\"alpha\"] = self._train_params[\"alpha\"] - self._train_params[\"mixup_alpha\"] / (\n nb_epochs - int(3 * nb_epochs / 4) + 1\n )\n self._train_params[\"i_lpips_weight\"] = (\n self._train_params[\"lpips_weight\"]\n * (i_epoch - int(3 * nb_epochs / 4))\n / (nb_epochs - int(3 * nb_epochs / 4))\n )\n self._train_params[\"beta\"] = beta_init + (self._train_params[\"beta_final\"] - beta_init) * (\n i_epoch - int(3 * nb_epochs / 4)\n ) / (nb_epochs - int(3 * nb_epochs / 4))\n\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch, y_batch = generator.get_batch()\n x_batch = x_batch.copy()\n\n _train_loss, _train_acc, _train_n = self._batch_process(i_epoch, nb_epochs, batch_id, x_batch, y_batch)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n (x_test, y_test) = validation_data\n y_test = check_and_transform_label_format(y_test, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed_test, y_preprocessed_test = self._classifier._apply_preprocessing(\n x_test,\n y_test,\n fit=True,\n )\n # pylint: enable=protected-access\n output_clean = np.argmax(self.predict(x_preprocessed_test), axis=1)\n nb_correct_clean = np.sum(output_clean == np.argmax(y_preprocessed_test, axis=1))\n self._attack.set_params(\n eps=self._train_params[\"epsilon\"],\n eps_step=self._train_params[\"epsilon\"] / 4.0,\n max_iter=self._train_params[\"max_iter\"],\n )\n x_test_adv = self._attack.generate(x_preprocessed_test, y=y_preprocessed_test)\n\n x_preprocessed_test_adv, y_preprocessed_test = self._classifier._apply_preprocessing(\n x_test_adv,\n y_test,\n fit=True,\n )\n # pylint: enable=protected-access\n output_adv = np.argmax(self.predict(x_preprocessed_test_adv), axis=1)\n nb_correct_adv = np.sum(output_adv == np.argmax(y_preprocessed_test, axis=1))\n\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv (tr): %.4f acc-clean (val): %.4f acc-adv (val): %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n nb_correct_clean / x_test.shape[0],\n nb_correct_adv / x_test.shape[0],\n )\n # save last checkpoint\n if i_epoch + 1 == nb_epochs:\n self._classifier.save(filename=f\"oaat_epoch_{i_epoch}\", path=self._train_params[\"models_path\"])\n\n # save best checkpoint\n if nb_correct_adv / x_test.shape[0] > best_acc_adv_test:\n self._classifier.save(filename=\"oaat_epoch_best\", path=self._train_params[\"models_path\"])\n best_acc_adv_test = nb_correct_adv / x_test.shape[0]\n\n else:\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc-adv: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n if i_epoch > self._train_params[\"swa_save_epoch\"] - 1:\n for epoch_swa, tau_val, p_classifier in zip(\n self._train_params[\"list_swa_epoch\"], self._train_params[\"list_swa_tau\"], self._list_avg_models\n ):\n if epoch_swa <= i_epoch:\n file_name = f\"oaat_swa_tau_{tau_val}.model\"\n if self._train_params[\"models_path\"] is None:\n full_path = os.path.join(config.ART_DATA_PATH, file_name)\n else:\n full_path = os.path.join(self._train_params[\"models_path\"], file_name)\n\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # disable pylint because access to _modules required\n torch.save(p_classifier._model._model.state_dict(), full_path)\n\n def _batch_process(\n self, i_epoch: int, nb_epochs: int, batch_id: int, x_batch: np.ndarray, y_batch: np.ndarray\n ) -> tuple[float, float, float]:\n \"\"\"\n Perform the operations of OAAT for a batch of data.\n See class documentation for more information on the exact procedure.\n\n :param i_epoch: training epoch number.\n :param nb_epochs: total training epochs.\n :param batch_id: batch_id of input data.\n :param x_batch: batch of x.\n :param y_batch: batch of y.\n :return: Tuple containing batch data loss, batch data accuracy and number of samples in the batch\n \"\"\"\n import torch\n from torch import nn\n import torch.nn.functional as F\n\n if self._classifier.optimizer is None:\n raise ValueError(\"Optimizer of classifier is currently None, but is required for adversarial training.\")\n\n if self._proxy_classifier.optimizer is None:\n raise ValueError(\n \"Optimizer of proxy classifier is currently None, but is required for adversarial training.\"\n )\n\n self._classifier.model.train(mode=False)\n\n if self._apply_lpips_pert and (batch_id % 2 != 0):\n x_batch_pert = self._attack_lpips(\n x_batch,\n y=y_batch,\n eps=self._train_params[\"i_epsilon\"],\n eps_step=self._train_params[\"i_epsilon\"] / 4.0,\n max_iter=self._train_params[\"max_iter\"],\n training_mode=False,\n )\n\n elif self._apply_lpips_pert and (batch_id % 2 == 0):\n self._attack.set_params(\n eps=self._train_params[\"mixup_epsilon\"],\n eps_step=self._train_params[\"mixup_epsilon\"] / 4.0,\n max_iter=self._train_params[\"max_iter\"],\n )\n x_batch_pert = self._attack.generate(x_batch, y=y_batch)\n\n else:\n if i_epoch <= (nb_epochs // 4):\n self._attack.set_params(\n eps=self._train_params[\"i_epsilon\"], eps_step=self._train_params[\"i_epsilon\"] / 2.0, max_iter=5\n )\n else:\n self._attack.set_params(\n eps=self._train_params[\"i_epsilon\"],\n eps_step=self._train_params[\"i_epsilon\"] / 4.0,\n max_iter=self._train_params[\"max_iter\"],\n )\n\n x_batch_pert = self._attack.generate(x_batch, y=y_batch)\n\n # Apply preprocessing\n y_batch = check_and_transform_label_format(y_batch, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed, y_preprocessed = self._classifier._apply_preprocessing(x_batch, y_batch, fit=True)\n x_preprocessed_pert, _ = self._classifier._apply_preprocessing(x_batch_pert, y_batch, fit=True)\n\n # Check label shape\n if self._classifier._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n i_batch = torch.from_numpy(x_preprocessed).to(self._classifier.device)\n i_batch_pert = torch.from_numpy(x_preprocessed_pert).to(self._classifier.device)\n o_batch = torch.from_numpy(y_preprocessed).to(self._classifier.device)\n\n self._classifier.model.train(mode=True)\n\n if self._apply_wp:\n if not self._apply_lpips_pert:\n i_batch_pert_awp = torch.clamp(i_batch + 2.0 * (i_batch_pert - i_batch), 0, 1)\n else:\n i_batch_pert_awp = i_batch_pert\n w_perturb = self._weight_perturbation(x_batch=i_batch, x_batch_pert=i_batch_pert_awp, y_batch=o_batch)\n list_keys = list(w_perturb.keys())\n self._modify_classifier(self._classifier, list_keys, w_perturb, op=\"add\")\n\n # Zero the parameter gradients\n self._classifier.optimizer.zero_grad()\n\n n = x_batch.shape[0]\n # Perform prediction\n model_outputs = self._classifier.model(i_batch)\n model_outputs_pert = self._classifier.model(i_batch_pert)\n\n # Form the loss function\n loss_clean = self._classifier.loss(model_outputs, o_batch)\n\n if self._apply_lpips_pert and (batch_id % 2 == 0):\n i_batch_pert_eps = torch.min(\n torch.max(i_batch_pert, i_batch - self._train_params[\"i_epsilon\"]),\n i_batch + self._train_params[\"i_epsilon\"],\n )\n model_outputs_pert_eps = self._classifier.model(i_batch_pert_eps)\n loss_kl = (1.0 / n) * nn.KLDivLoss(reduction=\"sum\")(\n F.log_softmax(model_outputs_pert_eps, dim=1),\n torch.clamp(\n self._train_params[\"alpha\"] * F.softmax(model_outputs, dim=1)\n + (1.0 - self._train_params[\"alpha\"]) * F.softmax(model_outputs_pert, dim=1),\n min=EPS,\n ),\n )\n\n else:\n loss_kl = (1.0 / n) * nn.KLDivLoss(reduction=\"sum\")(\n F.log_softmax(model_outputs_pert, dim=1), torch.clamp(F.softmax(model_outputs, dim=1), min=EPS)\n )\n loss = loss_clean + self._train_params[\"beta\"] * loss_kl\n\n loss.backward()\n\n self._classifier.optimizer.step()\n\n if self._apply_wp:\n self._modify_classifier(self._classifier, list_keys, w_perturb, op=\"subtract\")\n\n train_loss = loss.item() * o_batch.size(0)\n train_acc = (model_outputs_pert.max(1)[1] == o_batch).sum().item()\n train_n = o_batch.size(0)\n\n for epoch_swa, tau_val, p_classifier in zip(\n self._train_params[\"list_swa_epoch\"], self._train_params[\"list_swa_tau\"], self._list_avg_models\n ):\n if i_epoch == epoch_swa:\n for name, params in self._classifier.model.state_dict().items():\n p_classifier.model.state_dict()[name] = params\n elif i_epoch > epoch_swa:\n for name, params in self._classifier.model.state_dict().items():\n p_classifier.model.state_dict()[name] = (\n 1 - tau_val\n ) * params + tau_val * p_classifier.model.state_dict()[name]\n else:\n pass\n\n self._classifier.model.train(mode=False)\n\n return train_loss, train_acc, train_n\n\n def _weight_perturbation(\n self, x_batch: \"torch.Tensor\", x_batch_pert: \"torch.Tensor\", y_batch: \"torch.Tensor\"\n ) -> dict[str, \"torch.Tensor\"]:\n \"\"\"\n Calculate wight perturbation for a batch of data.\n See class documentation for more information on the exact procedure.\n\n :param x_batch: batch of x.\n :param x_batch_pert: batch of x with perturbations.\n :param y_batch: batch of y.\n :return: dict containing names of classifier model's layers as keys and parameters as values\n \"\"\"\n import torch\n from torch import nn\n import torch.nn.functional as F\n\n w_perturb = OrderedDict()\n params_dict, _ = self._calculate_model_params(self._classifier)\n list_keys = list(params_dict.keys())\n self._proxy_classifier.model.load_state_dict(self._classifier.model.state_dict())\n self._proxy_classifier.model.train(mode=True)\n\n n = x_batch.shape[0]\n # Perform prediction\n model_outputs = self._proxy_classifier.model(x_batch)\n model_outputs_pert = self._proxy_classifier.model(x_batch_pert)\n loss_clean = self._proxy_classifier.loss(model_outputs, y_batch)\n loss_kl = (1.0 / n) * nn.KLDivLoss(reduction=\"sum\")(\n F.log_softmax(model_outputs_pert, dim=1), torch.clamp(F.softmax(model_outputs, dim=1), min=EPS)\n )\n loss = -1.0 * (loss_clean + self._train_params[\"beta\"] * loss_kl)\n\n self._proxy_classifier.optimizer.zero_grad()\n loss.backward()\n self._proxy_classifier.optimizer.step()\n\n params_dict_proxy, _ = self._calculate_model_params(self._proxy_classifier)\n\n for name in list_keys:\n perturbation = params_dict_proxy[name][\"param\"] - params_dict[name][\"param\"]\n perturbation = torch.reshape(perturbation, list(params_dict[name][\"size\"]))\n scale = params_dict[name][\"norm\"] / (perturbation.norm() + EPS)\n w_perturb[name] = scale * perturbation\n\n return w_perturb\n\n @staticmethod\n def _calculate_model_params(\n p_classifier: PyTorchClassifier,\n ) -> tuple[dict[str, dict[str, \"torch.Tensor\"]], \"torch.Tensor\"]:\n \"\"\"\n Calculates a given model's different layers' parameters' shape and norm, and model parameter norm.\n\n :param p_classifier: model for awp protocol.\n :return: Tuple with first element a dictionary with model parameters' names as keys and a nested dictionary\n as value. The nested dictionary contains model parameters, model parameters' size, model parameters' norms.\n The second element of tuple denotes norm of all model parameters\n \"\"\"\n import torch\n\n params_dict: dict[str, dict[str, \"torch.Tensor\"]] = OrderedDict()\n list_params = []\n for name, param in p_classifier.model.state_dict().items():\n if len(param.size()) <= 1:\n continue\n if \"weight\" in name:\n temp_param = param.reshape(-1)\n list_params.append(temp_param)\n params_dict[name] = OrderedDict()\n params_dict[name][\"param\"] = temp_param\n params_dict[name][\"size\"] = param.size()\n params_dict[name][\"norm\"] = temp_param.norm()\n\n model_all_params = torch.cat(list_params)\n model_all_params_norm = model_all_params.norm()\n return params_dict, model_all_params_norm\n\n def _modify_classifier(\n self, p_classifier: PyTorchClassifier, list_keys: list[str], w_perturb: dict[str, \"torch.Tensor\"], op: str\n ) -> None:\n \"\"\"\n Modify the model's weight parameters according to the weight perturbations.\n\n :param p_classifier: model for awp protocol.\n :param list_keys: list of model parameters' names\n :param w_perturb: dictionary containing model parameters' names as keys and model parameters as values\n :param op: controls whether weight perturbation will be added or subtracted from model parameters\n \"\"\"\n import torch\n\n if op.lower() == \"add\":\n c_mult = 1.0\n elif op.lower() == \"subtract\":\n c_mult = -1.0\n else:\n raise ValueError(\"Incorrect op provided for weight perturbation. 'op' must be among 'add' and 'subtract'.\")\n with torch.no_grad():\n for name, param in p_classifier.model.named_parameters():\n if name in list_keys:\n param.add_(c_mult * self._train_params[\"awp_gamma\"] * w_perturb[name])\n\n @staticmethod\n def get_layer_activations( # type: ignore\n p_classifier: PyTorchClassifier,\n x: \"torch.Tensor\",\n layers: list[int | str],\n ) -> tuple[dict[str, \"torch.Tensor\"], list[str]]:\n \"\"\"\n Return the output of the specified layers for input `x`. `layers` is a list of either layer indices (between 0\n and `nb_layers - 1`) or layers' name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param p_classifier: model for adversarial training protocol.\n :param x: Input for computing the activations.\n :param layers: Layers for computing the activations\n :return: Tuple containing the output dict and a list of layers' names. In dictionary each element is a\n layer's output where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n\n p_classifier.model.train(mode=False)\n\n list_layer_names = []\n for layer in layers:\n if isinstance(layer, six.string_types):\n if layer not in p_classifier._layer_names:\n raise ValueError(f\"Layer name {layer} not supported\")\n layer_name = layer\n list_layer_names.append(layer_name)\n\n elif isinstance(layer, int):\n layer_index = layer\n layer_name = p_classifier._layer_names[layer_index]\n list_layer_names.append(layer_name)\n\n else:\n raise TypeError(\"Layer must be of type str or int\")\n\n def get_feature(name):\n # the hook signature\n def hook(model, input, output): # pylint: disable=redefined-builtin,unused-argument\n p_classifier._features[name] = output\n\n return hook\n\n if not hasattr(p_classifier, \"_features\"):\n p_classifier._features = {}\n # register forward hooks on the layers of choice\n\n for layer_name in list_layer_names:\n if layer_name not in p_classifier._features:\n interim_layer = dict([*p_classifier._model._model.named_modules()])[layer_name]\n interim_layer.register_forward_hook(get_feature(layer_name))\n\n p_classifier.model(x)\n return p_classifier._features, list_layer_names\n\n @staticmethod\n def normalize_concatenate_activations(\n activations_dict: dict[str, \"torch.Tensor\"],\n list_layer_names: list[str],\n ) -> \"torch.Tensor\":\n \"\"\"\n Takes a dictionary `activations_dict' of activation values of different layers for an input batch and Returns\n a tensor where all activation values are normalised layer-wise and flattened to a vector for\n each input of the batch.\n\n :param activations_dict: dict containing the activations at different layers.\n :param list_layer_names: Layers' names for fetching the activations.\n :return: The activations after normalisation and flattening, where the first dimension is the batch size.\n \"\"\"\n\n import torch\n\n activation_vectors = []\n for name in list_layer_names:\n temp_activation = activations_dict[name]\n size_temp_activation = list(temp_activation.size())\n norm_factor_layer = size_temp_activation[2] * size_temp_activation[3]\n norm_temp_activation = torch.sqrt(torch.sum(temp_activation**2, dim=1, keepdim=True)) + EPS\n temp_activation_n_channel = temp_activation / norm_temp_activation\n temp_activation_n_layer_channel = temp_activation_n_channel / np.sqrt(norm_factor_layer)\n temp_activation_n_layer_channel_flat = temp_activation_n_layer_channel.view(size_temp_activation[0], -1)\n activation_vectors.append(temp_activation_n_layer_channel_flat)\n\n activation_vectors_flattened = torch.cat(activation_vectors, dim=1)\n return activation_vectors_flattened\n\n @staticmethod\n def calculate_lpips_distance( # type: ignore\n p_classifier: PyTorchClassifier,\n input_1: \"torch.Tensor\",\n input_2: \"torch.Tensor\",\n layers: list[int | str],\n ) -> \"torch.Tensor\":\n \"\"\"\n Return the LPIPS distance between input_1 and input_2. `layers` is a list of either layer indices (between 0 and\n `nb_layers - 1`) or layers' name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param p_classifier: model for adversarial training protocol.\n :param input_1: Input for computing the activations.\n :param input_2: Input for computing the activations.\n :param layers: Layers for computing the activations.\n :return: The lpips distance, where the first dimension is the batch size corresponding to\n `input_1`.\n \"\"\"\n\n import torch\n\n activations_input_1, list_layer_names = AdversarialTrainerOAATPyTorch.get_layer_activations(\n p_classifier, input_1, layers\n )\n activations_input_2, _ = AdversarialTrainerOAATPyTorch.get_layer_activations(p_classifier, input_2, layers)\n normalised_activations_1 = AdversarialTrainerOAATPyTorch.normalize_concatenate_activations(\n activations_input_1, list_layer_names\n )\n normalised_activations_2 = AdversarialTrainerOAATPyTorch.normalize_concatenate_activations(\n activations_input_2, list_layer_names\n )\n lpips_distance = torch.norm(normalised_activations_1 - normalised_activations_2, dim=1)\n\n return lpips_distance\n\n def update_learning_rate(\n self, optimizer: \"torch.optim.optimizer.Optimizer\", epoch: int, nb_epochs: int, lr_schedule: str = \"step\"\n ) -> None:\n \"\"\"\n adjust learning rate of the optimizer.\n\n :param optimizer: optimizer of the classifier.\n :param epoch: current training epoch.\n :param nb_epochs: total training epoch.\n :param lr_schedule: string denoting learning rate scheduler for optimizer\n :return: calculated learning rate\n \"\"\"\n if lr_schedule.lower() == \"cosine\":\n if self._train_params[\"oaat_warmup\"] == 1:\n l_r = self._train_params[\"lr\"] * 0.5 * (1 + np.cos((epoch - 10) / (nb_epochs - 10) * np.pi))\n else:\n l_r = self._train_params[\"lr\"] * 0.5 * (1 + np.cos(epoch / nb_epochs * np.pi))\n\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = l_r\n\n elif lr_schedule.lower() == \"linear\":\n l_r = (epoch + 1) * (self._train_params[\"lr\"] / 10)\n\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = l_r\n\n elif lr_schedule.lower() == \"step\":\n if epoch >= 75 * nb_epochs / 110:\n l_r = self._train_params[\"lr\"] * 0.1\n if epoch >= 90 * nb_epochs / 110:\n l_r = self._train_params[\"lr\"] * 0.01\n if epoch >= 100 * nb_epochs / 110:\n l_r = self._train_params[\"lr\"] * 0.001\n\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = l_r\n else:\n raise ValueError(f\"lr_schedule {lr_schedule} not supported\")\n\n def _attack_lpips(\n self,\n x: np.ndarray,\n y: np.ndarray,\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n max_iter: int,\n training_mode: bool,\n ) -> np.ndarray:\n \"\"\"\n Compute adversarial examples with cross entropy and lpips distance.\n\n :param x: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236).\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param max_iter: number of iterations of attack.\n :param training_mode: training mode of classifier for attack generation. training_mode=False puts classifier in\n eval mode\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n x_t = torch.from_numpy(x.astype(ART_NUMPY_DTYPE)).to(self._classifier.device)\n y_t = torch.from_numpy(y.astype(ART_NUMPY_DTYPE)).to(self._classifier.device)\n adv_x = torch.clone(x_t)\n\n for i_max_iter in range(max_iter):\n adv_x = self._one_step_adv_example(adv_x, x_t, y_t, eps, eps_step, i_max_iter == 0, training_mode)\n\n return adv_x.cpu().detach().numpy()\n\n def _one_step_adv_example(\n self,\n x: \"torch.Tensor\",\n x_init: \"torch.Tensor\",\n y: \"torch.Tensor\",\n eps: int | float | np.ndarray,\n eps_step: int | float | np.ndarray,\n random_init: bool,\n training_mode: bool,\n ) -> \"torch.Tensor\":\n \"\"\"\n Compute adversarial examples for one iteration.\n\n :param x: Current adversarial examples.\n :param x_init: An array with the original inputs.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236).\n :param eps: Maximum perturbation that the attacker can introduce.\n :param eps_step: Attack step size (input variation) at each iteration.\n :param random_init: Random initialisation within the epsilon ball. For random_init=False starting at the\n original input.\n :param training_mode: training mode of classifier for attack generation. training_mode=False puts classifier in\n eval mode\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n if random_init:\n n = x.shape[0]\n m = np.prod(x.shape[1:]).item()\n\n random_perturbation_array = (\n random_sphere(n, m, eps, self._train_params[\"norm\"]).reshape(x.shape).astype(ART_NUMPY_DTYPE)\n )\n random_perturbation = torch.from_numpy(random_perturbation_array).to(self._classifier.device)\n x_adv = x + random_perturbation\n\n if self._classifier.clip_values is not None:\n clip_min, clip_max = self._classifier.clip_values\n x_adv = torch.max(\n torch.min(x_adv, torch.tensor(clip_max).to(self._classifier.device)),\n torch.tensor(clip_min).to(self._classifier.device),\n )\n\n else:\n x_adv = x\n\n # Get perturbation\n perturbation = self._compute_perturbation(x_adv, x_init, y, training_mode)\n\n # Apply perturbation and clip\n x_adv = self._apply_perturbation(x_adv, perturbation, eps_step)\n\n # Do projection\n perturbation = self._projection(x_adv - x_init, eps, self._train_params[\"norm\"])\n\n # Recompute x_adv\n x_adv = perturbation + x_init\n\n return x_adv\n\n def _compute_perturbation(\n self, x: \"torch.Tensor\", x_init: \"torch.Tensor\", y: \"torch.Tensor\", training_mode: bool = False\n ) -> \"torch.Tensor\":\n \"\"\"\n Compute perturbations.\n\n :param x: Current adversarial examples.\n :param x_init: initial input samples.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,). Only provide this parameter if you'd like to use true labels when crafting adversarial\n samples. Otherwise, model predictions are used as labels to avoid the \"label leaking\" effect\n (explained in this paper: https://arxiv.org/abs/1611.01236). Default is `None`.\n :param training_mode: training mode of classifier for attack generation. training_mode=False puts classifier in\n eval mode\n \"\"\"\n import torch\n\n self._classifier.model.train(mode=training_mode)\n self._lpips_classifier.model.train(mode=training_mode)\n\n # Backpropagation through RNN modules in eval mode raises RuntimeError due to cudnn issues and require training\n # mode, i.e. RuntimeError: cudnn RNN backward can only be called in training mode. Therefore, if the model is\n # an RNN type we always use training mode but freeze batch-norm and dropout layers if training_mode=False.\n if self._classifier.is_rnn:\n self._classifier.model.train(mode=True)\n if not training_mode:\n logger.debug(\n \"Freezing batch-norm and dropout layers for gradient calculation in train mode with eval parameters\"\n \"of batch-norm and dropout.\"\n )\n self._classifier.set_batchnorm(train=False)\n self._classifier.set_dropout(train=False)\n\n if self._lpips_classifier.is_rnn:\n self._lpips_classifier.model.train(mode=True)\n if not training_mode:\n logger.debug(\n \"Freezing batch-norm and dropout layers for gradient calculation in train mode with eval parameters\"\n \"of batch-norm and dropout.\"\n )\n self._lpips_classifier.set_batchnorm(train=False)\n self._lpips_classifier.set_dropout(train=False)\n\n # Apply preprocessing\n if self._classifier.all_framework_preprocessing:\n if isinstance(x, torch.Tensor):\n x_grad = x.clone().detach().requires_grad_(True)\n else:\n x_grad = torch.tensor(x).to(self._classifier.device)\n x_grad.requires_grad = True\n if isinstance(y, torch.Tensor):\n y_grad = y.clone().detach()\n else:\n y_grad = torch.tensor(y).to(self._classifier.device)\n if isinstance(x_init, torch.Tensor):\n x_init = x_init.clone().detach()\n else:\n x_init = torch.tensor(x_init).to(self._classifier.device)\n inputs_t, y_preprocessed = self._classifier._apply_preprocessing(x_grad, y=y_grad, fit=False, no_grad=False)\n inputs_init, _ = self._classifier._apply_preprocessing(x_init, y=y_grad, fit=False, no_grad=False)\n elif isinstance(x, np.ndarray):\n x_preprocessed, y_preprocessed = self._classifier._apply_preprocessing(x, y=y, fit=False, no_grad=True)\n x_grad = torch.from_numpy(x_preprocessed).to(self._classifier.device)\n x_grad.requires_grad = True\n inputs_t = x_grad\n x_init_preprocessed, _ = self._classifier._apply_preprocessing(x_init, y=y, fit=False, no_grad=True)\n x_init = torch.from_numpy(x_init_preprocessed).to(self._classifier.device)\n x_init.requires_grad = False\n inputs_init = x_init\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n # Check label shape\n if self._classifier._reduce_labels:\n y_preprocessed = self._classifier.reduce_labels(y_preprocessed)\n\n if isinstance(y_preprocessed, np.ndarray):\n labels_t = torch.from_numpy(y_preprocessed).to(self._classifier.device)\n else:\n labels_t = y_preprocessed\n\n # Compute the gradient and return\n model_outputs = self._classifier.model(inputs_t)\n\n lpips_distance = self.calculate_lpips_distance(\n p_classifier=self._lpips_classifier,\n input_1=inputs_t,\n input_2=inputs_init,\n layers=self._train_params[\"layer_names_activation\"],\n )\n loss = self._classifier.loss(model_outputs, labels_t) - self._train_params[\"i_lpips_weight\"] * torch.mean(\n lpips_distance\n )\n\n # Clean gradients\n self._classifier.model.zero_grad()\n self._lpips_classifier.model.zero_grad()\n\n loss.backward()\n\n if x_grad.grad is not None:\n grad = x_grad.grad\n else:\n raise ValueError(\"Gradient term in PyTorch model is `None`.\")\n\n if not self._classifier.all_framework_preprocessing:\n grad = self._classifier._apply_preprocessing_gradient(x, grad)\n assert grad.shape == x.shape\n\n # Check for nan before normalisation and replace with 0\n if torch.any(grad.isnan()): # pragma: no cover\n logger.warning(\"Elements of the loss gradient are NaN and have been replaced with 0.0.\")\n grad[grad.isnan()] = 0.0\n\n # Apply norm bound\n if self._train_params[\"norm\"] in [\"inf\", np.inf]:\n grad = grad.sign()\n\n elif self._train_params[\"norm\"] == 1:\n ind = tuple(range(1, len(x.shape)))\n grad = grad / (torch.sum(grad.abs(), dim=ind, keepdims=True) + EPS) # type: ignore\n\n elif self._train_params[\"norm\"] == 2:\n ind = tuple(range(1, len(x.shape)))\n grad = grad / (torch.sqrt(torch.sum(grad * grad, axis=ind, keepdims=True)) + EPS) # type: ignore\n\n assert x.shape == grad.shape\n\n return grad\n\n def _apply_perturbation(\n self, x: \"torch.Tensor\", perturbation: \"torch.Tensor\", eps_step: int | float | np.ndarray\n ) -> \"torch.Tensor\":\n \"\"\"\n Apply perturbation on examples.\n\n :param x: Current adversarial examples.\n :param perturbation: Current perturbations.\n :param eps_step: Attack step size (input variation) at each iteration.\n :return: Adversarial examples.\n \"\"\"\n import torch\n\n eps_step = np.array(eps_step, dtype=ART_NUMPY_DTYPE)\n perturbation_step = torch.tensor(eps_step).to(self._classifier.device) * perturbation\n perturbation_step[torch.isnan(perturbation_step)] = 0\n x = x + perturbation_step\n if self._classifier.clip_values is not None:\n clip_min, clip_max = self._classifier.clip_values\n x = torch.max(\n torch.min(x, torch.tensor(clip_max).to(self._classifier.device)),\n torch.tensor(clip_min).to(self._classifier.device),\n )\n\n return x\n\n def _projection(\n self, values: \"torch.Tensor\", eps: int | float | np.ndarray, norm_p: int | float | str\n ) -> \"torch.Tensor\":\n \"\"\"\n Project `values` on the L_p norm ball of size `eps`.\n\n :param values: Values to clip.\n :param eps: Maximum norm allowed.\n :param norm_p: L_p norm to use for clipping supporting 1, 2, `np.Inf` and \"inf\".\n :return: Values of `values` after projection.\n \"\"\"\n import torch\n\n values_tmp = values.reshape(values.shape[0], -1)\n\n if norm_p == 2:\n if isinstance(eps, np.ndarray):\n raise NotImplementedError(\n \"The parameter `eps` of type `np.ndarray` is not supported to use with norm 2.\"\n )\n\n values_tmp = values_tmp * torch.min(\n torch.tensor([1.0], dtype=torch.float32).to(self._classifier.device),\n eps / (torch.norm(values_tmp, p=2, dim=1) + EPS),\n ).unsqueeze_(-1)\n\n elif norm_p == 1:\n if isinstance(eps, np.ndarray):\n raise NotImplementedError(\n \"The parameter `eps` of type `np.ndarray` is not supported to use with norm 1.\"\n )\n\n values_tmp = values_tmp * torch.min(\n torch.tensor([1.0], dtype=torch.float32).to(self._classifier.device),\n eps / (torch.norm(values_tmp, p=1, dim=1) + EPS),\n ).unsqueeze_(-1)\n\n elif norm_p in [np.inf, \"inf\"]:\n if isinstance(eps, np.ndarray):\n eps_array = eps * np.ones_like(values.cpu())\n eps = eps_array.reshape([eps_array.shape[0], -1])\n\n values_tmp = values_tmp.sign() * torch.min(\n values_tmp.abs(), torch.tensor([eps], dtype=torch.float32).to(self._classifier.device)\n )\n\n else:\n raise NotImplementedError(\n \"Values of `norm_p` different from 1, 2 and `np.inf` are currently not supported.\"\n )\n\n values = values_tmp.reshape(values.shape)\n\n return values\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_trades.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements adversarial training with TRADES protocol.\n\n| Paper link: https://proceedings.mlr.press/v97/zhang19p.html\n\n| It was noted that this protocol uses a modified loss called TRADES loss which is a combination of cross entropy\nloss on clean data and KL divergence loss between clean data and adversarial data. Consequently, framework specific\nimplementations are being provided in ART.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.attacks.attack import EvasionAttack\nfrom art.data_generators import DataGenerator\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nclass AdversarialTrainerTRADES(Trainer, abc.ABC):\n \"\"\"\n This is abstract class for different backend-specific implementations of TRADES protocol\n for adversarial training.\n\n | Paper link: https://proceedings.mlr.press/v97/zhang19p.html\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n attack: EvasionAttack,\n beta: float = 6.0,\n ):\n \"\"\"\n Create an :class:`.AdversarialTrainerTRADES` instance.\n\n :param classifier: Model to train adversarially.\n :param attack: attack to use for data augmentation in adversarial training\n :param beta: The scaling factor controlling tradeoff between clean loss and adversarial loss\n \"\"\"\n self._attack = attack\n self._beta = beta\n super().__init__(classifier)\n\n @abc.abstractmethod\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with TRADES. See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def fit_generator(self, generator: DataGenerator, nb_epochs: int = 20, **kwargs):\n \"\"\"\n Train a model adversarially using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n return self._classifier.predict(x, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/adversarial_trainer_trades_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis is a PyTorch implementation of the TRADES protocol.\n\n| Paper link: https://proceedings.mlr.press/v97/zhang19p.html\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport time\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.defences.trainer.adversarial_trainer_trades import AdversarialTrainerTRADES\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.data_generators import DataGenerator\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\nEPS = 1e-8\n\n\nclass AdversarialTrainerTRADESPyTorch(AdversarialTrainerTRADES):\n \"\"\"\n Class performing adversarial training following TRADES protocol.\n\n | Paper link: https://proceedings.mlr.press/v97/zhang19p.html\n \"\"\"\n\n def __init__(self, classifier: PyTorchClassifier, attack: EvasionAttack, beta: float):\n \"\"\"\n Create an :class:`.AdversarialTrainerTRADESPyTorch` instance.\n\n :param classifier: Model to train adversarially.\n :param attack: attack to use for data augmentation in adversarial training\n :param beta: The scaling factor controlling tradeoff between clean loss and adversarial loss\n \"\"\"\n super().__init__(classifier, attack, beta)\n self._classifier: PyTorchClassifier\n self._attack: EvasionAttack\n self._beta: float\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with TRADES protocol.\n See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param scheduler: Learning rate scheduler to run at the end of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n import torch\n\n logger.info(\"Performing adversarial training with TRADES protocol\")\n\n if (scheduler is not None) and (\n not isinstance(scheduler, torch.optim.lr_scheduler._LRScheduler)\n ): # pylint: enable=protected-access\n raise ValueError(\"Invalid Pytorch scheduler is provided for adversarial training.\")\n\n nb_batches = int(np.ceil(len(x) / batch_size))\n ind = np.arange(len(x))\n\n logger.info(\"Adversarial Training TRADES\")\n y = check_and_transform_label_format(y, nb_classes=self.classifier.nb_classes)\n\n if validation_data is not None:\n (x_test, y_test) = validation_data\n y_test = check_and_transform_label_format(y_test, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed_test, y_preprocessed_test = self._classifier._apply_preprocessing(x_test, y_test, fit=True)\n\n for i_epoch in trange(nb_epochs, desc=\"Adversarial Training TRADES - Epochs\"):\n # Shuffle the examples\n np.random.shuffle(ind)\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n # Create batch data\n x_batch = x[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]].copy()\n y_batch = y[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n\n _train_loss, _train_acc, _train_n = self._batch_process(x_batch, y_batch)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n if scheduler:\n scheduler.step()\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n output = np.argmax(self.predict(x_preprocessed_test), axis=1)\n nb_correct_pred = np.sum(output == np.argmax(y_preprocessed_test, axis=1))\n\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc(tr): %.4f acc(val): %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n nb_correct_pred / x_test.shape[0],\n )\n else:\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def fit_generator(\n self,\n generator: DataGenerator,\n nb_epochs: int = 20,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with TRADES protocol using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param nb_epochs: Number of epochs to use for trainings.\n :param scheduler: Learning rate scheduler to run at the end of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of\n the target classifier.\n \"\"\"\n import torch\n\n logger.info(\"Performing adversarial training with TRADES protocol\")\n\n if (scheduler is not None) and (\n not isinstance(scheduler, torch.optim.lr_scheduler._LRScheduler)\n ): # pylint: enable=protected-access\n raise ValueError(\"Invalid Pytorch scheduler is provided for adversarial training.\")\n\n size = generator.size\n batch_size = generator.batch_size\n if size is not None:\n nb_batches = int(np.ceil(size / batch_size))\n else:\n raise ValueError(\"Size is None.\")\n\n logger.info(\"Adversarial Training TRADES\")\n\n for i_epoch in trange(nb_epochs, desc=\"Adversarial Training TRADES - Epochs\"):\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches): # pylint: disable=unused-variable\n # Create batch data\n x_batch, y_batch = generator.get_batch()\n x_batch = x_batch.copy()\n\n _train_loss, _train_acc, _train_n = self._batch_process(x_batch, y_batch)\n\n train_loss += _train_loss\n train_acc += _train_acc\n train_n += _train_n\n\n if scheduler:\n scheduler.step()\n\n train_time = time.time()\n logger.info(\n \"epoch: %s time(s): %.1f loss: %.4f acc: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def _batch_process(self, x_batch: np.ndarray, y_batch: np.ndarray) -> tuple[float, float, float]:\n \"\"\"\n Perform the operations of TRADES for a batch of data.\n See class documentation for more information on the exact procedure.\n\n :param x_batch: batch of x.\n :param y_batch: batch of y.\n :return: Tuple containing batch data loss, batch data accuracy and number of samples in the batch\n \"\"\"\n import torch\n from torch import nn\n import torch.nn.functional as F\n\n if self._classifier._optimizer is None:\n raise ValueError(\"Optimizer of classifier is currently None, but is required for adversarial training.\")\n\n n = x_batch.shape[0]\n self._classifier._model.train(mode=False)\n x_batch_pert = self._attack.generate(x_batch, y=y_batch)\n\n # Apply preprocessing\n y_batch = check_and_transform_label_format(y_batch, nb_classes=self.classifier.nb_classes)\n\n x_preprocessed, y_preprocessed = self._classifier._apply_preprocessing(x_batch, y_batch, fit=True)\n x_preprocessed_pert, _ = self._classifier._apply_preprocessing(x_batch_pert, y_batch, fit=True)\n\n # Check label shape\n if self._classifier._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n i_batch = torch.from_numpy(x_preprocessed).to(self._classifier._device)\n i_batch_pert = torch.from_numpy(x_preprocessed_pert).to(self._classifier._device)\n o_batch = torch.from_numpy(y_preprocessed).to(self._classifier._device)\n\n self._classifier._model.train(mode=True)\n\n # Zero the parameter gradients\n self._classifier._optimizer.zero_grad()\n\n # Perform prediction\n model_outputs = self._classifier._model(i_batch)\n model_outputs_pert = self._classifier._model(i_batch_pert)\n\n # Form the loss function\n loss_clean = self._classifier._loss(model_outputs[-1], o_batch)\n loss_kl = (1.0 / n) * nn.KLDivLoss(reduction=\"sum\")(\n F.log_softmax(model_outputs_pert[-1], dim=1), torch.clamp(F.softmax(model_outputs[-1], dim=1), min=EPS)\n )\n loss = loss_clean + self._beta * loss_kl\n loss.backward()\n\n self._classifier._optimizer.step()\n\n train_loss = loss.item() * o_batch.size(0)\n train_acc = (model_outputs_pert[0].max(1)[1] == o_batch).sum().item()\n train_n = o_batch.size(0)\n\n self._classifier._model.train(mode=False)\n\n return train_loss, train_acc, train_n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/certified_adversarial_trainer_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements certified adversarial training following techniques from works such as:\n\n | Paper link: http://proceedings.mlr.press/v80/mirman18b/mirman18b.pdf\n | Paper link: https://arxiv.org/pdf/1810.12715.pdf\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport math\nimport random\nimport sys\n\nimport numpy as np\n\nfrom sklearn.utils import shuffle\nfrom tqdm import tqdm\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.utils import check_and_transform_label_format\n\nif sys.version_info >= (3, 8):\n from typing import TypedDict, Any, TYPE_CHECKING\nelse:\n from typing import Any, TYPE_CHECKING\n from functools import reduce\n\nif TYPE_CHECKING:\n from art.utils import CERTIFIER_TYPE\n\n # if we use python 3.8 or higher use the more informative TypedDict for type hinting\n if sys.version_info >= (3, 8):\n\n class PGDParamDict(TypedDict):\n \"\"\"\n A TypedDict class to define the types in the pgd_params dictionary.\n \"\"\"\n\n eps: float\n eps_step: float\n max_iter: int\n num_random_init: int\n batch_size: int\n\n else:\n PGDParamDict: dict[str, int | float]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DefaultLinearScheduler:\n \"\"\"\n Class implementing a simple linear scheduler to grow the certification radius.\n \"\"\"\n\n def __init__(self, step_per_epoch: float, initial_bound: float = 0.0) -> None:\n \"\"\"\n Create a .DefaultLinearScheduler instance.\n\n :param step_per_epoch: how much to increase the certification radius every epoch\n :param initial_bound: the initial bound to increase from\n \"\"\"\n self.step_per_epoch = step_per_epoch\n self.bound = initial_bound\n\n def step(self) -> float:\n \"\"\"\n Grow the certification radius by self.step_per_epoch\n \"\"\"\n self.bound += self.step_per_epoch\n return self.bound\n\n\nclass AdversarialTrainerCertifiedPytorch(Trainer):\n \"\"\"\n Class performing certified adversarial training from methods such as\n\n | Paper link: http://proceedings.mlr.press/v80/mirman18b/mirman18b.pdf\n | Paper link: https://arxiv.org/pdf/1810.12715.pdf\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CERTIFIER_TYPE\",\n nb_epochs: int | None = 20,\n bound: float = 0.1,\n loss_weighting: float = 0.1,\n batch_size: int = 10,\n use_certification_schedule: bool = True,\n certification_schedule: Any | None = None,\n augment_with_pgd: bool = True,\n pgd_params: \"PGDParamDict\" | None = None,\n ) -> None:\n \"\"\"\n Create an :class:`.AdversarialTrainerCertified` instance.\n\n Default values are for MNIST in pixel range 0-1.\n\n :param classifier: Classifier to train adversarially.\n :param pgd_params: A dictionary containing the specific parameters relating to regular PGD training.\n If not provided, we will default to typical MNIST values.\n Otherwise, must contain the following keys:\n\n * *eps*: Maximum perturbation that the attacker can introduce.\n * *eps_step*: Attack step size (input variation) at each iteration.\n * *max_iter*: The maximum number of iterations.\n * *batch_size*: Size of the batch on which adversarial samples are generated.\n * *num_random_init*: Number of random initialisations within the epsilon ball.\n :param bound: The perturbation range for the zonotope. Will be ignored if a certification_schedule is used.\n :param loss_weighting: Weighting factor for the certified loss.\n :param nb_epochs: Number of training epochs.\n :param use_certification_schedule: If to use a training schedule for the certification radius.\n :param certification_schedule: Schedule for gradually increasing the certification radius. Empirical studies\n have shown that this is often required to achieve the best performance.\n Either True to use the default linear scheduler,\n or a class with a .step() method that returns the updated bound every epoch.\n :param batch_size: Size of batches to use for certified training. NB, this will run the data\n sequentially accumulating gradients over the batch size.\n \"\"\"\n from art.estimators.certification.deep_z.pytorch import PytorchDeepZ\n\n if not isinstance(classifier, PytorchDeepZ):\n raise ValueError(\n \"The classifier to pass in should be of type PytorchDeepZ which can be found in \"\n \"art.estimators.certification.deep_z.pytorch.PytorchDeepZ\"\n )\n super().__init__(classifier=classifier)\n self.classifier: \"CERTIFIER_TYPE\"\n self.pgd_params: \"PGDParamDict\"\n\n if pgd_params is None:\n self.pgd_params = {\"eps\": 0.3, \"eps_step\": 0.05, \"max_iter\": 20, \"batch_size\": 128, \"num_random_init\": 1}\n else:\n self.pgd_params = pgd_params\n\n self.nb_epochs = nb_epochs\n self.loss_weighting = loss_weighting\n self.bound = bound\n self.use_certification_schedule = use_certification_schedule\n self.certification_schedule = certification_schedule\n self.batch_size = batch_size\n self.augment_with_pgd = augment_with_pgd\n # Setting up adversary and perform adversarial training:\n self.attack = ProjectedGradientDescent(\n estimator=self.classifier,\n eps=self.pgd_params[\"eps\"],\n eps_step=self.pgd_params[\"eps_step\"],\n max_iter=self.pgd_params[\"max_iter\"],\n num_random_init=self.pgd_params[\"num_random_init\"],\n )\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n certification_loss: Any = \"interval_loss_cce\",\n batch_size: int | None = None,\n nb_epochs: int | None = None,\n training_mode: bool = True,\n scheduler: Any | None = None,\n verbose: bool = True,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param certification_loss: Which certification loss function to use. Either \"interval_loss_cce\"\n or \"max_logit_loss\". By default, will use interval_loss_cce.\n Alternatively, a user can supply their own loss function which takes in as input\n the zonotope predictions of the form () and labels of the form () and returns a\n scalar loss.\n :param batch_size: Size of batches to use for certified training. NB, this will run the data\n sequentially accumulating gradients over the batch size.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: If to display the per-batch statistics while training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n\n if batch_size is None:\n batch_size = self.batch_size\n\n if nb_epochs is not None:\n epochs: int = nb_epochs\n elif self.batch_size is not None:\n epochs = self.batch_size\n else:\n raise ValueError(\"Value of `epochs` not defined.\")\n\n # Set model mode\n self.classifier._model.train(mode=training_mode)\n\n if self.classifier.optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none is provided.\")\n\n y = check_and_transform_label_format(y, nb_classes=self.classifier.nb_classes)\n\n # Apply preprocessing\n y_preprocessed: np.ndarray\n x_preprocessed, y_preprocessed = self.classifier.apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.classifier.reduce_labels(y_preprocessed) # type: ignore\n\n num_batch = int(np.ceil(len(x_preprocessed) / float(self.pgd_params[\"batch_size\"])))\n ind = np.arange(len(x_preprocessed)).tolist()\n\n x_cert = np.copy(x_preprocessed)\n y_cert = np.copy(y_preprocessed)\n\n # Start training\n if self.use_certification_schedule:\n if self.certification_schedule is None:\n certification_schedule_function = DefaultLinearScheduler(\n step_per_epoch=self.bound / epochs, initial_bound=0.0\n )\n else:\n bound = self.bound\n\n for _ in tqdm(range(epochs)):\n epoch_non_cert_loss = []\n epoch_non_cert_acc = []\n\n epoch_cert_loss = []\n epoch_cert_acc = []\n\n if self.use_certification_schedule:\n bound = certification_schedule_function.step()\n\n # Shuffle the examples\n random.shuffle(ind)\n\n # Train for one epoch\n pbar = tqdm(range(num_batch), disable=not verbose)\n\n for m in pbar:\n certified_loss = torch.tensor(0.0).to(self.classifier.device)\n samples_certified = 0\n # Zero the parameter gradients\n self.classifier.optimizer.zero_grad()\n\n # get the certified loss\n x_cert, y_cert = shuffle(x_cert, y_cert)\n for i, (sample, label) in enumerate(zip(x_cert, y_cert)):\n\n self.set_forward_mode(\"concrete\")\n concrete_pred_tensor = self.classifier.model.forward(np.expand_dims(sample, axis=0))\n concrete_pred = int(torch.argmax(concrete_pred_tensor).item())\n\n if self.classifier.concrete_to_zonotope is None:\n if sys.version_info >= (3, 8):\n eps_bound = np.eye(math.prod(self.classifier.input_shape)) * bound\n else:\n eps_bound = np.eye(reduce(lambda x, y: x * y, self.classifier.input_shape)) * bound\n\n processed_sample, eps_bound = self.classifier.pre_process(cent=np.copy(sample), eps=eps_bound)\n processed_sample = np.expand_dims(processed_sample, axis=0)\n else:\n processed_sample, eps_bound = self.classifier.concrete_to_zonotope(sample, bound)\n\n # Perform prediction\n self.set_forward_mode(\"abstract\")\n bias, eps = self.classifier.model.forward(eps=eps_bound, cent=processed_sample)\n bias = torch.unsqueeze(bias, dim=0)\n\n if certification_loss == \"max_logit_loss\":\n certified_loss += self.classifier.max_logit_loss( # type: ignore\n prediction=torch.cat((bias, eps)),\n target=torch.from_numpy(np.expand_dims(label, axis=0)).to(self.classifier.device),\n )\n elif certification_loss == \"interval_loss_cce\":\n certified_loss += self.classifier.interval_loss_cce(\n prediction=torch.cat((bias, eps)),\n target=torch.from_numpy(np.expand_dims(label, axis=0)).to(self.classifier.device),\n )\n else:\n certified_loss += certification_loss(torch.cat((bias, eps)), np.expand_dims(label, axis=0))\n\n certification_results = []\n bias = torch.squeeze(bias).detach().cpu().numpy()\n eps = eps.detach().cpu().numpy()\n\n for k in range(self.classifier.nb_classes):\n if k != concrete_pred:\n cert_via_sub = self.classifier.certify_via_subtraction(\n predicted_class=concrete_pred, class_to_consider=k, cent=bias, eps=eps\n )\n certification_results.append(cert_via_sub)\n\n if all(certification_results) and concrete_pred == label:\n samples_certified += 1\n\n if (i + 1) % batch_size == 0 and i > 0:\n break\n\n certified_loss /= batch_size\n epoch_cert_loss.append(certified_loss)\n epoch_cert_acc.append(np.sum(samples_certified) / batch_size)\n\n # Concrete PGD loss\n i_batch = np.copy(\n x_preprocessed[ind[m * self.pgd_params[\"batch_size\"] : (m + 1) * self.pgd_params[\"batch_size\"]]]\n ).astype(\"float32\")\n o_batch = y_preprocessed[\n ind[m * self.pgd_params[\"batch_size\"] : (m + 1) * self.pgd_params[\"batch_size\"]]\n ]\n\n # Perform prediction\n self.set_forward_mode(\"concrete\")\n\n if self.augment_with_pgd:\n self.attack = ProjectedGradientDescent(\n estimator=self.classifier,\n eps=self.pgd_params[\"eps\"],\n eps_step=self.pgd_params[\"eps_step\"],\n max_iter=self.pgd_params[\"max_iter\"],\n num_random_init=self.pgd_params[\"num_random_init\"],\n )\n i_batch = self.attack.generate(i_batch, y=o_batch)\n\n self.classifier.model.zero_grad()\n model_outputs = self.classifier.model.forward(i_batch)\n\n # Form the loss function\n non_cert_loss = self.classifier.concrete_loss(\n model_outputs, torch.from_numpy(o_batch).to(self.classifier.device)\n )\n epoch_non_cert_loss.append(non_cert_loss)\n epoch_non_cert_acc.append(self.classifier.get_accuracy(model_outputs, o_batch))\n\n if verbose:\n pbar.set_description(\n f\"Bound {bound:.3f}: \"\n f\"Loss {torch.mean(torch.stack(epoch_non_cert_loss)):.2f} \"\n f\"Cert Loss {torch.mean(torch.stack(epoch_cert_loss)):.2f} \"\n f\"Acc {np.mean(epoch_non_cert_acc):.2f} Cert Acc {np.mean(epoch_cert_acc):.2f}\"\n )\n\n loss = certified_loss * self.loss_weighting + non_cert_loss * (1 - self.loss_weighting)\n # Do training\n if self.classifier._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self.classifier.optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self.classifier.optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n if self.classifier.model.forward_mode != \"concrete\":\n raise ValueError(\n \"For normal predictions, the model must be running in concrete mode. If an abstract \"\n \"prediction is wanted then use predict_zonotopes instead\"\n )\n\n return self.classifier.predict(x, **kwargs)\n\n def predict_zonotopes(self, cent: np.ndarray, bound, **kwargs) -> tuple[list[np.ndarray], list[np.ndarray]]:\n \"\"\"\n Perform prediction using the adversarially trained classifier using zonotopes\n\n :param cent: The datapoint, representing the zonotope center.\n :param bound: The perturbation range for the zonotope.\n \"\"\"\n\n if self.classifier.model.forward_mode != \"abstract\":\n raise ValueError(\n \"For zonotope predictions, the model must be running in abstract mode. If a concrete \"\n \"prediction is wanted then use predict instead\"\n )\n\n return self.classifier.predict_zonotopes(cent, bound, **kwargs)\n\n def set_forward_mode(self, mode: str) -> None:\n \"\"\"\n Helper function to set the forward mode of the model\n\n :param mode: either concrete or abstract signifying how to run the forward pass\n \"\"\"\n self.classifier.model.set_forward_mode(mode) # type: ignore\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/dp_instahide_trainer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements DP-InstaHide training method.\n\n| Paper link: https://arxiv.org/abs/2103.02079\n\n| This training method is dependent to the choice of data augmentation and noise parameters. Consequently, framework\n specific implementations are being provided in ART.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport sys\nimport time\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.defences.trainer.trainer import Trainer\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\nif TYPE_CHECKING:\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE, CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass DPInstaHideTrainer(Trainer):\n \"\"\"\n Class performing adversarial training following the DP-InstaHide protocol.\n\n Uses data augmentation methods in conjunction with some type of additive noise.\n\n | Paper link: https://arxiv.org/abs/2103.02079\n \"\"\"\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n augmentations: \"Preprocessor\" | list[\"Preprocessor\"],\n noise: Literal[\"gaussian\", \"laplacian\", \"exponential\"] = \"laplacian\",\n loc: int | float = 0.0,\n scale: int | float = 0.03,\n clip_values: \"CLIP_VALUES_TYPE\" = (0.0, 1.0),\n ):\n \"\"\"\n Create an :class:`.DPInstaHideTrainer` instance.\n\n :param classifier: The model to train using the protocol.\n :param augmentations: The preprocessing data augmentation defence(s) to be applied.\n :param noise: The type of additive noise to use: 'gaussian' | 'laplacian' | 'exponential'.\n :param loc: The location or mean parameter of the distribution to sample.\n :param scale: The scale or standard deviation parameter of the distribution to sample.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n \"\"\"\n from art.defences.preprocessor import Preprocessor\n\n super().__init__(classifier)\n if isinstance(augmentations, Preprocessor):\n self.augmentations = [augmentations]\n else:\n self.augmentations = augmentations\n self.noise = noise\n self.loc = loc\n self.scale = scale\n self.clip_values = clip_values\n\n def _generate_noise(self, x: np.ndarray) -> np.ndarray:\n if self.noise == \"gaussian\":\n noise = np.random.normal(loc=self.loc, scale=self.scale, size=x.shape)\n elif self.noise == \"laplacian\":\n noise = np.random.laplace(loc=self.loc, scale=self.scale, size=x.shape)\n elif self.noise == \"exponential\":\n noise = np.random.exponential(scale=self.scale, size=x.shape)\n else:\n raise ValueError(\"The provided noise type is not supported:\", self.noise)\n\n x_noise = x + noise\n x_noise = np.clip(x_noise, self.clip_values[0], self.clip_values[1])\n\n return x_noise.astype(x.dtype)\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n validation_data: tuple[np.ndarray, np.ndarray] | None = None,\n batch_size: int = 128,\n nb_epochs: int = 20,\n **kwargs,\n ):\n \"\"\"\n Train a model adversarially with the DP-InstaHide protocol.\n See class documentation for more information on the exact procedure.\n\n :param x: Training set.\n :param y: Labels for the training set.\n :param validation_data: Tuple consisting of validation data, (x_val, y_val)\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function\n of the target classifier.\n \"\"\"\n logger.info(\"Performing adversarial training with DP-InstaHide protocol\")\n\n nb_batches = int(np.ceil(len(x) / batch_size))\n ind = np.arange(len(x))\n\n logger.info(\"Adversarial Training DP-InstaHide\")\n\n for i_epoch in trange(nb_epochs, desc=\"DP-InstaHide training epochs\"):\n # shuffle the examples\n np.random.shuffle(ind)\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for batch_id in range(nb_batches):\n # create batch data\n x_batch = x[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n y_batch = y[ind[batch_id * batch_size : min((batch_id + 1) * batch_size, x.shape[0])]]\n\n # augment the data\n x_aug = x_batch.copy()\n y_aug = y_batch.copy()\n for augmentation in self.augmentations:\n x_aug, y_aug = augmentation(x_aug, y_aug)\n\n # apply additive noise\n x_aug = self._generate_noise(x_aug)\n\n # fit batch\n self._classifier.fit(x_aug, y_aug, nb_epochs=1, batch_size=x_aug.shape[0], verbose=False, **kwargs)\n\n # get metrics\n loss = self._classifier.compute_loss(x_aug, y_aug, reduction=\"mean\")\n output = np.argmax(self.predict(x_batch), axis=1)\n acc = np.sum(output == np.argmax(y_batch, axis=1))\n n = len(x_aug)\n\n # update metrics\n train_loss += np.sum(loss)\n train_acc += acc\n train_n += n\n\n train_time = time.time()\n\n # compute accuracy\n if validation_data is not None:\n (x_test, y_test) = validation_data\n output = np.argmax(self.predict(x_test), axis=1)\n test_loss = self._classifier.compute_loss(x_test, y_test, reduction=\"mean\")\n test_acc = np.mean(output == np.argmax(y_test, axis=1))\n logger.info(\n \"epoch: %s time(s): %.1f, loss(tr): %.4f, acc(tr): %.4f, loss(val): %.4f, acc(val): %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n test_loss,\n test_acc,\n )\n else:\n logger.info(\n \"epoch: %s time(s): %.1f, loss: %.4f, acc: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs):\n \"\"\"\n Train a model adversarially with the DP-InstaHide protocol using a data generator.\n See class documentation for more information on the exact procedure.\n\n :param generator: Data generator.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function\n of the target classifier.\n \"\"\"\n logger.info(\"Performing adversarial training with DP-InstaHide protocol\")\n size = generator.size\n batch_size = generator.batch_size\n if size is not None:\n nb_batches = int(np.ceil(size / batch_size))\n else:\n raise ValueError(\"Size is None.\")\n\n logger.info(\"Adversarial Training DP-InstaHide\")\n\n for i_epoch in trange(nb_epochs, desc=\"DP-InstaHide training epochs\"):\n start_time = time.time()\n train_loss = 0.0\n train_acc = 0.0\n train_n = 0.0\n\n for _ in range(nb_batches):\n # create batch data\n x_batch, y_batch = generator.get_batch()\n\n # augment the data\n x_aug = x_batch.copy()\n y_aug = y_batch.copy()\n for augmentation in self.augmentations:\n x_aug, y_aug = augmentation(x_aug, y_aug)\n\n # apply additive noise\n x_aug = self._generate_noise(x_aug)\n\n # fit batch\n self._classifier.fit(x_aug, y_aug, nb_epochs=1, batch_size=x_aug.shape[0], verbose=False, **kwargs)\n\n # get metrics\n loss = self._classifier.compute_loss(x_aug, y_aug, reduction=\"mean\")\n output = np.argmax(self.predict(x_batch), axis=1)\n acc = np.sum(output == np.argmax(y_batch, axis=1))\n n = len(x_aug)\n\n # update metrics\n train_loss += np.sum(loss)\n train_acc += acc\n train_n += n\n\n train_time = time.time()\n\n # compute accuracy\n logger.info(\n \"epoch: %s time(s): %.1f, loss: %.4f, acc: %.4f\",\n i_epoch,\n train_time - start_time,\n train_loss / train_n,\n train_acc / train_n,\n )\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n return self._classifier.predict(x, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/ibp_certified_trainer_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements certified adversarial training following techniques from works such as:\n\n | Paper link: http://proceedings.mlr.press/v80/mirman18b/mirman18b.pdf\n | Paper link: https://arxiv.org/pdf/1810.12715.pdf\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport random\nimport sys\n\nimport numpy as np\nfrom sklearn.utils import shuffle\nfrom tqdm import tqdm\n\nfrom art.defences.trainer.trainer import Trainer\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.utils import check_and_transform_label_format\n\nif sys.version_info >= (3, 8):\n from typing import TypedDict, Any, TYPE_CHECKING\nelse:\n from typing import Any, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from art.utils import IBP_CERTIFIER_TYPE\n\n # if we use python 3.8 or higher use the more informative TypedDict for type hinting\n if sys.version_info >= (3, 8):\n\n class PGDParamDict(TypedDict):\n \"\"\"\n A TypedDict class to define the types in the pgd_params dictionary.\n \"\"\"\n\n eps: float\n eps_step: float\n max_iter: int\n num_random_init: int\n batch_size: int\n\n else:\n PGDParamDict: dict[str, int | float]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DefaultLinearScheduler:\n \"\"\"\n Class implementing a simple linear scheduler to grow the certification radius or change the loss weightings\n \"\"\"\n\n def __init__(\n self, step_per_epoch: float, initial_val: float = 0.0, final_val: float = 1.0, warmup: int = 0\n ) -> None:\n \"\"\"\n Create a .DefaultLinearScheduler instance.\n\n :param step_per_epoch: How much to increase the certification radius every epoch.\n :param initial_val: The initial value.\n :param warmup: If to have an initial warmup period.\n \"\"\"\n self.step_per_epoch = step_per_epoch\n self.val = initial_val\n self.warmup = warmup\n self.final_val = final_val\n self.step_count = 0\n\n def step(self) -> float:\n \"\"\"\n Grow the value by self.step_per_epoch.\n\n :return: The updated scheduler value.\n \"\"\"\n self.step_count += 1\n if self.step_count > self.warmup and self.val < self.final_val:\n self.val += self.step_per_epoch\n self.val = min(self.val, self.final_val)\n return self.val\n\n\nclass AdversarialTrainerCertifiedIBPPyTorch(Trainer):\n \"\"\"\n Class performing certified adversarial training from methods such as\n\n | Paper link: http://proceedings.mlr.press/v80/mirman18b/mirman18b.pdf\n | Paper link: https://arxiv.org/pdf/1810.12715.pdf\n \"\"\"\n\n def __init__(\n self,\n classifier: \"IBP_CERTIFIER_TYPE\",\n nb_epochs: int | None = 20,\n bound: float = 0.1,\n batch_size: int = 32,\n loss_weighting: int | None = None,\n use_certification_schedule: bool = True,\n certification_schedule: Any | None = None,\n use_loss_weighting_schedule: bool = True,\n loss_weighting_schedule: Any | None = None,\n augment_with_pgd: bool = False,\n pgd_params: \"PGDParamDict\" | None = None,\n ) -> None:\n \"\"\"\n Create an :class:`.AdversarialTrainerCertified` instance.\n\n Default values are for MNIST in pixel range 0-1.\n\n :param classifier: Classifier to train adversarially.\n :param pgd_params: A dictionary containing the specific parameters relating to regular PGD training.\n If not provided, we will default to typical MNIST values.\n Otherwise, must contain the following keys:\n\n * *eps*: Maximum perturbation that the attacker can introduce.\n * *eps_step*: Attack step size (input variation) at each iteration.\n * *max_iter*: The maximum number of iterations.\n * *batch_size*: Size of the batch on which adversarial samples are generated.\n * *num_random_init*: Number of random initialisations within the epsilon ball.\n :param loss_weighting: Weighting factor for the certified loss.\n :param bound: The perturbation range for the interval. If the default certification schedule is used\n will be the upper limit.\n :param nb_epochs: Number of training epochs.\n :param use_certification_schedule: If to use a training schedule for the certification radius.\n :param certification_schedule: Schedule for gradually increasing the certification radius. Empirical studies\n have shown that this is often required to achieve the best performance.\n Either True to use the default linear scheduler,\n or a class with a .step() method that returns the updated bound every epoch.\n :param batch_size: Size of batches to use for certified training.\n \"\"\"\n from art.estimators.certification.interval.pytorch import PyTorchIBPClassifier\n\n if not isinstance(classifier, PyTorchIBPClassifier):\n raise ValueError(\n \"The classifier to pass in should be of type PyTorchIBPClassifier which can be found in \"\n \"art.estimators.certification.interval.pytorch.PyTorchIBPClassifier\"\n )\n\n if not use_loss_weighting_schedule and loss_weighting is None:\n raise ValueError(\n \"If a loss weighting schedule is not used then a value for loss_weighting should be supplied.\"\n )\n\n if use_loss_weighting_schedule and loss_weighting is not None:\n raise ValueError(\"Using a loss weighting schedule is incompatible with a fixed loss_weighting.\")\n\n super().__init__(classifier=classifier)\n self.classifier: \"IBP_CERTIFIER_TYPE\"\n self.pgd_params: \"PGDParamDict\"\n self.nb_epochs = nb_epochs\n self.loss_weighting = loss_weighting\n self.bound = bound\n self.use_certification_schedule = use_certification_schedule\n self.certification_schedule = certification_schedule\n\n self.use_loss_weighting_schedule = use_loss_weighting_schedule\n self.loss_weighting_schedule = loss_weighting_schedule\n\n self.batch_size = batch_size\n self.augment_with_pgd = augment_with_pgd\n\n if self.augment_with_pgd:\n if pgd_params is None:\n self.pgd_params = {\n \"eps\": 0.3,\n \"eps_step\": 0.05,\n \"max_iter\": 20,\n \"batch_size\": 128,\n \"num_random_init\": 1,\n }\n else:\n self.pgd_params = pgd_params\n\n # Setting up adversary and perform adversarial training:\n self.attack = ProjectedGradientDescent(\n estimator=self.classifier,\n eps=self.pgd_params[\"eps\"],\n eps_step=self.pgd_params[\"eps_step\"],\n max_iter=self.pgd_params[\"max_iter\"],\n num_random_init=self.pgd_params[\"num_random_init\"],\n )\n\n @staticmethod\n def initialise_default_scheduler(initial_val: float, final_val: float, epochs: int) -> DefaultLinearScheduler:\n \"\"\"\n Create linear schedulers based on default example values.\n\n :param initial_val: Initial value to begin the scheduler from.\n :param final_val: Final value to end the scheduler at.\n :param epochs: Total number of epochs.\n\n :return: A linear scheduler initialised with default example values.\n \"\"\"\n warm_up = int(0.01 * epochs)\n epochs_to_ramp = int(0.30 * epochs) # increasing eps from 0 to eps over 30% of the total epochs\n if epochs_to_ramp == 0:\n epochs_to_ramp = 1\n\n step_in_eps_per_epoch = (final_val - initial_val) / epochs_to_ramp\n\n return DefaultLinearScheduler(\n step_per_epoch=step_in_eps_per_epoch,\n initial_val=initial_val,\n final_val=final_val,\n warmup=warm_up,\n )\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n limits: list[float] | np.ndarray | None = None,\n certification_loss: Any = \"interval_loss_cce\",\n batch_size: int | None = None,\n nb_epochs: int | None = None,\n training_mode: bool = True,\n scheduler: Any | None = None,\n verbose: bool = True,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param limits: Max and min limits on the inputs, limits[0] being the lower bounds and limits[1] being upper\n bounds. Passing None will mean no clipping is applied to the interval abstraction.\n Typical images will have limits of [0.0, 1.0] after normalization.\n :param certification_loss: Which certification loss function to use. Either \"interval_loss_cce\"\n or \"max_logit_loss\". By default, will use interval_loss_cce.\n Alternatively, a user can supply their own loss function which takes in as input\n the interval predictions of the form () and labels of the form () and returns a\n scalar loss.\n :param batch_size: Size of batches to use for certified training. NB, this will run the data\n sequentially accumulating gradients over the batch size.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: If to display the per-batch statistics while training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n\n if batch_size is None:\n batch_size = self.batch_size\n\n if nb_epochs is not None:\n epochs: int = nb_epochs\n else:\n raise ValueError(\"Value of `epochs` not defined.\")\n\n if limits is None:\n raise ValueError(\n \"Please provide values for the clipping limits of the data. \"\n \"Typical images will have limits of [0.0, 1.0]. \"\n )\n\n # Set model mode\n self.classifier._model.train(mode=training_mode)\n\n if self.classifier.optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none is provided.\")\n\n y = check_and_transform_label_format(y, nb_classes=self.classifier.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self.classifier.apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.classifier.reduce_labels(y_preprocessed)\n\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n ind = np.arange(len(x_preprocessed)).tolist()\n\n x_cert = np.copy(x_preprocessed)\n y_cert = np.copy(y_preprocessed)\n\n # Start training\n if self.use_certification_schedule:\n if self.certification_schedule is None:\n # Using typical MNIST values as default.\n self.certification_schedule = self.initialise_default_scheduler(\n initial_val=0.0, final_val=self.bound, epochs=epochs\n )\n else:\n bound = self.bound\n\n if self.use_loss_weighting_schedule:\n if self.loss_weighting_schedule is None:\n self.loss_weighting_schedule = self.initialise_default_scheduler(\n initial_val=0.0, final_val=0.5, epochs=epochs\n )\n elif self.loss_weighting is not None:\n loss_weighting_k = self.loss_weighting\n else:\n raise ValueError(\"Unable to determine loss weighting.\")\n\n for _ in tqdm(range(epochs)):\n if self.use_certification_schedule and self.certification_schedule is not None:\n bound = self.certification_schedule.step()\n if self.use_loss_weighting_schedule and self.loss_weighting_schedule is not None:\n loss_weighting_k = self.loss_weighting_schedule.step()\n\n # Shuffle the examples\n random.shuffle(ind)\n\n # Train for one epoch\n pbar = tqdm(range(num_batch), disable=not verbose)\n x_cert, y_cert = shuffle(x_cert, y_cert)\n epoch_non_cert_loss = []\n non_cert_acc = []\n\n cert_loss = []\n cert_acc = []\n\n for m in pbar:\n x_batch = np.copy(x_cert[batch_size * m : batch_size * (m + 1)])\n y_batch = np.copy(y_cert[batch_size * m : batch_size * (m + 1)])\n\n # Zero the parameter gradients\n self.classifier.optimizer.zero_grad()\n\n if self.classifier.provided_concrete_to_interval:\n processed_x_cert = self.classifier.provided_concrete_to_interval(x_batch, bound, limits=limits)\n else:\n processed_x_cert = self.classifier.concrete_to_interval(x_batch, bound, limits=limits)\n\n # Perform prediction\n self.set_forward_mode(\"abstract\")\n interval_preds = self.classifier.model.forward(processed_x_cert)\n\n if certification_loss == \"interval_loss_cce\":\n certified_loss = self.classifier.interval_loss_cce(\n prediction=interval_preds,\n target=torch.from_numpy(y_batch).to(self.classifier.device),\n )\n else:\n certified_loss = certification_loss(interval_preds, y_batch)\n samples_certified = self.classifier.certify(preds=interval_preds.cpu().detach(), labels=y_batch)\n\n cert_loss.append(certified_loss)\n cert_acc.append(np.sum(samples_certified) / batch_size)\n\n # Concrete PGD loss\n if self.augment_with_pgd:\n i_batch = np.copy(\n x_preprocessed[ind[m * self.pgd_params[\"batch_size\"] : (m + 1) * self.pgd_params[\"batch_size\"]]]\n ).astype(\"float32\")\n o_batch = y_preprocessed[\n ind[m * self.pgd_params[\"batch_size\"] : (m + 1) * self.pgd_params[\"batch_size\"]]\n ]\n # Perform prediction\n self.set_forward_mode(\"attack\")\n self.attack = ProjectedGradientDescent(\n estimator=self.classifier,\n eps=self.pgd_params[\"eps\"],\n eps_step=self.pgd_params[\"eps_step\"],\n max_iter=self.pgd_params[\"max_iter\"],\n num_random_init=self.pgd_params[\"num_random_init\"],\n )\n i_batch = self.attack.generate(i_batch, y=o_batch) # type: ignore\n self.classifier.model.zero_grad()\n else:\n i_batch = np.copy(x_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]).astype(\"float32\")\n o_batch = y_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]\n self.set_forward_mode(\"concrete\")\n\n model_outputs = self.classifier.model.forward(i_batch)\n acc = self.classifier.get_accuracy(model_outputs, o_batch)\n\n # Form the loss function\n non_cert_loss = self.classifier.concrete_loss(\n model_outputs, torch.from_numpy(o_batch).to(self.classifier.device)\n )\n epoch_non_cert_loss.append(non_cert_loss)\n non_cert_acc.append(acc)\n\n loss = certified_loss * loss_weighting_k + non_cert_loss * (1 - loss_weighting_k)\n # Do training\n if self.classifier._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self.classifier.optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self.classifier.optimizer.step()\n self.classifier.re_convert()\n\n if verbose:\n pbar.set_description(\n f\"Bound {bound:.2f}: \"\n f\"Loss {torch.mean(torch.stack(epoch_non_cert_loss)):.2f} \"\n f\"Cert Loss {torch.mean(torch.stack(cert_loss)):.2f} \"\n f\"Acc {np.mean(non_cert_acc):.2f} Cert Acc {np.mean(cert_acc):.2f} \"\n f\"l_weight {loss_weighting_k:.2f} lr {self.classifier.optimizer.param_groups[0]['lr']}\"\n )\n\n if scheduler is not None:\n scheduler.step()\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier.\n\n :param x: Input samples.\n :param kwargs: Other parameters to be passed on to the `predict` function of the classifier.\n :return: Predictions for test set.\n \"\"\"\n if self.classifier.model.forward_mode != \"concrete\":\n raise ValueError(\n \"For normal predictions, the model must be running in concrete mode. If an abstract \"\n \"prediction is wanted then use predict_interval instead\"\n )\n\n return self.classifier.predict(x, **kwargs)\n\n def predict_intervals(\n self,\n x: np.ndarray,\n is_interval: bool = False,\n bounds: float | list[float] | np.ndarray | None = None,\n limits: list[float] | np.ndarray | None = None,\n batch_size: int = 128,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Perform prediction using the adversarially trained classifier using zonotopes\n\n :param x: The datapoint, either:\n\n 1. In the interval format of x[batch_size, 2, feature_1, feature_2, ...]\n where axis=1 corresponds to the [lower, upper] bounds.\n\n 2. Or in regular concrete form, in which case the bounds/limits need to be supplied.\n :param is_interval: if the datapoint is already in the correct interval format.\n :param bounds: The perturbation range.\n :param limits: The clipping to apply to the interval data.\n :param batch_size: batch size to use when looping through the data\n \"\"\"\n\n if self.classifier.model.forward_mode != \"abstract\":\n raise ValueError(\n \"For interval predictions, the model must be running in abstract mode. If a concrete \"\n \"prediction is wanted then use predict instead\"\n )\n return self.classifier.predict_intervals(x, is_interval, bounds, limits, batch_size, **kwargs)\n\n def set_forward_mode(self, mode: str) -> None:\n \"\"\"\n Helper function to set the forward mode of the model\n\n :param mode: either concrete or abstract signifying how to run the forward pass\n \"\"\"\n self.classifier.model.set_forward_mode(mode) # type: ignore\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/trainer/trainer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for defences that adversarially train models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nclass Trainer(abc.ABC):\n \"\"\"\n Abstract base class for training defences.\n \"\"\"\n\n def __init__(self, classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\") -> None:\n \"\"\"\n Create a adversarial training object\n \"\"\"\n self._classifier = classifier\n\n @abc.abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Train the model.\n\n :param x: Training data.\n :param y: Labels for the training data.\n :param kwargs: Other parameters.\n \"\"\"\n raise NotImplementedError\n\n @property\n def classifier(self) -> \"CLASSIFIER_LOSS_GRADIENTS_TYPE\":\n \"\"\"\n Access function to get the classifier.\n\n :return: The classifier.\n \"\"\"\n return self._classifier\n\n def get_classifier(self) -> \"CLASSIFIER_LOSS_GRADIENTS_TYPE\":\n \"\"\"\n Return the classifier trained via adversarial training.\n\n :return: The classifier.\n \"\"\"\n return self._classifier\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing transformer-based defences against adversarial attacks.\n\"\"\"\n\nfrom art.defences.transformer.transformer import Transformer\n\nfrom art.defences.transformer import evasion\nfrom art.defences.transformer import poisoning\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/transformer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for defences that transform a classifier into a more robust classifier.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\n\nclass Transformer(abc.ABC):\n \"\"\"\n Abstract base class for transformation defences.\n \"\"\"\n\n params: list[str] = []\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\") -> None:\n \"\"\"\n Create a transformation object.\n\n :param classifier: A trained classifier.\n \"\"\"\n self.classifier = classifier\n self._is_fitted = False\n\n @property\n def is_fitted(self) -> bool:\n \"\"\"\n Return the state of the transformation object.\n\n :return: `True` if the transformation model has been fitted (if this applies).\n \"\"\"\n return self._is_fitted\n\n def get_classifier(self) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Get the internal classifier.\n\n :return: The internal classifier.\n \"\"\"\n return self.classifier\n\n @abc.abstractmethod\n def __call__(self, x: np.ndarray, transformed_classifier: \"CLASSIFIER_TYPE\") -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Perform the transformation defence and return a robuster classifier.\n\n :param x: Dataset for training the transformed classifier.\n :param transformed_classifier: A classifier to be transformed for increased robustness.\n :return: The transformed classifier.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> None:\n \"\"\"\n Fit the parameters of the transformer if it has any.\n\n :param x: Training set to fit the transformer.\n :param y: Labels for the training set.\n :param kwargs: Other parameters.\n \"\"\"\n raise NotImplementedError\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take in a dictionary of parameters and apply checks before saving them as attributes.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.params:\n setattr(self, key, value)\n self._check_params()\n\n def _check_params(self) -> None:\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/evasion/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing transformer-based defences against evasion attacks.\n\"\"\"\n\nfrom art.defences.transformer.evasion.defensive_distillation import DefensiveDistillation\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/evasion/defensive_distillation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the transforming defence mechanism of defensive distillation.\n\n| Paper link: https://arxiv.org/abs/1511.04508\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.transformer.transformer import Transformer\nfrom art.utils import is_probability\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass DefensiveDistillation(Transformer):\n \"\"\"\n Implement the defensive distillation mechanism.\n\n | Paper link: https://arxiv.org/abs/1511.04508\n \"\"\"\n\n params = [\"batch_size\", \"nb_epochs\"]\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\", batch_size: int = 128, nb_epochs: int = 10) -> None:\n \"\"\"\n Create an instance of the defensive distillation defence.\n\n :param classifier: A trained classifier.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n \"\"\"\n super().__init__(classifier=classifier)\n self._is_fitted = True\n self.batch_size = batch_size\n self.nb_epochs = nb_epochs\n self._check_params()\n\n def __call__(self, x: np.ndarray, transformed_classifier: \"CLASSIFIER_TYPE\") -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Perform the defensive distillation defence mechanism and return a robuster classifier.\n\n :param x: Dataset for training the transformed classifier.\n :param transformed_classifier: A classifier to be transformed for increased robustness. Note that, the\n objective loss function used for fitting inside the input transformed_classifier must support soft labels,\n i.e. probability labels.\n :return: The transformed classifier.\n \"\"\"\n # Check if the trained classifier produces probability outputs\n preds = self.classifier.predict(x=x, batch_size=self.batch_size)\n are_probability = [is_probability(y) for y in preds]\n all_probability = np.sum(are_probability) == preds.shape[0]\n\n if not all_probability:\n raise ValueError(\"The input trained classifier do not produce probability outputs.\")\n\n # Check if the transformed classifier produces probability outputs\n transformed_preds = transformed_classifier.predict(x=x, batch_size=self.batch_size)\n are_probability = [is_probability(y) for y in transformed_preds]\n all_probability = np.sum(are_probability) == transformed_preds.shape[0]\n\n if not all_probability:\n raise ValueError(\"The input transformed classifier do not produce probability outputs.\")\n\n # Train the transformed classifier with soft labels\n transformed_classifier.fit(x=x, y=preds, batch_size=self.batch_size, nb_epochs=self.nb_epochs)\n\n return transformed_classifier\n\n def fit(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> None:\n \"\"\"\n No parameters to learn for this method; do nothing.\n \"\"\"\n pass\n\n def _check_params(self) -> None:\n if not isinstance(self.batch_size, int) or self.batch_size <= 0:\n raise ValueError(\"The size of batches must be a positive integer.\")\n\n if not isinstance(self.nb_epochs, int) or self.nb_epochs <= 0:\n raise ValueError(\"The number of epochs must be a positive integer.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/poisoning/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule implementing transformer-based defences against poisoning attacks.\n\"\"\"\n\nfrom art.defences.transformer.poisoning.neural_cleanse import NeuralCleanse\nfrom art.defences.transformer.poisoning.strip import STRIP\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/poisoning/neural_cleanse.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Neural Cleanse (Wang et. al. 2019)\n\n| Paper link: http://people.cs.uchicago.edu/~ravenben/publications/abstracts/backdoor-sp19.html\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.transformer.transformer import Transformer\nfrom art.estimators.poison_mitigation.neural_cleanse import KerasNeuralCleanse\nfrom art.estimators.classification.keras import KerasClassifier\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass NeuralCleanse(Transformer):\n \"\"\"\n Implementation of methods in Neural Cleanse: Identifying and Mitigating Backdoor Attacks in Neural Networks.\n Wang et al. (2019).\n\n | Paper link: https://people.cs.uchicago.edu/~ravenben/publications/pdf/backdoor-sp19.pdf\n \"\"\"\n\n params = [\n \"steps\",\n \"init_cost\",\n \"norm\",\n \"learning_rate\",\n \"attack_success_threshold\",\n \"patience\",\n \"early_stop\",\n \"early_stop_threshold\",\n \"early_stop_patience\",\n \"cost_multiplier\",\n \"batch_size\",\n ]\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\") -> None:\n \"\"\"\n Create an instance of the neural cleanse defence.\n\n :param classifier: A trained classifier.\n \"\"\"\n super().__init__(classifier=classifier)\n self._is_fitted = False\n self._check_params()\n\n def __call__( # type: ignore\n self,\n transformed_classifier: \"CLASSIFIER_TYPE\",\n steps: int = 1000,\n init_cost: float = 1e-3,\n norm: int | float = 2,\n learning_rate: float = 0.1,\n attack_success_threshold: float = 0.99,\n patience: int = 5,\n early_stop: bool = True,\n early_stop_threshold: float = 0.99,\n early_stop_patience: int = 10,\n cost_multiplier: float = 1.5,\n batch_size: int = 32,\n ) -> KerasNeuralCleanse:\n \"\"\"\n Returns a new classifier with implementation of methods in Neural Cleanse: Identifying and Mitigating Backdoor\n Attacks in Neural Networks. Wang et al. (2019).\n\n Namely, the new classifier has a new method mitigate(). This can also affect the predict() function.\n\n | Paper link: https://people.cs.uchicago.edu/~ravenben/publications/pdf/backdoor-sp19.pdf\n\n :param transformed_classifier: An ART classifier\n :param steps: The maximum number of steps to run the Neural Cleanse optimization\n :param init_cost: The initial value for the cost tensor in the Neural Cleanse optimization\n :param norm: The norm to use for the Neural Cleanse optimization, can be 1, 2, or np.inf\n :param learning_rate: The learning rate for the Neural Cleanse optimization\n :param attack_success_threshold: The threshold at which the generated backdoor is successful enough to stop the\n Neural Cleanse optimization\n :param patience: How long to wait for changing the cost multiplier in the Neural Cleanse optimization\n :param early_stop: Whether to allow early stopping in the Neural Cleanse optimization\n :param early_stop_threshold: How close values need to come to max value to start counting early stop\n :param early_stop_patience: How long to wait to determine early stopping in the Neural Cleanse optimization\n :param cost_multiplier: How much to change the cost in the Neural Cleanse optimization\n :param batch_size: The batch size for optimizations in the Neural Cleanse optimization\n \"\"\"\n transformed_classifier = KerasNeuralCleanse(\n model=transformed_classifier.model,\n steps=steps,\n init_cost=init_cost,\n norm=norm,\n learning_rate=learning_rate,\n attack_success_threshold=attack_success_threshold,\n patience=patience,\n early_stop=early_stop,\n early_stop_threshold=early_stop_threshold,\n early_stop_patience=early_stop_patience,\n cost_multiplier=cost_multiplier,\n batch_size=batch_size,\n )\n return transformed_classifier\n\n def fit(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> None:\n \"\"\"\n No parameters to learn for this method; do nothing.\n \"\"\"\n raise NotImplementedError\n\n def _check_params(self) -> None:\n if not isinstance(self.classifier, KerasClassifier):\n raise NotImplementedError(\"Only Keras classifiers are supported for this defence.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/defences/transformer/poisoning/strip.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements STRIP: A Defence Against Trojan Attacks on Deep Neural Networks.\n\n| Paper link: https://arxiv.org/abs/1902.06531\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.defences.transformer.transformer import Transformer\nfrom art.estimators.poison_mitigation.strip import STRIPMixin\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass STRIP(Transformer):\n \"\"\"\n Implementation of STRIP: A Defence Against Trojan Attacks on Deep Neural Networks (Gao et. al. 2020)\n\n | Paper link: https://arxiv.org/abs/1902.06531\n \"\"\"\n\n params = [\n \"num_samples\",\n \"false_acceptance_rate\",\n ]\n\n def __init__(self, classifier: \"CLASSIFIER_TYPE\"):\n \"\"\"\n Create an instance of the neural cleanse defence.\n\n :param classifier: A trained classifier.\n \"\"\"\n super().__init__(classifier=classifier)\n self._check_params()\n\n def __call__( # type: ignore\n self,\n num_samples: int = 20,\n false_acceptance_rate: float = 0.01,\n ) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n Create a STRIP defense\n\n :param num_samples: The number of samples to use to test entropy at inference time\n :param false_acceptance_rate: The percentage of acceptable false acceptance\n \"\"\"\n base_cls = self.classifier.__class__\n base_cls_name = self.classifier.__class__.__name__\n self.classifier.__class__ = type(\n base_cls_name,\n (STRIPMixin, base_cls),\n dict(\n num_samples=num_samples, false_acceptance_rate=false_acceptance_rate, predict_fn=self.classifier.predict\n ),\n )\n\n return self.classifier # type: ignore\n\n def fit(self, x: np.ndarray, y: np.ndarray | None = None, **kwargs) -> None:\n \"\"\"\n No parameters to learn for this method; do nothing.\n \"\"\"\n raise NotImplementedError\n\n def _check_params(self) -> None:\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains the Estimator API.\n\"\"\"\n\nfrom art.estimators.estimator import (\n BaseEstimator,\n LossGradientsMixin,\n NeuralNetworkMixin,\n DecisionTreeMixin,\n)\n\nfrom art.estimators.keras import KerasEstimator\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.estimators.scikitlearn import ScikitlearnEstimator\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\n\nfrom art.estimators import certification\nfrom art.estimators import classification\nfrom art.estimators import generation\nfrom art.estimators import object_detection\nfrom art.estimators import poison_mitigation\nfrom art.estimators import regression\nfrom art.estimators import speech_recognition\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/estimator.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements abstract base and mixin classes for estimators in ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nif TYPE_CHECKING:\n # pylint: disable=cyclic-import\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE, ESTIMATOR_TYPE\n from art.data_generators import DataGenerator\n from art.metrics.verification_decisions_trees import Tree\n from art.defences.postprocessor.postprocessor import Postprocessor\n from art.defences.preprocessor.preprocessor import Preprocessor\n\n\nclass BaseEstimator(ABC):\n \"\"\"\n The abstract base class `BaseEstimator` defines the basic requirements of an estimator in ART. The BaseEstimator is\n the highest abstraction of a machine learning model in ART.\n \"\"\"\n\n estimator_params = [\n \"model\",\n \"clip_values\",\n \"preprocessing_defences\",\n \"postprocessing_defences\",\n \"preprocessing\",\n ]\n\n def __init__(\n self,\n model,\n clip_values: \"CLIP_VALUES_TYPE\" | None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" | \"Preprocessor\" = (0.0, 1.0),\n ):\n \"\"\"\n Initialize a `BaseEstimator` object.\n\n :param model: The model\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the estimator.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the estimator.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input and the results will be\n divided by the second value.\n \"\"\"\n self._model = model\n self._clip_values = clip_values\n\n self.preprocessing = self._set_preprocessing(preprocessing)\n self.preprocessing_defences = self._set_preprocessing_defences(preprocessing_defences)\n self.postprocessing_defences = self._set_postprocessing_defences(postprocessing_defences)\n self.preprocessing_operations: list[\"Preprocessor\"] = []\n BaseEstimator._update_preprocessing_operations(self)\n BaseEstimator._check_params(self)\n\n def _update_preprocessing_operations(self):\n from art.defences.preprocessor.preprocessor import Preprocessor\n\n self.preprocessing_operations.clear()\n\n if self.preprocessing_defences is None:\n pass\n elif isinstance(self.preprocessing_defences, Preprocessor):\n self.preprocessing_operations.append(self.preprocessing_defences)\n else:\n self.preprocessing_operations += self.preprocessing_defences\n\n if self.preprocessing is None:\n pass\n elif isinstance(self.preprocessing, tuple):\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n\n self.preprocessing_operations.append(\n StandardisationMeanStd(mean=self.preprocessing[0], std=self.preprocessing[1])\n )\n elif isinstance(self.preprocessing, Preprocessor):\n self.preprocessing_operations.append(self.preprocessing)\n else: # pragma: no cover\n raise ValueError(\"Preprocessing argument not recognised.\")\n\n @staticmethod\n def _set_preprocessing(preprocessing: \"PREPROCESSING_TYPE\" | \"Preprocessor\" | None) -> \"Preprocessor\" | None:\n from art.defences.preprocessor.preprocessor import Preprocessor\n\n if preprocessing is None:\n return None\n if isinstance(preprocessing, tuple):\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n\n return StandardisationMeanStd(mean=preprocessing[0], std=preprocessing[1]) # type: ignore\n if isinstance(preprocessing, Preprocessor):\n return preprocessing\n\n raise ValueError(\"Preprocessing argument not recognised.\") # pragma: no cover\n\n @staticmethod\n def _set_preprocessing_defences(\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None,\n ) -> list[\"Preprocessor\"] | None:\n from art.defences.preprocessor.preprocessor import Preprocessor\n\n if isinstance(preprocessing_defences, Preprocessor):\n return [preprocessing_defences]\n\n return preprocessing_defences\n\n @staticmethod\n def _set_postprocessing_defences(\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None,\n ) -> list[\"Postprocessor\"] | None:\n from art.defences.postprocessor.postprocessor import Postprocessor\n\n if isinstance(postprocessing_defences, Postprocessor):\n return [postprocessing_defences]\n\n return postprocessing_defences\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take a dictionary of parameters and apply checks before setting them as attributes.\n\n :param kwargs: A dictionary of attributes.\n \"\"\"\n for key, value in kwargs.items():\n if key in self.estimator_params:\n if hasattr(type(self), key) and isinstance(getattr(type(self), key), property):\n if getattr(type(self), key).fset is not None:\n setattr(self, key, value)\n else:\n setattr(self, \"_\" + key, value)\n elif hasattr(self, \"_\" + key):\n setattr(self, \"_\" + key, value)\n else:\n if key == \"preprocessing\":\n setattr(self, key, self._set_preprocessing(value))\n elif key == \"preprocessing_defences\":\n setattr(self, key, self._set_preprocessing_defences(value))\n elif key == \"postprocessing_defences\":\n setattr(self, key, self._set_postprocessing_defences(value))\n else:\n setattr(self, key, value)\n else: # pragma: no cover\n raise ValueError(f\"Unexpected parameter `{key}` found in kwargs.\")\n self._update_preprocessing_operations()\n self._check_params()\n\n def get_params(self) -> dict[str, Any]:\n \"\"\"\n Get all parameters and their values of this estimator.\n\n :return: A dictionary of string parameter names to their value.\n \"\"\"\n params = {}\n for key in self.estimator_params:\n params[key] = getattr(self, key)\n return params\n\n def clone_for_refitting(self) -> \"ESTIMATOR_TYPE\":\n \"\"\"\n Clone estimator for refitting.\n \"\"\"\n raise NotImplementedError\n\n def _check_params(self) -> None:\n from art.config import ART_NUMPY_DTYPE\n from art.defences.postprocessor.postprocessor import Postprocessor\n from art.defences.preprocessor.preprocessor import Preprocessor\n\n if self._clip_values is not None:\n if len(self._clip_values) != 2: # pragma: no cover\n raise ValueError(\n \"`clip_values` should be a tuple of 2 floats or arrays containing the allowed data range.\"\n )\n if np.array(self._clip_values[0] >= self._clip_values[1]).any(): # pragma: no cover\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n if isinstance(self._clip_values, np.ndarray):\n self._clip_values = self._clip_values.astype(ART_NUMPY_DTYPE)\n else:\n self._clip_values = np.array(self._clip_values, dtype=ART_NUMPY_DTYPE) # type: ignore\n\n if isinstance(self.preprocessing_operations, list):\n for preprocess in self.preprocessing_operations:\n if not isinstance(preprocess, Preprocessor): # pragma: no cover\n raise ValueError(\n \"All preprocessing defences have to be instance of \"\n \"art.defences.preprocessor.preprocessor.Preprocessor.\"\n )\n else: # pragma: no cover\n raise ValueError(\n \"All preprocessing defences have to be instance of \"\n \"art.defences.preprocessor.preprocessor.Preprocessor.\"\n )\n\n if isinstance(self.postprocessing_defences, list):\n for postproc_defence in self.postprocessing_defences:\n if not isinstance(postproc_defence, Postprocessor): # pragma: no cover\n raise ValueError(\n \"All postprocessing defences have to be instance of \"\n \"art.defences.postprocessor.postprocessor.Postprocessor.\"\n )\n elif self.postprocessing_defences is None:\n pass\n else: # pragma: no cover\n raise ValueError(\n \"All postprocessing defences have to be instance of \"\n \"art.defences.postprocessor.postprocessor.Postprocessor.\"\n )\n\n @abstractmethod\n def predict(self, x, **kwargs) -> Any:\n \"\"\"\n Perform prediction of the estimator for input `x`.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :return: Predictions by the model.\n :rtype: Format as produced by the `model`\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def fit(self, x, y, **kwargs) -> None:\n \"\"\"\n Fit the estimator using the training data `(x, y)`.\n\n :param x: Training data.\n :type x: Format as expected by the `model`\n :param y: Target values.\n :type y: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n @property\n def model(self):\n \"\"\"\n Return the model.\n\n :return: The model.\n \"\"\"\n return self._model\n\n @property\n @abstractmethod\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n raise NotImplementedError\n\n @property\n def clip_values(self) -> \"CLIP_VALUES_TYPE\" | None:\n \"\"\"\n Return the clip values of the input samples.\n\n :return: Clip values (min, max).\n \"\"\"\n return self._clip_values\n\n def _apply_preprocessing(self, x, y, fit: bool) -> tuple[Any, Any]:\n \"\"\"\n Apply all defences and preprocessing operations on the inputs `x` and `y`. This function has to be applied to\n all raw inputs `x` and `y` provided to the estimator.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :param y: Target values.\n :type y: Format as expected by the `model` or `None`\n :param fit: `True` if the defences are applied during training.\n :return: Tuple of `x` and `y` after applying the defences and standardisation.\n :rtype: Format as expected by the `model`\n \"\"\"\n if self.preprocessing_operations:\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x, y = preprocess(x, y)\n else:\n if preprocess.apply_predict:\n x, y = preprocess(x, y)\n\n return x, y\n\n def _apply_postprocessing(self, preds, fit: bool) -> np.ndarray:\n \"\"\"\n Apply all postprocessing defences on model predictions.\n\n :param preds: model output to be post-processed.\n :type preds: Format as expected by the `model`\n :param fit: `True` if the defences are applied during training.\n :return: Post-processed model predictions.\n \"\"\"\n post_preds = preds.copy()\n if self.postprocessing_defences is not None:\n for defence in self.postprocessing_defences:\n if fit:\n if defence.apply_fit:\n post_preds = defence(post_preds)\n else:\n if defence.apply_predict:\n post_preds = defence(post_preds)\n\n return post_preds\n\n def compute_loss(self, x: np.ndarray, y: Any, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the estimator for samples `x`.\n\n :param x: Input samples.\n :param y: Target values.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n def compute_loss_from_predictions(self, pred: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the estimator for predictions `pred`.\n\n :param pred: Model predictions.\n :param y: Target values.\n :return: Loss values.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n class_name = self.__class__.__name__\n attributes = {}\n for k, value in self.__dict__.items():\n k = k[1:] if k[0] == \"_\" else k\n attributes[k] = value\n attributes = [f\"{k}={v}\" for k, v in attributes.items()]\n repr_string = class_name + \"(\" + \", \".join(attributes) + \")\"\n return repr_string\n\n\nclass LossGradientsMixin(ABC):\n \"\"\"\n Mixin abstract base class defining additional functionality for estimators providing loss gradients. An estimator\n of this type can be combined with white-box attacks. This mixin abstract base class has to be mixed in with\n class `BaseEstimator`.\n \"\"\"\n\n @abstractmethod\n def loss_gradient(self, x, y, **kwargs):\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :param y: Target values.\n :type y: Format as expected by the `model`\n :return: Loss gradients w.r.t. `x` in the same format as `x`.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n def _apply_preprocessing_gradient(self, x, gradients, fit=False):\n \"\"\"\n Apply the backward pass to the gradients through all normalization and preprocessing defences that have been\n applied to `x` and `y` in the forward pass. This function has to be applied to all gradients w.r.t. `x`\n calculated by the estimator.\n\n :param x: Features, where first dimension is the number of samples.\n :type x: Format as expected by the `model`\n :param gradients: Gradients before backward pass through normalization and preprocessing defences.\n :type gradients: Format as expected by the `model`\n :return: Gradients after backward pass through normalization and preprocessing defences.\n :rtype: Format as expected by the `model`\n \"\"\"\n if self.preprocessing_operations:\n for preprocess in self.preprocessing_operations[::-1]:\n if fit:\n if preprocess.apply_fit:\n gradients = preprocess.estimate_gradient(x, gradients)\n else:\n if preprocess.apply_predict:\n gradients = preprocess.estimate_gradient(x, gradients)\n\n return gradients\n\n\nclass NeuralNetworkMixin(ABC):\n \"\"\"\n Mixin abstract base class defining additional functionality required for neural network estimators. This base class\n has to be mixed in with class `BaseEstimator`.\n \"\"\"\n\n estimator_params = [\"channels_first\"]\n\n def __init__(self, channels_first: bool, **kwargs) -> None:\n \"\"\"\n Initialize a neural network attributes.\n\n :param channels_first: Set channels first or last.\n \"\"\"\n self._channels_first: bool = channels_first\n super().__init__(**kwargs) # type: ignore\n\n @abstractmethod\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n \"\"\"\n Perform prediction of the neural network for samples `x`.\n\n :param x: Input samples.\n :param batch_size: Batch size.\n :return: Predictions.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the model of the estimator on the training data `x` and `y`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param batch_size: Batch size.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n raise NotImplementedError\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the estimator using a `generator` yielding training batches. Implementations can\n provide framework-specific versions of this function to speed-up computation.\n\n :param generator: Batch generator providing `(x, y)` for each epoch.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n from art.data_generators import DataGenerator\n\n if not isinstance(generator, DataGenerator):\n raise ValueError(\n f\"Expected instance of `DataGenerator` for `fit_generator`, got {type(generator)} instead.\"\n )\n\n for i in range(nb_epochs):\n for _ in trange(\n int(generator.size / generator.batch_size), desc=f\"Epoch {i + 1}/{nb_epochs}\" # type: ignore\n ):\n x, y = generator.get_batch()\n\n # Fit for current batch\n self.fit(x, y, nb_epochs=1, batch_size=generator.batch_size, **kwargs)\n\n @abstractmethod\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n \"\"\"\n Return the output of a specific layer for samples `x` where `layer` is the index of the layer between 0 and\n `nb_layers - 1 or the name of the layer. The number of layers can be determined by counting the results\n returned by calling `layer_names`.\n\n :param x: Samples\n :param layer: Index or name of the layer.\n :param batch_size: Batch size.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def channels_first(self) -> bool:\n \"\"\"\n :return: Boolean to indicate index of the color channels in the sample `x`.\n \"\"\"\n return self._channels_first\n\n @property\n def layer_names(self) -> list[str] | None:\n \"\"\"\n Return the names of the hidden layers in the model, if applicable.\n\n :return: The names of the hidden layers in the model, input and output layers are ignored.\n\n .. warning:: `layer_names` tries to infer the internal structure of the model.\n This feature comes with no guarantees on the correctness of the result.\n The intended order of the layers tries to match their order in the model, but this is not\n guaranteed either.\n \"\"\"\n return self._layer_names # type: ignore\n\n def __repr__(self):\n name = self.__class__.__name__\n\n attributes = {}\n for k, value in self.__dict__.items():\n k = k[1:] if k[0] == \"_\" else k\n attributes[k] = value\n attrs = [f\"{k}={v}\" for k, v in attributes.items()]\n repr_ = name + \"(\" + \", \".join(attrs) + \")\"\n\n return repr_\n\n\nclass DecisionTreeMixin(ABC):\n \"\"\"\n Mixin abstract base class defining additional functionality for decision-tree-based estimators. This mixin abstract\n base class has to be mixed in with class `BaseEstimator`.\n \"\"\"\n\n @abstractmethod\n def get_trees(self) -> list[\"Tree\"]:\n \"\"\"\n Get the decision trees.\n\n :return: A list of decision trees.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/keras.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract estimator `KerasEstimator` for Keras models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.estimator import (\n BaseEstimator,\n NeuralNetworkMixin,\n LossGradientsMixin,\n)\n\nlogger = logging.getLogger(__name__)\n\nif TYPE_CHECKING:\n from art.utils import KERAS_ESTIMATOR_TYPE\n\n\nclass KerasEstimator(NeuralNetworkMixin, LossGradientsMixin, BaseEstimator):\n \"\"\"\n Estimator class for Keras models.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + NeuralNetworkMixin.estimator_params\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n \"\"\"\n Perform prediction of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param batch_size: Batch size.\n :return: Predictions.\n :rtype: Format as expected by the `model`\n \"\"\"\n return NeuralNetworkMixin.predict(self, x, batch_size=batch_size, **kwargs)\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the model of the estimator on the training data `x` and `y`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param batch_size: Batch size.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n NeuralNetworkMixin.fit(self, x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n def clone_for_refitting(\n self,\n ) -> \"KERAS_ESTIMATOR_TYPE\":\n \"\"\"\n Create a copy of the estimator that can be refit from scratch. Will inherit same architecture, optimizer and\n initialization as cloned model, but without weights.\n\n :return: new estimator\n \"\"\"\n import tensorflow as tf\n\n try:\n # only works for functionally defined models\n model = tf.keras.models.clone_model(self.model, input_tensors=self.model.inputs)\n except ValueError as error:\n raise ValueError(\"Cannot clone custom models\") from error\n\n optimizer = self.model.optimizer\n # reset optimizer variables\n for var in optimizer.variables():\n var.assign(tf.zeros_like(var))\n\n loss_weights = None\n weighted_metrics = None\n if self.model.compiled_loss:\n loss_weights = self.model.compiled_loss._loss_weights\n if self.model.compiled_metrics:\n weighted_metrics = self.model.compiled_metrics._weighted_metrics\n\n model.compile(\n optimizer=optimizer,\n loss=self.model.loss,\n metrics=[m.name for m in self.model.metrics], # Need to copy metrics this way for keras\n loss_weights=loss_weights,\n weighted_metrics=weighted_metrics,\n run_eagerly=self.model.run_eagerly,\n )\n\n clone = type(self)(model=model, channels_first=self.channels_first)\n params = self.get_params()\n del params[\"model\"]\n clone.set_params(**params)\n return clone\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract estimator `PyTorchEstimator` for PyTorch models.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING, Any\n\nimport numpy as np\n\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin, NeuralNetworkMixin\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchEstimator(NeuralNetworkMixin, LossGradientsMixin, BaseEstimator):\n \"\"\"\n Estimator class for PyTorch models.\n \"\"\"\n\n estimator_params = (\n BaseEstimator.estimator_params\n + NeuralNetworkMixin.estimator_params\n + [\n \"device_type\",\n ]\n )\n\n def __init__(self, device_type: str = \"gpu\", **kwargs) -> None:\n \"\"\"\n Estimator class for PyTorch models.\n\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n import torch\n\n preprocessing = kwargs.get(\"preprocessing\")\n if isinstance(preprocessing, tuple):\n from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n kwargs[\"preprocessing\"] = StandardisationMeanStdPyTorch(\n mean=preprocessing[0], std=preprocessing[1], device_type=device_type\n )\n\n super().__init__(**kwargs)\n\n self._device_type = device_type\n\n # Set device\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self._device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self._device = torch.device(f\"cuda:{cuda_idx}\")\n\n PyTorchEstimator._check_params(self)\n\n @property\n def device_type(self) -> str:\n \"\"\"\n Return the type of device on which the estimator is run.\n\n :return: Type of device on which the estimator is run, either `gpu` or `cpu`.\n \"\"\"\n return self._device_type # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n \"\"\"\n Perform prediction of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param batch_size: Batch size.\n :return: Predictions.\n :rtype: Format as expected by the `model`\n \"\"\"\n return NeuralNetworkMixin.predict(self, x, batch_size=batch_size, **kwargs)\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the model of the estimator on the training data `x` and `y`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param batch_size: Batch size.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n NeuralNetworkMixin.fit(self, x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take a dictionary of parameters and apply checks before setting them as attributes.\n\n :param kwargs: A dictionary of attributes.\n \"\"\"\n super().set_params(**kwargs)\n self._check_params()\n\n def _check_params(self) -> None:\n from art.defences.preprocessor.preprocessor import PreprocessorPyTorch\n\n super()._check_params()\n self.all_framework_preprocessing = all(\n (isinstance(p, PreprocessorPyTorch) for p in self.preprocessing_operations)\n )\n\n def _apply_preprocessing(self, x, y, fit: bool = False, no_grad=True) -> tuple[Any, Any]:\n \"\"\"\n Apply all preprocessing defences of the estimator on the raw inputs `x` and `y`. This function should\n only be called from function `_apply_preprocessing`.\n\n The method overrides art.estimators.estimator::BaseEstimator._apply_preprocessing().\n It requires all defenses to have a method `forward()`.\n It converts numpy arrays to PyTorch tensors first, then chains a series of defenses by calling\n defence.forward() which contains PyTorch operations. At the end, it converts PyTorch tensors\n back to numpy arrays.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param fit: `True` if the function is call before fit/training and `False` if the function is called before a\n predict operation.\n :param no_grad: `True` if no gradients required.\n :type no_grad: bool\n :return: Tuple of `x` and `y` after applying the defences and standardisation.\n :rtype: Format as expected by the `model`\n \"\"\"\n import torch\n\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n if not self.preprocessing_operations:\n return x, y\n\n input_is_tensor = isinstance(x, torch.Tensor)\n\n if self.all_framework_preprocessing and not (not input_is_tensor and x.dtype == object):\n if not input_is_tensor:\n # Convert np arrays to torch tensors.\n x = torch.tensor(x, device=self._device)\n if y is not None:\n y = torch.tensor(y, device=self._device)\n\n def chain_processes(x, y):\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x, y = preprocess.forward(x, y)\n else:\n if preprocess.apply_predict:\n x, y = preprocess.forward(x, y)\n return x, y\n\n if no_grad:\n with torch.no_grad():\n x, y = chain_processes(x, y)\n else:\n x, y = chain_processes(x, y)\n\n # Convert torch tensors back to np arrays.\n if not input_is_tensor:\n x = x.cpu().numpy()\n if y is not None:\n y = y.cpu().numpy()\n\n elif len(self.preprocessing_operations) == 1 or (\n len(self.preprocessing_operations) == 2\n and isinstance(self.preprocessing_operations[-1], (StandardisationMeanStd, StandardisationMeanStdPyTorch))\n ):\n # Compatible with non-PyTorch defences if no chaining.\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x, y = preprocess(x, y)\n else:\n if preprocess.apply_predict:\n x, y = preprocess(x, y)\n\n else:\n raise NotImplementedError(\"The current combination of preprocessing types is not supported.\")\n\n return x, y\n\n def _apply_preprocessing_gradient(self, x, gradients, fit=False):\n \"\"\"\n Apply the backward pass to the gradients through all preprocessing defences that have been applied to `x`\n and `y` in the forward pass. This function should only be called from function\n `_apply_preprocessing_gradient`.\n\n The method overrides art.estimators.estimator::LossGradientsMixin._apply_preprocessing_gradient().\n It requires all defenses to have a method estimate_forward().\n It converts numpy arrays to PyTorch tensors first, then chains a series of defenses by calling\n defence.estimate_forward() which contains differentiable estimate of the operations. At the end,\n it converts PyTorch tensors back to numpy arrays.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :param gradients: Gradients before backward pass through preprocessing defences.\n :type gradients: Format as expected by the `model`\n :param fit: `True` if the gradients are computed during training.\n :return: Gradients after backward pass through preprocessing defences.\n :rtype: Format as expected by the `model`\n \"\"\"\n import torch\n\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n if not self.preprocessing_operations:\n return gradients\n\n input_is_tensor = isinstance(x, torch.Tensor)\n\n if self.all_framework_preprocessing and not (not input_is_tensor and x.dtype == object):\n # Convert np arrays to torch tensors.\n x = torch.tensor(x, device=self._device, requires_grad=True)\n gradients = torch.tensor(gradients, device=self._device)\n x_orig = x\n\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x = preprocess.estimate_forward(x)\n else:\n if preprocess.apply_predict:\n x = preprocess.estimate_forward(x)\n\n x.backward(gradients)\n\n # Convert torch tensors back to np arrays.\n gradients = x_orig.grad.detach().cpu().numpy()\n if gradients.shape != x_orig.shape:\n raise ValueError(f\"The input shape is {x.shape} while the gradient shape is {gradients.shape}\")\n\n elif len(self.preprocessing_operations) == 1 or (\n len(self.preprocessing_operations) == 2\n and isinstance(self.preprocessing_operations[-1], (StandardisationMeanStd, StandardisationMeanStdPyTorch))\n ):\n # Compatible with non-PyTorch defences if no chaining.\n for preprocess in self.preprocessing_operations[::-1]:\n if fit:\n if preprocess.apply_fit:\n gradients = preprocess.estimate_gradient(x, gradients)\n else:\n if preprocess.apply_predict:\n gradients = preprocess.estimate_gradient(x, gradients)\n\n else:\n raise NotImplementedError(\"The current combination of preprocessing types is not supported.\")\n\n return gradients\n\n def _set_layer(self, train: bool, layerinfo: list[\"torch.nn.modules.Module\"]) -> None:\n \"\"\"\n Set all layers that are an instance of `layerinfo` into training or evaluation mode.\n\n :param train: False for evaluation mode.\n :param layerinfo: List of module types.\n \"\"\"\n import torch\n\n assert all((issubclass(layer, torch.nn.modules.Module) for layer in layerinfo)) # type: ignore\n\n def set_train(layer, layerinfo=layerinfo):\n \"Set layer into training mode if instance of `layerinfo`.\"\n if isinstance(layer, tuple(layerinfo)):\n layer.train()\n\n def set_eval(layer, layerinfo=layerinfo):\n \"Set layer into evaluation mode if instance of `layerinfo`.\"\n if isinstance(layer, tuple(layerinfo)):\n layer.eval()\n\n if train:\n self._model.apply(set_train)\n else:\n self._model.apply(set_eval)\n\n def set_dropout(self, train: bool) -> None:\n \"\"\"\n Set all dropout layers into train or eval mode.\n\n :param train: False for evaluation mode.\n \"\"\"\n import torch\n\n self._set_layer(train=train, layerinfo=[torch.nn.modules.dropout._DropoutNd]) # type: ignore\n\n def set_batchnorm(self, train: bool) -> None:\n \"\"\"\n Set all batch normalization layers into train or eval mode.\n\n :param train: False for evaluation mode.\n \"\"\"\n import torch\n\n self._set_layer(train=train, layerinfo=[torch.nn.modules.batchnorm._BatchNorm]) # type: ignore\n\n def set_multihead_attention(self, train: bool) -> None:\n \"\"\"\n Set all multi-head attention layers into train or eval mode.\n\n :param train: False for evaluation mode.\n \"\"\"\n import torch\n\n self._set_layer(train=train, layerinfo=[torch.nn.modules.MultiheadAttention]) # type: ignore\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/scikitlearn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract estimator for scikit-learn models.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\n\nfrom art.estimators.estimator import BaseEstimator\n\nlogger = logging.getLogger(__name__)\n\n\nclass ScikitlearnEstimator(BaseEstimator):\n \"\"\"\n Estimator class for scikit-learn models.\n \"\"\"\n\n def _get_input_shape(self, model) -> tuple[int, ...] | None:\n _input_shape: tuple[int, ...] | None\n if hasattr(model, \"n_features_\"):\n _input_shape = (model.n_features_,)\n elif hasattr(model, \"n_features_in_\"):\n _input_shape = (model.n_features_in_,)\n elif hasattr(model, \"feature_importances_\"):\n _input_shape = (len(model.feature_importances_),)\n elif hasattr(model, \"coef_\"):\n if len(model.coef_.shape) == 1:\n _input_shape = (model.coef_.shape[0],)\n else:\n _input_shape = (model.coef_.shape[1],)\n elif hasattr(model, \"support_vectors_\"):\n _input_shape = (model.support_vectors_.shape[1],)\n elif hasattr(model, \"steps\"):\n _input_shape = self._get_input_shape(model.steps[0][1])\n else:\n logger.warning(\"Input shape not recognised. The model might not have been fitted.\")\n _input_shape = None\n return _input_shape\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract estimators `TensorFlowV2Estimator` for TensorFlow models.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art import config\nfrom art.estimators.estimator import (\n BaseEstimator,\n LossGradientsMixin,\n NeuralNetworkMixin,\n)\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2Estimator(NeuralNetworkMixin, LossGradientsMixin, BaseEstimator):\n \"\"\"\n Estimator class for TensorFlow v2 models.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + NeuralNetworkMixin.estimator_params\n\n def __init__(self, **kwargs):\n \"\"\"\n Estimator class for TensorFlow v2 models.\n \"\"\"\n preprocessing = kwargs.get(\"preprocessing\")\n if isinstance(preprocessing, tuple):\n from art.preprocessing.standardisation_mean_std.tensorflow import StandardisationMeanStdTensorFlow\n\n kwargs[\"preprocessing\"] = StandardisationMeanStdTensorFlow(mean=preprocessing[0], std=preprocessing[1])\n\n super().__init__(**kwargs)\n TensorFlowV2Estimator._check_params(self)\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n \"\"\"\n Perform prediction of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param batch_size: Batch size.\n :return: Predictions.\n :rtype: Format as expected by the `model`\n \"\"\"\n return NeuralNetworkMixin.predict(self, x, batch_size=batch_size, **kwargs)\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the model of the estimator on the training data `x` and `y`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param batch_size: Batch size.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n NeuralNetworkMixin.fit(self, x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take a dictionary of parameters and apply checks before setting them as attributes.\n\n :param kwargs: A dictionary of attributes.\n \"\"\"\n super().set_params(**kwargs)\n self._check_params()\n\n def _check_params(self) -> None:\n from art.defences.preprocessor.preprocessor import PreprocessorTensorFlowV2\n\n super()._check_params()\n self.all_framework_preprocessing = all(\n (isinstance(p, PreprocessorTensorFlowV2) for p in self.preprocessing_operations)\n )\n\n def _apply_preprocessing(self, x, y, fit: bool = False) -> tuple[Any, Any]:\n \"\"\"\n Apply all preprocessing defences of the estimator on the raw inputs `x` and `y`. This function should\n only be called from function `_apply_preprocessing`.\n\n The method overrides art.estimators.estimator::BaseEstimator._apply_preprocessing().\n It requires all defenses to have a method `forward()`.\n It converts numpy arrays to TensorFlow tensors first, then chains a series of defenses by calling\n defence.forward() which contains TensorFlow operations. At the end, it converts TensorFlow tensors\n back to numpy arrays.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param fit: `True` if the function is call before fit/training and `False` if the function is called before a\n predict operation.\n :return: Tuple of `x` and `y` after applying the defences and standardisation.\n :rtype: Format as expected by the `model`\n \"\"\"\n import tensorflow as tf\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n from art.preprocessing.standardisation_mean_std.tensorflow import StandardisationMeanStdTensorFlow\n\n if not self.preprocessing_operations:\n return x, y\n\n input_is_tensor = isinstance(x, tf.Tensor)\n\n if self.all_framework_preprocessing and not (not input_is_tensor and x.dtype == object):\n # Convert np arrays to torch tensors.\n if not input_is_tensor:\n x = tf.convert_to_tensor(x)\n if y is not None:\n y = tf.convert_to_tensor(y)\n\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x, y = preprocess.forward(x, y)\n else:\n if preprocess.apply_predict:\n x, y = preprocess.forward(x, y)\n\n # Convert torch tensors back to np arrays.\n if not input_is_tensor:\n x = x.numpy()\n if y is not None:\n y = y.numpy()\n\n elif len(self.preprocessing_operations) == 1 or (\n len(self.preprocessing_operations) == 2\n and isinstance(\n self.preprocessing_operations[-1], (StandardisationMeanStd, StandardisationMeanStdTensorFlow)\n )\n ):\n # Compatible with non-TensorFlow defences if no chaining.\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x, y = preprocess(x, y)\n else:\n if preprocess.apply_predict:\n x, y = preprocess(x, y)\n\n else:\n raise NotImplementedError(\"The current combination of preprocessing types is not supported.\")\n\n return x, y\n\n def _apply_preprocessing_gradient(self, x, gradients, fit=False):\n \"\"\"\n Apply the backward pass to the gradients through all preprocessing defences that have been applied to `x`\n and `y` in the forward pass. This function should only be called from function\n `_apply_preprocessing_gradient`.\n\n The method overrides art.estimators.estimator::LossGradientsMixin._apply_preprocessing_gradient().\n It requires all defenses to have a method estimate_forward().\n It converts numpy arrays to TensorFlow tensors first, then chains a series of defenses by calling\n defence.estimate_forward() which contains differentiable estimate of the operations. At the end,\n it converts TensorFlow tensors back to numpy arrays.\n\n :param x: Samples.\n :type x: Format as expected by the `model`\n :param gradients: Gradients before backward pass through preprocessing defences.\n :type gradients: Format as expected by the `model`\n :param fit: `True` if the gradients are computed during training.\n :return: Gradients after backward pass through preprocessing defences.\n :rtype: Format as expected by the `model`\n \"\"\"\n import tensorflow as tf\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n from art.preprocessing.standardisation_mean_std.tensorflow import StandardisationMeanStdTensorFlow\n\n if not self.preprocessing_operations:\n return gradients\n\n input_is_tensor = isinstance(x, tf.Tensor)\n\n if self.all_framework_preprocessing and not (not input_is_tensor and x.dtype == object):\n with tf.GradientTape() as tape:\n # Convert np arrays to TensorFlow tensors.\n x = tf.convert_to_tensor(x, dtype=config.ART_NUMPY_DTYPE)\n tape.watch(x)\n gradients = tf.convert_to_tensor(gradients, dtype=config.ART_NUMPY_DTYPE)\n x_orig = x\n\n for preprocess in self.preprocessing_operations:\n if fit:\n if preprocess.apply_fit:\n x = preprocess.estimate_forward(x)\n else:\n if preprocess.apply_predict:\n x = preprocess.estimate_forward(x)\n\n x_grad = tape.gradient(target=x, sources=x_orig, output_gradients=gradients)\n\n # Convert torch tensors back to np arrays.\n gradients = x_grad.numpy()\n if gradients.shape != x_orig.shape: # pragma: no cover\n raise ValueError(f\"The input shape is {x.shape} while the gradient shape is {gradients.shape}\")\n\n elif len(self.preprocessing_operations) == 1 or (\n len(self.preprocessing_operations) == 2\n and isinstance(\n self.preprocessing_operations[-1], (StandardisationMeanStd, StandardisationMeanStdTensorFlow)\n )\n ):\n # Compatible with non-TensorFlow defences if no chaining.\n for preprocess in self.preprocessing_operations[::-1]:\n if fit:\n if preprocess.apply_fit:\n gradients = preprocess.estimate_gradient(x, gradients)\n else:\n if preprocess.apply_predict:\n gradients = preprocess.estimate_gradient(x, gradients)\n\n else:\n raise NotImplementedError(\"The current combination of preprocessing types is not supported.\")\n\n return gradients\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains certified classifiers.\n\"\"\"\n\nimport importlib\nfrom art.estimators.certification.randomized_smoothing.randomized_smoothing import RandomizedSmoothingMixin\nfrom art.estimators.certification.randomized_smoothing.numpy import NumpyRandomizedSmoothing\nfrom art.estimators.certification.randomized_smoothing.tensorflow import TensorFlowV2RandomizedSmoothing\nfrom art.estimators.certification.randomized_smoothing.pytorch import PyTorchRandomizedSmoothing\nfrom art.estimators.certification.derandomized_smoothing.pytorch import PyTorchDeRandomizedSmoothing\nfrom art.estimators.certification.derandomized_smoothing.tensorflow import TensorFlowV2DeRandomizedSmoothing\nfrom art.estimators.certification.object_seeker.object_seeker import ObjectSeekerMixin\nfrom art.estimators.certification.object_seeker.pytorch import PyTorchObjectSeeker\n\nif importlib.util.find_spec(\"torch\") is not None:\n from art.estimators.certification.deep_z.deep_z import ZonoDenseLayer\n from art.estimators.certification.deep_z.deep_z import ZonoBounds\n from art.estimators.certification.deep_z.deep_z import ZonoConv\n from art.estimators.certification.deep_z.deep_z import ZonoReLU\n from art.estimators.certification.deep_z.pytorch import PytorchDeepZ\n from art.estimators.certification.interval.interval import PyTorchIntervalDense\n from art.estimators.certification.interval.interval import PyTorchIntervalConv2D\n from art.estimators.certification.interval.interval import PyTorchIntervalReLU\n from art.estimators.certification.interval.interval import PyTorchIntervalFlatten\n from art.estimators.certification.interval.interval import PyTorchIntervalBounds\n from art.estimators.certification.interval.pytorch import PyTorchIBPClassifier\nelse:\n import warnings\n\n warnings.warn(\"PyTorch not found. Not importing DeepZ or Interval Bound Propagation functionality\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/abstain.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a mixin to be added to classifier so that they may abstain from classification.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nlogger = logging.getLogger(__name__)\n\n\nclass AbstainPredictorMixin(ClassifierMixin):\n \"\"\"\n A mixin class that gives classifiers the ability to abstain\n \"\"\"\n\n def abstain(self) -> np.ndarray:\n \"\"\"\n Abstain from a prediction\n :return: A numpy array of zeros\n \"\"\"\n return np.zeros(self.nb_classes)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/deep_z/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nDeepZ based certification estimators.\n\"\"\"\n\nfrom art.estimators.certification.deep_z.deep_z import ZonoDenseLayer\nfrom art.estimators.certification.deep_z.deep_z import ZonoBounds\nfrom art.estimators.certification.deep_z.deep_z import ZonoConv\nfrom art.estimators.certification.deep_z.deep_z import ZonoReLU\nfrom art.estimators.certification.deep_z.pytorch import PytorchDeepZ\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/deep_z/deep_z.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements DeepZ proposed in Fast and Effective Robustness Certification.\n\n| Paper link: https://papers.nips.cc/paper/2018/file/f2f446980d8e971ef3da97af089481c3-Paper.pdf\n\"\"\"\nfrom __future__ import annotations\n\nimport numpy as np\nimport torch\n\n\nclass ZonoDenseLayer(torch.nn.Module):\n \"\"\"\n Class implementing a dense layer on a zonotope.\n Bias is only added to the zeroth term.\n \"\"\"\n\n def __init__(self, in_features: int, out_features: int):\n super().__init__()\n self.weight = torch.nn.Parameter(\n torch.normal(mean=torch.zeros(out_features, in_features), std=torch.ones(out_features, in_features))\n )\n self.bias = torch.nn.Parameter(torch.normal(mean=torch.zeros(out_features), std=torch.ones(out_features)))\n\n def __call__(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n return self.forward(x)\n\n def forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Abstract forward pass through the dense layer.\n\n :param x: input zonotope to the dense layer.\n :return: zonotope after being pushed through the dense layer.\n \"\"\"\n x = self.zonotope_matmul(x)\n x = self.zonotope_add(x)\n return x\n\n def concrete_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Concrete forward pass through the dense layer.\n\n :param x: concrete input to the dense layer.\n :return: concrete dense layer outputs.\n \"\"\"\n x = torch.matmul(x, torch.transpose(self.weight, 0, 1)) + self.bias\n return x\n\n def zonotope_matmul(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Matrix multiplication for dense layer.\n\n :param x: input to the dense layer.\n :return: zonotope after weight multiplication.\n \"\"\"\n return torch.matmul(x, torch.transpose(self.weight, 0, 1))\n\n def zonotope_add(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Modification required compared to the normal torch dense layer.\n The bias is added only to the central zonotope term and not the error terms.\n\n :param x: zonotope input to have the bias added.\n :return: zonotope with the bias added to the central (first) term.\n \"\"\"\n x[0] = x[0] + self.bias\n return x\n\n\nclass ZonoBounds:\n \"\"\"\n Class providing functionality for computing operations related to getting lower and upper bounds on zonotopes.\n \"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def compute_lb(cent: \"torch.Tensor\", eps: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute the lower bound on a feature.\n\n :param eps: tensor with the eps terms\n :param cent: tensor with the zero zonotope term\n :return: lower bound on the given feature\n \"\"\"\n return torch.sum(-1 * torch.abs(eps), dim=0) + cent\n\n @staticmethod\n def compute_ub(cent: \"torch.Tensor\", eps: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute the upper bound on a feature.\n\n :param eps: tensor with the eps terms\n :param cent: tensor with the zero zonotope term\n :return: upper bound on the given feature\n \"\"\"\n return torch.sum(torch.abs(eps), dim=0) + cent\n\n @staticmethod\n def certify_via_subtraction(\n predicted_class: int, class_to_consider: int, cent: np.ndarray, eps: np.ndarray\n ) -> bool:\n \"\"\"\n To perform the certification we subtract the zonotope of \"class_to_consider\"\n from the zonotope of the predicted class.\n\n :param predicted_class: class the model predicted.\n :param class_to_consider: class to check if the model could have classified to it.\n :param cent: center/zeroth zonotope term.\n :param eps: zonotope error terms.\n :return: True/False if the point has been certified\n \"\"\"\n diff_in_bias = cent[class_to_consider] - cent[predicted_class]\n diff_in_eps = eps[:, class_to_consider] - eps[:, predicted_class]\n lbs = np.sum(-1 * np.abs(diff_in_eps)) + diff_in_bias\n ubs = np.sum(np.abs(diff_in_eps)) + diff_in_bias\n\n return np.sign(lbs) < 0 and np.sign(ubs) < 0\n\n def zonotope_get_bounds(self, cent: \"torch.Tensor\", eps: \"torch.Tensor\") -> tuple[list, list]:\n \"\"\"\n Compute the upper and lower bounds for the final zonotopes\n\n :param cent: center/zeroth zonotope term.\n :param eps: zonotope error terms.\n :return: lists with the upper and lower bounds.\n \"\"\"\n upper_bounds_output = []\n lower_bounds_output = []\n\n for j in range(cent.shape[0]):\n # compute lower bounds\n lbs = self.compute_lb(eps=eps[:, j], cent=cent[j])\n # compute upper bounds\n ubs = self.compute_ub(eps=eps[:, j], cent=cent[j])\n\n upper_bounds_output.append(ubs)\n lower_bounds_output.append(lbs)\n return upper_bounds_output, lower_bounds_output\n\n @staticmethod\n def adjust_to_within_bounds(cent: np.ndarray, eps: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Simple helper function to pre-process and adjust zonotope values to be within 0 - 1 range.\n This is written with image data from MNIST and CIFAR10 in mind using L-infty bounds.\n Each feature here starts with a single eps term.\n Users can implement custom pre-processors tailored to their data if it does not conform to these requirements.\n\n :param cent: original feature values between 0 - 1\n :param eps: the zonotope error terms.\n :return: adjusted center and eps values if center + eps exceed 1 or if center - eps falls below 0.\n \"\"\"\n for j in range(cent.shape[1]):\n # we assume that each feature will start with just a single eps term\n row_of_eps = np.argmax(eps[:, j])\n if cent[:, j] < eps[row_of_eps, j]:\n eps[row_of_eps, j] = (eps[row_of_eps, j] + cent[:, j]) / 2\n cent[:, j] = eps[row_of_eps, j]\n elif cent[:, j] > (1 - eps[row_of_eps, j]):\n eps[row_of_eps, j] = (eps[row_of_eps, j] + (1 - cent[:, j])) / 2\n cent[:, j] = 1 - eps[row_of_eps, j]\n\n return cent, eps\n\n def pre_process(self, cent: np.ndarray, eps: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Simple helper function to reshape and adjust the zonotope values before pushing through the neural network.\n This is written with image data from MNIST and CIFAR10 in mind using L-infty bounds.\n Each feature here starts with a single eps term.\n Users can implement custom pre-processors tailored to their data if it does not conform to these requirements.\n\n :param cent: original feature values between 0 - 1\n :param eps: the zonotope error terms.\n :return: adjusted center and eps values if center + eps exceed 1 or if center - eps falls below 0.\n \"\"\"\n original_shape = cent.shape\n cent = np.reshape(np.copy(cent), (1, -1))\n num_of_error_terms = eps.shape[0]\n cent, eps = self.adjust_to_within_bounds(cent, np.copy(eps))\n cent = np.reshape(cent, original_shape)\n\n reshape_dim = (num_of_error_terms,) + original_shape\n eps = np.reshape(eps, reshape_dim)\n\n return cent, eps\n\n\nclass ZonoConv(torch.nn.Module):\n \"\"\"\n Wrapper around pytorch's convolutional layer.\n We only add the bias to the zeroth element of the zonotope\n \"\"\"\n\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n kernel_size: int | tuple[int, int],\n stride: int | tuple[int, int],\n dilation: int | tuple[int, int] = 1,\n padding: int | tuple[int, int] = 0,\n ):\n super().__init__()\n self.conv = torch.nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n dilation=dilation,\n padding=padding,\n bias=False,\n )\n self.bias = torch.nn.Parameter(\n torch.zeros(\n out_channels,\n )\n )\n\n def __call__(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n return self.forward(x)\n\n def forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Abstract forward pass through the convolutional layer\n\n :param x: input zonotope to the convolutional layer.\n :return x: zonotope after being pushed through the convolutional layer.\n \"\"\"\n x = self.conv(x)\n x = self.zonotope_add(x)\n return x\n\n def concrete_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Concrete forward pass through the convolutional layer\n\n :param x: concrete input to the convolutional layer.\n :return: concrete convolutional layer outputs.\n \"\"\"\n x = self.conv(x)\n bias = torch.unsqueeze(self.bias, dim=-1)\n bias = torch.unsqueeze(bias, dim=-1)\n bias = torch.unsqueeze(bias, dim=0)\n return x + bias\n\n def zonotope_add(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Modification required compared to the normal torch conv layers.\n The bias is added only to the central zonotope term and not the error terms.\n\n :param x: zonotope input to have the bias added.\n :return: zonotope with the bias added to the central (first) term.\n \"\"\"\n # unsqueeze to broadcast along height and width\n bias = torch.unsqueeze(self.bias, dim=-1)\n bias = torch.unsqueeze(bias, dim=-1)\n x[0] = x[0] + bias\n return x\n\n\nclass ZonoReLU(torch.nn.Module, ZonoBounds):\n \"\"\"\n Implements \"DeepZ\" for relu.\n\n | Paper link: https://papers.nips.cc/paper/2018/file/f2f446980d8e971ef3da97af089481c3-Paper.pdf\n \"\"\"\n\n def __init__(self, device=\"cpu\"):\n super().__init__()\n self.device = device\n self.concrete_activation = torch.nn.ReLU()\n\n def __call__(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n return self.forward(x)\n\n def forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Forward pass through the relu\n\n :param x: input zonotope to the dense layer.\n :return x: zonotope after being pushed through the dense layer.\n \"\"\"\n return self.zonotope_relu(x)\n\n def concrete_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Concrete pass through the ReLU function\n\n :param x: concrete input to the activation function.\n :return: concrete outputs from the ReLU.\n \"\"\"\n return self.concrete_activation(x)\n\n def zonotope_relu(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Implements \"DeepZ\" for ReLU.\n\n :param x: input zonotope.\n :return x: zonotope after application of the relu. May have grown in dimension if crossing relus occur.\n \"\"\"\n original_shape = x.shape\n x = x.reshape((x.shape[0], -1))\n\n # compute lower bounds\n lbs = self.compute_lb(cent=x[0], eps=x[1:])\n\n # compute upper bounds\n ubs = self.compute_ub(cent=x[0], eps=x[1:])\n slope = torch.div(ubs, (ubs - lbs))\n\n index_cent_vector = torch.zeros((x.shape[0], 1)).to(self.device)\n index_cent_vector[0] = 1\n\n cent_update = (slope * lbs) / 2\n cent_update = torch.tile(cent_update, (x.shape[0], 1))\n\n # find where we have a crossing relu\n bools = torch.logical_and(lbs < 0, ubs > 0)\n\n # where we have a crossing relu, update the terms. Else, do not change input.\n x = torch.where(bools, x * slope - cent_update * index_cent_vector, x)\n\n # where we have a feature that is < 0, relu always returns 0\n zeros = torch.from_numpy(np.zeros(1).astype(\"float32\")).to(self.device)\n x = torch.where(ubs < 0, zeros, x)\n\n # vector containing all the (potential) new error terms. We will need to 1) select the ones\n # we need and zero out the rest. And 2) Shape the errors into the correct matrix.\n new_vector = torch.unsqueeze(-1 * ((slope * lbs) / 2), dim=0)\n\n # indexing_matrix is the shape we want the error terms to be.\n indexing_matrix = np.zeros((torch.sum(bools), x.shape[1]))\n\n tmp_crossing_relu = torch.logical_and(lbs < 0, ubs > 0)\n crossing_relu_index = 0\n for j, crossing_relu in enumerate(tmp_crossing_relu):\n if crossing_relu:\n indexing_matrix[crossing_relu_index, j] = 1\n crossing_relu_index += 1\n\n indexing_matrix_tensor = torch.from_numpy(indexing_matrix.astype(\"float32\")).to(self.device)\n\n # where there is a crossing ReLU, select the error terms, else zero the vector.\n new_vector = torch.where(bools, new_vector, zeros)\n # tile the error vector to the correct shape and select the terms we want.\n # crossing_relu_index at this point is also the same as the number of crossing relus\n new_vector = torch.tile(new_vector, (crossing_relu_index, 1))\n new_vector = new_vector * indexing_matrix_tensor\n\n # add the new error terms to the zonotope.\n x = torch.cat((x, new_vector))\n\n if len(original_shape) > 2:\n x = x.reshape((-1, original_shape[1], original_shape[2], original_shape[3]))\n return x\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/deep_z/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements DeepZ proposed in Fast and Effective Robustness Certification.\n\n| Paper link: https://papers.nips.cc/paper/2018/file/f2f446980d8e971ef3da97af089481c3-Paper.pdf\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import Any, TYPE_CHECKING\n\nimport logging\nimport math\nimport warnings\nimport sys\n\nimport numpy as np\nimport torch\n\nfrom art.estimators.certification.deep_z.deep_z import ZonoConv, ZonoDenseLayer, ZonoReLU, ZonoBounds\nfrom art.estimators.classification.pytorch import PyTorchClassifier\n\nif sys.version_info < (3, 8):\n from functools import reduce\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\n\nclass ConvertedModel(torch.nn.Module):\n \"\"\"\n Class which converts the supplied pytorch model into an equivalent model\n which uses abstract operations\n \"\"\"\n\n def __init__(self, model: \"torch.nn.Module\", channels_first: bool, input_shape: tuple[int, ...]):\n super().__init__()\n modules = []\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.forward_mode: str\n self.forward_mode = \"abstract\"\n self.reshape_op_num = -1\n\n def forward_hook(input_module, hook_input, hook_output):\n modules.append(input_module)\n\n for module in model.children():\n module.register_forward_hook(forward_hook)\n\n if channels_first:\n input_for_hook = torch.rand(input_shape).to(self.device)\n else:\n raise ValueError(\"Please provide data in channels first format\")\n\n input_for_hook = torch.unsqueeze(input_for_hook, dim=0)\n model(input_for_hook) # hooks are fired sequentially from model input to the output\n\n self.ops = torch.nn.ModuleList()\n for module in modules:\n if isinstance(module, torch.nn.modules.conv.Conv2d):\n zono_conv = ZonoConv(\n in_channels=module.in_channels,\n out_channels=module.out_channels,\n kernel_size=module.kernel_size, # type: ignore\n stride=module.stride, # type: ignore\n dilation=module.dilation, # type: ignore\n padding=module.padding, # type: ignore\n )\n zono_conv.conv.weight.data = module.weight.data.to(self.device)\n zono_conv.bias.data = module.bias.data.to(self.device) # type: ignore\n self.ops.append(zono_conv)\n\n elif isinstance(module, torch.nn.modules.linear.Linear):\n zono_dense = ZonoDenseLayer(in_features=module.in_features, out_features=module.out_features)\n zono_dense.weight.data = module.weight.data.to(self.device)\n zono_dense.bias.data = module.bias.data.to(self.device)\n self.ops.append(zono_dense)\n\n elif isinstance(module, torch.nn.modules.activation.ReLU):\n self.ops.append(ZonoReLU(device=self.device))\n else:\n raise ValueError(\"Supported Operations are Conv2D, Linear, and RelU\")\n\n for op_num, op in enumerate(self.ops):\n # as reshapes are not modules we infer when the reshape from convolutional to dense occurs\n if isinstance(op, ZonoDenseLayer):\n # if the preceeding op was a convolution:\n if isinstance(self.ops[op_num - 1], ZonoConv):\n self.reshape_op_num = op_num\n print(\"Inferred reshape on op num\", op_num)\n # if the preceeding op was a relu and the one before the activation was a convolution\n if isinstance(self.ops[op_num - 1], ZonoReLU) and isinstance(self.ops[op_num - 2], ZonoConv):\n self.reshape_op_num = op_num\n print(\"Inferred reshape on op num\", op_num)\n\n def forward(\n self, cent: np.ndarray, eps: np.ndarray | None = None\n ) -> \"torch.Tensor\" | tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Performs the neural network forward pass, either using abstract operations or concrete ones\n depending on the value of self.forward_mode\n\n :param cent: input data, either regular data if running in concrete mode, or the zonotope bias term.\n :param eps: zonotope error terms if running in abstract mode\n :return: model predictions, with zonotope error terms if running in abstract mode\n \"\"\"\n if self.forward_mode == \"concrete\":\n return self.concrete_forward(cent)\n if self.forward_mode == \"abstract\":\n if eps is not None:\n out_cent, out_eps = self.abstract_forward(cent, eps)\n return out_cent, out_eps\n raise ValueError(\"for abstract forward mode, please provide both cent and eps\")\n raise ValueError(\"forward_mode must be set to abstract or concrete\")\n\n def abstract_forward(\n self, cent: np.ndarray, eps: np.ndarray\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]: # typing: ignore\n \"\"\"\n Do the forward pass through the NN with the given error terms and zonotope center.\n\n :param cent: The datapoint, representing the zonotope center.\n :param eps: Error terms of the zonotope.\n :return: A tuple, the first element being the zonotope center vector.\n The second is the zonotope error terms/coefficients.\n \"\"\"\n\n x = np.concatenate([cent, eps])\n x = torch.from_numpy(x.astype(\"float32\")).to(self.device)\n\n for op_num, op in enumerate(self.ops):\n # as reshapes are not modules we infer when the reshape from convolutional to dense occurs\n if self.reshape_op_num == op_num:\n x = x.reshape((x.shape[0], -1))\n x = op(x)\n return x[0, :], x[1:, :]\n\n def concrete_forward(self, in_x: np.ndarray | \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Do the forward pass using the concrete operations\n\n :param in_x: regular (concrete) data.\n \"\"\"\n\n if isinstance(in_x, np.ndarray):\n x = torch.from_numpy(in_x.astype(\"float32\")).to(self.device)\n else:\n x = in_x\n\n for op_num, op in enumerate(self.ops):\n # as reshapes are not modules we infer when the reshape from convolutional to dense occurs\n if self.reshape_op_num == op_num:\n x = x.reshape((x.shape[0], -1))\n x = op.concrete_forward(x) # type: ignore\n return x\n\n def set_forward_mode(self, mode: str) -> None:\n \"\"\"\n Helper function to set the forward mode of the model\n\n :param mode: either concrete or abstract signifying how to run the forward pass\n \"\"\"\n assert mode in {\"concrete\", \"abstract\"}\n self.forward_mode = mode\n\n\nclass PytorchDeepZ(PyTorchClassifier, ZonoBounds):\n \"\"\"\n Implementation of DeepZ to certify neural network robustness. We use the zonotope representation of a datapoint as\n it travels through the network to then verify if it can have its class changed given a certain perturbation.\n\n | Paper link: https://papers.nips.cc/paper/2018/file/f2f446980d8e971ef3da97af089481c3-Paper.pdf\n \"\"\"\n\n estimator_params = PyTorchClassifier.estimator_params\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n concrete_to_zonotope: Callable | None = None,\n ):\n \"\"\"\n Create a certifier based on the zonotope domain.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param concrete_to_zonotope: Optional argument. Function which takes in a concrete data point and the bound\n and converts the datapoint to the zonotope domain via:\n\n processed_sample, eps_bound = concrete_to_zonotope(sample, bound)\n\n where processed_sample is the zonotope bias term, and eps_bound are the\n associated error terms.\n If left as None, by default we apply the bound to every feature equally and\n adjust the zonotope such that it remains in the 0 - 1 range.\n \"\"\"\n\n warnings.warn(\n \"\\nThis estimator does not support networks which have dense layers before convolutional. \"\n \"We currently infer a reshape when a neural network goes from convolutional layers to \"\n \"dense layers. If your use case does not fall into this pattern then consider \"\n \"directly building a certifier network with the \"\n \"custom layers found in art.estimators.certification.deepz.deep_z.py\\n\"\n )\n converted_model = ConvertedModel(model, channels_first, input_shape)\n\n if TYPE_CHECKING:\n converted_optimizer: torch.optim.Adam | torch.optim.SGD | None\n\n if optimizer is not None:\n opt_state_dict = optimizer.state_dict()\n if isinstance(optimizer, torch.optim.Adam):\n logging.info(\"Converting Adam Optimiser\")\n converted_optimizer = torch.optim.Adam(converted_model.parameters(), lr=1e-4)\n elif isinstance(optimizer, torch.optim.SGD):\n logging.info(\"Converting SGD Optimiser\")\n converted_optimizer = torch.optim.SGD(converted_model.parameters(), lr=1e-4)\n else:\n raise ValueError(\"Optimiser not supported for conversion\")\n\n converted_optimizer.load_state_dict(opt_state_dict)\n else:\n converted_optimizer = None\n\n self.concrete_to_zonotope = concrete_to_zonotope\n\n super().__init__(\n model=converted_model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=converted_optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n\n def predict_zonotopes(\n self, cent: np.ndarray, bound: float, training_mode: bool = True, **kwargs\n ) -> tuple[list[np.ndarray], list[np.ndarray]]:\n \"\"\"\n\n :param cent: The datapoint, representing the zonotope center.\n :param bound: The perturbation range for the zonotope.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n x_preprocessed, _ = self._apply_preprocessing(cent, y=None, fit=False)\n self._model.train(mode=training_mode)\n\n bias_results_list = []\n eps_results_list = []\n\n for sample in x_preprocessed:\n if self.concrete_to_zonotope is None:\n if sys.version_info >= (3, 8):\n eps_bound = np.eye(math.prod(self.input_shape)) * bound\n else:\n eps_bound = np.eye(reduce(lambda x, y: x * y, self.input_shape)) * bound\n\n processed_sample, eps_bound = self.pre_process(cent=np.copy(sample), eps=eps_bound)\n processed_sample = np.expand_dims(processed_sample, axis=0)\n else:\n processed_sample, eps_bound = self.concrete_to_zonotope(sample, bound)\n\n bias, eps = self.model.forward(eps=eps_bound, cent=processed_sample)\n bias = bias.detach().cpu().numpy()\n eps = eps.detach().cpu().numpy()\n\n bias_results_list.append(np.expand_dims(bias, axis=0))\n eps_results_list.append(eps)\n\n return bias_results_list, eps_results_list\n\n def certify(self, cent: np.ndarray, eps: np.ndarray, prediction: int) -> bool:\n \"\"\"\n Check if the datapoint has been certifiably classified.\n\n First do the forward pass through the NN with the given error terms and zonotope center to\n obtain the output zonotope.\n\n Then perform the certification step by computing the difference of the logits in the final zonotope\n and projecting to interval.\n\n :param cent: The datapoint, representing the zonotope center.\n :param eps: Error terms of the zonotope.\n :param prediction: The prediction the neural network gave on the basic datapoint.\n\n :return: True/False if the datapoint could be misclassified given the eps bounds.\n \"\"\"\n cent_tensor, eps_tensor = self.model.forward(eps=eps, cent=cent)\n cent = cent_tensor.detach().cpu().numpy()\n eps = eps_tensor.detach().cpu().numpy()\n\n certification_results = []\n for k in range(self.nb_classes):\n if k != prediction:\n cert_via_sub = self.certify_via_subtraction(\n predicted_class=prediction, class_to_consider=k, cent=cent, eps=eps\n )\n certification_results.append(cert_via_sub)\n\n return all(certification_results)\n\n def concrete_loss(self, output: \"torch.Tensor\", target: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Access function to get the classifier loss\n\n :param output: model predictions\n :param target: ground truth labels\n\n :return: loss value\n \"\"\"\n return self._loss(output, target)\n\n def apply_preprocessing(self, x: np.ndarray, y: np.ndarray, fit: bool) -> tuple[Any, Any]:\n \"\"\"\n Access function to get preprocessing\n\n :param x: unprocessed input data.\n :param y: unprocessed labels.\n :param fit: `True` if the function is call before fit/training and `False` if the function is called before a\n predict operation.\n :return: Tuple with the processed input data and labels.\n \"\"\"\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=fit)\n return x_preprocessed, y_preprocessed\n\n def max_logit_loss(self, prediction: \"torch.Tensor\", target: \"torch.Tensor\") -> \"torch.Tensor\" | None:\n \"\"\"\n Computes the loss as the largest logit value amongst the incorrect classes.\n\n :param prediction: model predictions.\n :param target: target classes. NB not one hot.\n :return: scalar loss value\n \"\"\"\n target_logit = prediction[:, target]\n output = prediction - target_logit\n\n ubs = torch.sum(torch.abs(output[1:, :]), dim=0) + output[0, :]\n\n loss = None\n for i in range(self.nb_classes):\n if i != target and (loss is None or ubs[i] > loss):\n loss = ubs[i]\n return loss\n\n @staticmethod\n def interval_loss_cce(prediction: \"torch.Tensor\", target: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Computes the categorical cross entropy loss with the correct class having the lower bound prediction,\n and the other classes having their upper bound predictions.\n\n :param prediction: model predictions.\n :param target: target classes. NB not one hot.\n :return: scalar loss value\n \"\"\"\n criterion = torch.nn.CrossEntropyLoss()\n ubs = torch.sum(torch.abs(prediction[1:, :]), dim=0) + prediction[0, :]\n lbs = torch.sum(-1 * torch.abs(prediction[1:, :]), dim=0) + prediction[0, :]\n\n # for the prediction corresponding to the target class, take the lower bound predictions\n ubs[target] = lbs[target]\n ubs = torch.unsqueeze(ubs, dim=0)\n return criterion(ubs, target)\n\n @staticmethod\n def get_accuracy(preds: np.ndarray | \"torch.Tensor\", labels: np.ndarray | \"torch.Tensor\") -> np.ndarray:\n \"\"\"\n Helper function to print out the accuracy during training\n\n :param preds: (concrete) model predictions\n :param labels: ground truth labels (not one hot)\n :return: prediction accuracy\n \"\"\"\n if isinstance(preds, torch.Tensor):\n preds = preds.detach().cpu().numpy()\n\n if isinstance(labels, torch.Tensor):\n labels = labels.detach().cpu().numpy()\n\n return np.sum(np.argmax(preds, axis=1) == labels) / len(labels)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nDeRandomized smoothing estimators.\n\"\"\"\n\nfrom art.estimators.certification.derandomized_smoothing.pytorch import PyTorchDeRandomizedSmoothing\nfrom art.estimators.certification.derandomized_smoothing.tensorflow import TensorFlowV2DeRandomizedSmoothing\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/derandomized.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements (De)Randomized Smoothing certifications against adversarial patches.\n\n| Paper link: https://arxiv.org/abs/2110.07719\n\n| Paper link: https://arxiv.org/abs/2002.10733\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom abc import ABC, abstractmethod\nimport numpy as np\n\n\nclass DeRandomizedSmoothingMixin(ABC):\n \"\"\"\n Mixin class for smoothed estimators.\n \"\"\"\n\n def __init__(\n self,\n *args,\n **kwargs,\n ) -> None:\n \"\"\"\n Create a derandomized smoothing wrapper.\n \"\"\"\n super().__init__(*args, **kwargs) # type: ignore\n\n @abstractmethod\n def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Performs cumulative predictions over every ablation location\n\n :param x: Unablated image\n :param batch_size: the batch size for the prediction\n :param training_mode: if to run the classifier in training mode\n :return: cumulative predictions after sweeping over all the ablation configurations.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements De-Randomized smoothing approaches PyTorch.\n\n(De)Randomized Smoothing for Certifiable Defense against Patch Attacks\n\n| Paper link: https://arxiv.org/abs/2002.10733\n\nand\n\nCertified Patch Robustness via Smoothed Vision Transformers\n\n| Paper link Accepted version:\n https://openaccess.thecvf.com/content/CVPR2022/papers/Salman_Certified_Patch_Robustness_via_Smoothed_Vision_Transformers_CVPR_2022_paper.pdf\n\n| Paper link Arxiv version (more detail): https://arxiv.org/pdf/2110.07719.pdf\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\nimport importlib\nimport logging\nfrom typing import Any, TYPE_CHECKING\nimport random\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.certification.derandomized_smoothing.derandomized import DeRandomizedSmoothingMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n import torchvision\n from timm.models.vision_transformer import VisionTransformer\n from art.estimators.certification.derandomized_smoothing.vision_transformers.pytorch import PyTorchVisionTransformer\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchDeRandomizedSmoothing(DeRandomizedSmoothingMixin, PyTorchClassifier):\n \"\"\"\n Interface class for the two De-randomized smoothing approaches supported by ART for PyTorch.\n\n If a regular pytorch neural network is fed in then (De)Randomized Smoothing as introduced in Levine et al. (2020)\n is used.\n\n Otherwise, if a timm vision transformer is fed in then Certified Patch Robustness via Smoothed Vision Transformers\n as introduced in Salman et al. (2021) is used.\n \"\"\"\n\n def __init__(\n self,\n model: str | \"VisionTransformer\" | \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n ablation_size: int,\n algorithm: str = \"salman2021\",\n ablation_type: str = \"column\",\n replace_last_layer: bool | None = None,\n drop_tokens: bool = True,\n load_pretrained: bool = True,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n optimizer_params: dict | None = None,\n channels_first: bool = True,\n threshold: float | None = None,\n logits: bool | None = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n verbose: bool = True,\n **kwargs,\n ):\n \"\"\"\n Create a smoothed classifier.\n\n :param model: Either a CNN or a VIT. For a ViT supply a string specifying which ViT architecture to load from\n the ViT library, or a vision transformer already created with the\n Pytorch Image Models (timm) library. To run Levine et al. (2020) provide a regular pytorch model.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param ablation_size: The size of the data portion to retain after ablation.\n :param algorithm: Either 'salman2021' or 'levine2020'. For salman2021 we support ViTs and CNNs. For levine2020\n there is only CNN support.\n :param replace_last_layer: ViT-specific. If to replace the last layer of the ViT with a fresh layer\n matching the number of classes for the dataset to be examined.\n Needed if going from the pre-trained imagenet models to fine-tune\n on a dataset like CIFAR.\n :param drop_tokens: ViT-specific. If to drop the fully ablated tokens in the ViT\n :param load_pretrained: ViT-specific. If to load a pretrained model matching the ViT name.\n Will only affect the ViT if a string name is passed to model rather than a ViT directly.\n :param optimizer: The optimizer used to train the classifier.\n :param ablation_type: The type of ablation to perform. Either \"column\", \"row\", or \"block\"\n :param threshold: Specific to Levine et al. The minimum threshold to count a prediction.\n :param logits: Specific to Levine et al. If the model returns logits or normalized probabilities\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n\n import torch\n\n if not channels_first:\n raise ValueError(\"Channels must be set to first\")\n logger.info(\"Running algorithm: %s\", algorithm)\n\n # Default value for output shape\n output_shape = input_shape\n self.mode = None\n if importlib.util.find_spec(\"timm\") is not None and algorithm == \"salman2021\":\n from timm.models.vision_transformer import VisionTransformer\n\n if isinstance(model, (VisionTransformer, str)):\n import timm\n from art.estimators.certification.derandomized_smoothing.vision_transformers.pytorch import (\n PyTorchVisionTransformer,\n )\n\n if replace_last_layer is None:\n raise ValueError(\"If using ViTs please specify if the last layer should be replaced\")\n\n # temporarily assign the original method to tmp_func\n tmp_func = timm.models.vision_transformer._create_vision_transformer\n\n # override with ART's ViT creation function\n timm.models.vision_transformer._create_vision_transformer = self.create_vision_transformer\n if isinstance(model, str):\n model = timm.create_model(\n model, pretrained=load_pretrained, drop_tokens=drop_tokens, device_type=device_type\n )\n if replace_last_layer:\n model.head = torch.nn.Linear(model.head.in_features, nb_classes) # type: ignore\n if isinstance(optimizer, type):\n if optimizer_params is not None:\n optimizer = optimizer(model.parameters(), **optimizer_params)\n else:\n raise ValueError(\"If providing an optimiser please also supply its parameters\")\n\n elif isinstance(model, VisionTransformer):\n pretrained_cfg = model.pretrained_cfg\n supplied_state_dict = model.state_dict()\n supported_models = self.get_models()\n if pretrained_cfg[\"architecture\"] not in supported_models: # type: ignore\n raise ValueError(\n \"Architecture not supported. Use PyTorchDeRandomizedSmoothing.get_models() \"\n \"to get the supported model architectures.\"\n )\n model = timm.create_model(\n pretrained_cfg[\"architecture\"], drop_tokens=drop_tokens, device_type=device_type # type: ignore\n )\n model.load_state_dict(supplied_state_dict) # type: ignore\n if replace_last_layer:\n model.head = torch.nn.Linear(model.head.in_features, nb_classes) # type: ignore\n\n if optimizer is not None:\n if not isinstance(optimizer, torch.optim.Optimizer):\n raise ValueError(\"Optimizer error: must be a torch.optim.Optimizer instance\")\n\n converted_optimizer: torch.optim.Adam | torch.optim.SGD\n opt_state_dict = optimizer.state_dict()\n if isinstance(optimizer, torch.optim.Adam):\n logging.info(\"Converting Adam Optimiser\")\n converted_optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) # type: ignore\n elif isinstance(optimizer, torch.optim.SGD):\n logging.info(\"Converting SGD Optimiser\")\n converted_optimizer = torch.optim.SGD(model.parameters(), lr=1e-4) # type: ignore\n else:\n raise ValueError(\"Optimiser not supported for conversion\")\n converted_optimizer.load_state_dict(opt_state_dict)\n\n self.to_reshape = False\n if not isinstance(model, PyTorchVisionTransformer):\n raise ValueError(\"Vision transformer is not of PyTorchViT. Error occurred in PyTorchViT creation.\")\n\n if model.default_cfg[\"input_size\"][0] != input_shape[0]: # type: ignore\n raise ValueError(\n f'ViT requires {model.default_cfg[\"input_size\"][0]} channel input,' # type: ignore\n f\" but {input_shape[0]} channels were provided.\"\n )\n\n if model.default_cfg[\"input_size\"] != input_shape: # type: ignore\n if verbose:\n logger.warning(\n \" ViT expects input shape of: (%i, %i, %i) but (%i, %i, %i) specified as the input shape.\"\n \" The input will be rescaled to (%i, %i, %i)\",\n *model.default_cfg[\"input_size\"], # type: ignore\n *input_shape,\n *model.default_cfg[\"input_size\"], # type: ignore\n )\n\n self.to_reshape = True\n output_shape = model.default_cfg[\"input_size\"] # type: ignore\n\n # set the method back to avoid unexpected side effects later on should timm need to be reused.\n timm.models.vision_transformer._create_vision_transformer = tmp_func\n self.mode = \"ViT\"\n else:\n if isinstance(model, torch.nn.Module):\n self.mode = \"CNN\"\n output_shape = input_shape\n self.to_reshape = False\n\n elif algorithm == \"levine2020\":\n if ablation_type is None or threshold is None or logits is None:\n raise ValueError(\n \"If using CNN please specify if the model returns logits, \"\n \" the prediction threshold, and ablation type\"\n )\n self.mode = \"CNN\"\n # input channels are internally doubled.\n input_shape = (input_shape[0] * 2, input_shape[1], input_shape[2])\n output_shape = input_shape\n self.to_reshape = False\n\n if optimizer is None or isinstance(optimizer, torch.optim.Optimizer):\n super().__init__(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n else:\n raise ValueError(\"Error occurred in optimizer creation\")\n\n self.threshold = threshold\n self.logits = logits\n self.ablation_size = (ablation_size,)\n self.algorithm = algorithm\n self.ablation_type = ablation_type\n if verbose:\n logger.info(self.model)\n\n from art.estimators.certification.derandomized_smoothing.ablators.pytorch import (\n ColumnAblatorPyTorch,\n BlockAblatorPyTorch,\n )\n\n if TYPE_CHECKING:\n self.ablator: ColumnAblatorPyTorch | BlockAblatorPyTorch\n\n if self.mode is None:\n raise ValueError(\"Model type not recognized.\")\n\n if ablation_type in {\"column\", \"row\"}:\n self.ablator = ColumnAblatorPyTorch(\n ablation_size=ablation_size,\n channels_first=True,\n ablation_mode=ablation_type,\n to_reshape=self.to_reshape,\n original_shape=input_shape,\n output_shape=output_shape,\n device_type=device_type,\n algorithm=algorithm,\n mode=self.mode,\n )\n elif ablation_type == \"block\":\n self.ablator = BlockAblatorPyTorch(\n ablation_size=ablation_size,\n channels_first=True,\n to_reshape=self.to_reshape,\n original_shape=input_shape,\n output_shape=output_shape,\n device_type=device_type,\n algorithm=algorithm,\n mode=self.mode,\n )\n else:\n raise ValueError(f\"ablation_type of {ablation_type} not recognized. Must be either column, row, or block\")\n\n @classmethod\n def get_models(cls, generate_from_null: bool = False) -> list[str]:\n \"\"\"\n Return the supported model names to the user.\n\n :param generate_from_null: If to re-check the creation of all the ViTs in timm from scratch.\n :return: A list of compatible models\n \"\"\"\n import timm\n import torch\n\n supported_models = [\n \"vit_base_patch8_224\",\n \"vit_base_patch16_18x2_224\",\n \"vit_base_patch16_224\",\n \"vit_base_patch16_224_miil\",\n \"vit_base_patch16_384\",\n \"vit_base_patch16_clip_224\",\n \"vit_base_patch16_clip_384\",\n \"vit_base_patch16_gap_224\",\n \"vit_base_patch16_plus_240\",\n \"vit_base_patch16_rpn_224\",\n \"vit_base_patch16_xp_224\",\n \"vit_base_patch32_224\",\n \"vit_base_patch32_384\",\n \"vit_base_patch32_clip_224\",\n \"vit_base_patch32_clip_384\",\n \"vit_base_patch32_clip_448\",\n \"vit_base_patch32_plus_256\",\n \"vit_giant_patch14_224\",\n \"vit_giant_patch14_clip_224\",\n \"vit_gigantic_patch14_224\",\n \"vit_gigantic_patch14_clip_224\",\n \"vit_huge_patch14_224\",\n \"vit_huge_patch14_clip_224\",\n \"vit_huge_patch14_clip_336\",\n \"vit_huge_patch14_xp_224\",\n \"vit_large_patch14_224\",\n \"vit_large_patch14_clip_224\",\n \"vit_large_patch14_clip_336\",\n \"vit_large_patch14_xp_224\",\n \"vit_large_patch16_224\",\n \"vit_large_patch16_384\",\n \"vit_large_patch32_224\",\n \"vit_large_patch32_384\",\n \"vit_medium_patch16_gap_240\",\n \"vit_medium_patch16_gap_256\",\n \"vit_medium_patch16_gap_384\",\n \"vit_small_patch16_18x2_224\",\n \"vit_small_patch16_36x1_224\",\n \"vit_small_patch16_224\",\n \"vit_small_patch16_384\",\n \"vit_small_patch32_224\",\n \"vit_small_patch32_384\",\n \"vit_tiny_patch16_224\",\n \"vit_tiny_patch16_384\",\n ]\n\n if not generate_from_null:\n return supported_models\n\n supported = []\n unsupported = []\n\n models = timm.list_models(\"vit_*\")\n pbar = tqdm(models)\n\n # store in case not re-assigned in the model creation due to unsuccessful creation\n tmp_func = timm.models.vision_transformer._create_vision_transformer\n\n for model in pbar:\n pbar.set_description(f\"Testing {model} creation\")\n try:\n _ = cls(\n model=model,\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=torch.optim.SGD, # type: ignore\n optimizer_params={\"lr\": 0.01},\n input_shape=(3, 32, 32),\n nb_classes=10,\n ablation_size=4,\n load_pretrained=False,\n replace_last_layer=True,\n verbose=False,\n )\n supported.append(model)\n except (TypeError, AttributeError):\n unsupported.append(model)\n timm.models.vision_transformer._create_vision_transformer = tmp_func\n\n if supported != supported_models:\n logger.warning(\n \"Difference between the generated and fixed model list. Although not necessarily \"\n \"an error, this may point to the timm library being updated.\"\n )\n\n return supported\n\n @staticmethod\n def create_vision_transformer(\n variant: str, pretrained: bool = False, use_naflex: bool | None = None, **kwargs\n ) -> \"PyTorchVisionTransformer\":\n \"\"\"\n Creates a vision transformer using PyTorchViT which controls the forward pass of the model\n\n :param variant: The name of the vision transformer to load\n :param pretrained: If to load pre-trained weights\n :param use_naflex: If using NaFlexVit.\n :return: A ViT with the required methods needed for ART\n \"\"\"\n\n from timm.models._builder import build_model_with_cfg\n from timm.models.vision_transformer import checkpoint_filter_fn\n from art.estimators.certification.derandomized_smoothing.vision_transformers.pytorch import (\n PyTorchVisionTransformer,\n )\n\n return build_model_with_cfg(\n PyTorchVisionTransformer,\n variant,\n pretrained,\n pretrained_filter_fn=checkpoint_filter_fn,\n **kwargs,\n )\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: Any | None = None,\n verbose: bool = False,\n update_batchnorm: bool = True,\n batchnorm_update_epochs: int = 1,\n transform: \"torchvision.transforms.transforms.Compose\" | None = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: Display training progress bar.\n :param update_batchnorm: ViT specific argument.\n If to run the training data through the model to update any batch norm statistics prior\n to training. Useful on small datasets when using pre-trained ViTs.\n :param batchnorm_update_epochs: ViT specific argument. How many times to forward pass over the training data\n to pre-adjust the batchnorm statistics.\n :param transform: ViT specific argument. Torchvision compose of relevant augmentation transformations to apply.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n if update_batchnorm and self.mode == \"ViT\": # VIT specific\n self.update_batchnorm(x_preprocessed, batch_size, nb_epochs=batchnorm_update_epochs)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n num_batch = len(x_preprocessed) / float(batch_size)\n num_batch = int(np.floor(num_batch)) if drop_last else int(np.ceil(num_batch))\n ind = np.arange(len(x_preprocessed)).tolist()\n\n # Start training\n for _ in tqdm(range(nb_epochs)):\n # Shuffle the examples\n random.shuffle(ind)\n\n epoch_acc = []\n epoch_loss = []\n epoch_batch_sizes = []\n\n pbar = tqdm(range(num_batch), disable=not verbose)\n\n # Train for one epoch\n for m in pbar:\n i_batch = self.ablator.forward(np.copy(x_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]))\n\n if transform is not None and self.mode == \"ViT\": # VIT specific\n i_batch = transform(i_batch)\n\n if isinstance(i_batch, np.ndarray):\n i_batch = torch.from_numpy(i_batch).to(self._device)\n o_batch = torch.from_numpy(y_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]).to(self._device)\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Perform prediction\n try:\n model_outputs = self.model(i_batch)\n except ValueError as err:\n if \"Expected more than 1 value per channel when training\" in str(err):\n logger.exception(\n \"Try dropping the last incomplete batch by setting drop_last=True in \"\n \"method PyTorchClassifier.fit.\"\n )\n raise err\n\n loss = self.loss(model_outputs, o_batch)\n acc = self.get_accuracy(preds=model_outputs, labels=o_batch)\n\n # Do training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self.optimizer.step()\n\n epoch_acc.append(acc)\n epoch_loss.append(loss.cpu().detach().numpy())\n epoch_batch_sizes.append(len(i_batch))\n\n if verbose:\n pbar.set_description(\n f\"Loss {np.average(epoch_loss, weights=epoch_batch_sizes):.3f} \"\n f\"Acc {np.average(epoch_acc, weights=epoch_batch_sizes):.3f} \"\n )\n\n if scheduler is not None:\n scheduler.step()\n\n @staticmethod\n def get_accuracy(preds: np.ndarray | \"torch.Tensor\", labels: np.ndarray | \"torch.Tensor\") -> np.ndarray:\n \"\"\"\n Helper function to get the accuracy during training.\n\n :param preds: model predictions.\n :param labels: ground truth labels (not one hot).\n :return: prediction accuracy.\n \"\"\"\n if not isinstance(preds, np.ndarray):\n preds = preds.detach().cpu().numpy()\n\n if not isinstance(labels, np.ndarray):\n labels = labels.detach().cpu().numpy()\n\n return np.sum(np.argmax(preds, axis=1) == labels) / len(labels)\n\n def update_batchnorm(self, x: np.ndarray, batch_size: int, nb_epochs: int = 1) -> None:\n \"\"\"\n Method to update the batchnorm of a neural network on small datasets when it was pre-trained\n\n :param x: Training data.\n :param batch_size: Size of batches.\n :param nb_epochs: How many times to forward pass over the input data\n \"\"\"\n import torch\n\n if self.mode != \"ViT\":\n raise ValueError(\"Accessing a ViT specific functionality while running in CNN mode\")\n\n self.model.train()\n\n ind = np.arange(len(x))\n num_batch = int(len(x) / float(batch_size))\n\n with torch.no_grad():\n for _ in tqdm(range(nb_epochs)):\n for m in tqdm(range(num_batch)):\n i_batch = self.ablator.forward(\n np.copy(x[ind[m * batch_size : (m + 1) * batch_size]]), column_pos=random.randint(0, x.shape[3])\n )\n _ = self.model(i_batch)\n\n def eval_and_certify(\n self,\n x: np.ndarray,\n y: np.ndarray,\n size_to_certify: int,\n batch_size: int = 128,\n verbose: bool = True,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Evaluates the ViT's normal and certified performance over the supplied data.\n\n :param x: Evaluation data.\n :param y: Evaluation labels.\n :param size_to_certify: The size of the patch to certify against.\n If not provided will default to the ablation size.\n :param batch_size: batch size when evaluating.\n :param verbose: If to display the progress bar\n :return: The accuracy and certified accuracy over the dataset\n \"\"\"\n import torch\n\n self.model.eval()\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n pbar = tqdm(range(num_batch), disable=not verbose)\n accuracy = torch.tensor(0.0).to(self._device)\n cert_sum = torch.tensor(0.0).to(self._device)\n n_samples = 0\n\n with torch.no_grad():\n for m in pbar:\n if m == (num_batch - 1):\n i_batch = np.copy(x_preprocessed[m * batch_size :])\n o_batch = y_preprocessed[m * batch_size :]\n else:\n i_batch = np.copy(x_preprocessed[m * batch_size : (m + 1) * batch_size])\n o_batch = y_preprocessed[m * batch_size : (m + 1) * batch_size]\n\n pred_counts = np.zeros((len(i_batch), self.nb_classes))\n if self.ablation_type in {\"column\", \"row\"}:\n for pos in range(i_batch.shape[-1]):\n ablated_batch = self.ablator.forward(i_batch, column_pos=pos)\n # Perform prediction\n model_outputs = self.model(ablated_batch)\n\n if self.algorithm == \"salman2021\":\n pred_counts[np.arange(0, len(i_batch)), model_outputs.argmax(dim=-1).cpu()] += 1\n else:\n if self.logits:\n model_outputs = torch.nn.functional.softmax(model_outputs, dim=1)\n model_outputs = model_outputs >= self.threshold\n pred_counts += model_outputs.cpu().numpy()\n\n else:\n for column_pos in range(i_batch.shape[-1]):\n for row_pos in range(i_batch.shape[-2]):\n ablated_batch = self.ablator.forward(i_batch, column_pos=column_pos, row_pos=row_pos)\n model_outputs = self.model(ablated_batch)\n\n if self.algorithm == \"salman2021\":\n pred_counts[np.arange(0, len(i_batch)), model_outputs.argmax(dim=-1).cpu()] += 1\n else:\n if self.logits:\n model_outputs = torch.nn.functional.softmax(model_outputs, dim=1)\n model_outputs = model_outputs >= self.threshold\n pred_counts += model_outputs.cpu().numpy()\n\n _, cert_and_correct, top_predicted_class = self.ablator.certify(\n pred_counts, size_to_certify=size_to_certify, label=o_batch\n )\n cert_sum += torch.sum(cert_and_correct)\n o_batch = torch.from_numpy(o_batch).to(self.device)\n accuracy += torch.sum(top_predicted_class == o_batch)\n n_samples += len(cert_and_correct)\n\n pbar.set_description(f\"Normal Acc {accuracy / n_samples:.3f} \" f\"Cert Acc {cert_sum / n_samples:.3f}\")\n\n return (accuracy / n_samples), (cert_sum / n_samples)\n\n def _predict_classifier(\n self, x: np.ndarray | \"torch.Tensor\", batch_size: int, training_mode: bool, **kwargs\n ) -> np.ndarray:\n import torch\n\n if isinstance(x, torch.Tensor):\n x_numpy = x.cpu().numpy()\n\n outputs = PyTorchClassifier.predict(\n self, x=x_numpy, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n\n if self.algorithm == \"levine2020\":\n if not self.logits:\n return np.asarray((outputs >= self.threshold))\n return np.asarray(\n (torch.nn.functional.softmax(torch.from_numpy(outputs), dim=1) >= self.threshold).type( # type: ignore\n torch.int\n )\n )\n return outputs\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Performs cumulative predictions over every ablation location\n\n :param x: Unablated image\n :param batch_size: the batch size for the prediction\n :param training_mode: if to run the classifier in training mode\n :return: cumulative predictions after sweeping over all the ablation configurations.\n \"\"\"\n if self._channels_first:\n columns_in_data = x.shape[-1]\n rows_in_data = x.shape[-2]\n else:\n columns_in_data = x.shape[-2]\n rows_in_data = x.shape[-3]\n\n if self.ablation_type in {\"column\", \"row\"}:\n if self.ablation_type == \"column\":\n ablate_over_range = columns_in_data\n else:\n # image will be transposed, so loop over the number of rows\n ablate_over_range = rows_in_data\n\n for ablation_start in range(ablate_over_range):\n ablated_x = self.ablator.forward(np.copy(x), column_pos=ablation_start)\n if ablation_start == 0:\n preds = self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n else:\n preds += self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n elif self.ablation_type == \"block\":\n for xcorner in range(rows_in_data):\n for ycorner in range(columns_in_data):\n ablated_x = self.ablator.forward(np.copy(x), row_pos=xcorner, column_pos=ycorner)\n if ycorner == 0 and xcorner == 0:\n preds = self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n else:\n preds += self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n\n return preds\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements (De)Randomized Smoothing for Certifiable Defense against Patch Attacks\n\n| Paper link: https://arxiv.org/abs/2002.10733\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom art.estimators.certification.derandomized_smoothing.derandomized import DeRandomizedSmoothingMixin\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE, ABLATOR_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2DeRandomizedSmoothing(TensorFlowV2Classifier, DeRandomizedSmoothingMixin):\n \"\"\"\n Implementation of (De)Randomized Smoothing applied to classifier predictions as introduced\n in Levine et al. (2020).\n\n | Paper link: https://arxiv.org/abs/2002.10733\n \"\"\"\n\n estimator_params = TensorFlowV2Classifier.estimator_params + [\n \"ablation_type\",\n \"ablation_size\",\n \"threshold\",\n \"logits\",\n ]\n\n def __init__(\n self,\n model,\n nb_classes: int,\n ablation_type: str,\n ablation_size: int,\n threshold: float,\n logits: bool,\n input_shape: tuple[int, ...],\n loss_object: \"tf.Tensor\" | None = None,\n optimizer: \"tf.keras.optimizers.Optimizer\" | None = None,\n train_step: Callable | None = None,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ):\n \"\"\"\n Create a derandomized smoothing classifier.\n\n :param model: a python functions or callable class defining the model and providing it prediction as output.\n :type model: `function` or `callable class`\n :param nb_classes: the number of classes in the classification task.\n :param ablation_type: The type of ablation to perform, must be either \"column\" or \"block\"\n :param ablation_size: The size of the data portion to retain after ablation. Will be a column of size N for\n \"column\" ablation type or a NxN square for ablation of type \"block\"\n :param threshold: The minimum threshold to count a prediction.\n :param logits: if the model returns logits or normalized probabilities\n :param input_shape: Shape of one input for the classifier, e.g. for MNIST input_shape=(28, 28, 1).\n :param loss_object: The loss function for which to compute gradients. This parameter is applied for training\n the model and computing gradients of the loss w.r.t. the input.\n :param optimizer: The optimizer used to train the classifier.\n :param train_step: A function that applies a gradient update to the trainable variables with signature\n `train_step(model, images, labels)`. This will override the default training loop that uses the\n provided `loss_object` and `optimizer` parameters. It is recommended to use the `@tf.function`\n decorator, if possible, for efficient training.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n # input channels are internally doubled for the certification algorithm.\n input_shape = (input_shape[0], input_shape[1], input_shape[2] * 2)\n super().__init__(\n model=model,\n nb_classes=nb_classes,\n input_shape=input_shape,\n loss_object=loss_object,\n optimizer=optimizer,\n train_step=train_step,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n self.ablation_type = ablation_type\n self.logits = logits\n self.threshold = threshold\n self._channels_first = channels_first\n\n from art.estimators.certification.derandomized_smoothing.ablators.tensorflow import (\n ColumnAblator,\n BlockAblator,\n )\n\n if TYPE_CHECKING:\n self.ablator: ABLATOR_TYPE\n\n if self.ablation_type in {\"column\", \"row\"}:\n row_ablation_mode = self.ablation_type == \"row\"\n self.ablator = ColumnAblator(\n ablation_size=ablation_size, channels_first=self._channels_first, row_ablation_mode=row_ablation_mode\n )\n elif self.ablation_type == \"block\":\n self.ablator = BlockAblator(ablation_size=ablation_size, channels_first=self._channels_first)\n else:\n raise ValueError(\"Ablation type not supported. Must be either column or block\")\n\n def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:\n import tensorflow as tf\n\n outputs = TensorFlowV2Classifier.predict(\n self, x=x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n if self.logits:\n outputs = tf.nn.softmax(outputs)\n return np.asarray(outputs >= self.threshold).astype(int)\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports\n \"scheduler\" which is an optional function that will be called at the end of every\n epoch to adjust the learning rate.\n \"\"\"\n import tensorflow as tf\n\n if self._train_step is None: # pragma: no cover\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\n \"A loss function `loss_object` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\n \"An optimizer `optimizer` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n\n @tf.function\n def train_step(model, images, labels):\n with tf.GradientTape() as tape:\n predictions = model(images, training=True)\n loss = self.loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n if hasattr(self.optimizer, \"_check_variables_are_known\"):\n self.optimizer._check_variables_are_known = lambda *args, **kwargs: None\n self.optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n return loss, predictions\n\n else:\n train_step = self._train_step\n\n scheduler = kwargs.get(\"scheduler\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n for epoch in tqdm(range(nb_epochs), desc=\"Epochs\"):\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n\n epoch_acc = []\n epoch_loss = []\n epoch_batch_sizes = []\n\n pbar = tqdm(range(num_batch), disable=not verbose)\n\n ind = np.arange(len(x_preprocessed))\n for m in pbar:\n i_batch = np.copy(x_preprocessed[ind[m * batch_size : (m + 1) * batch_size]])\n labels = y_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]\n images = self.ablator.forward(i_batch)\n\n if self._train_step is None:\n loss, predictions = train_step(self.model, images, labels)\n acc = np.sum(np.argmax(predictions.numpy(), axis=1) == np.argmax(labels, axis=1)) / len(labels)\n epoch_acc.append(acc)\n epoch_loss.append(loss.numpy())\n epoch_batch_sizes.append(len(i_batch))\n else:\n train_step(self.model, images, labels)\n\n if verbose:\n if self._train_step is None:\n pbar.set_description(\n f\"Loss {np.average(epoch_loss, weights=epoch_batch_sizes):.3f} \"\n f\"Acc {np.average(epoch_acc, weights=epoch_batch_sizes):.3f} \"\n )\n else:\n pbar.set_description(\"Batches\")\n\n if scheduler is not None:\n scheduler(epoch)\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Performs cumulative predictions over every ablation location\n\n :param x: Unablated image\n :param batch_size: the batch size for the prediction\n :param training_mode: if to run the classifier in training mode\n :return: cumulative predictions after sweeping over all the ablation configurations.\n \"\"\"\n if self._channels_first:\n columns_in_data = x.shape[-1]\n rows_in_data = x.shape[-2]\n else:\n columns_in_data = x.shape[-2]\n rows_in_data = x.shape[-3]\n\n if self.ablation_type in {\"column\", \"row\"}:\n if self.ablation_type == \"column\":\n ablate_over_range = columns_in_data\n else:\n # image will be transposed, so loop over the number of rows\n ablate_over_range = rows_in_data\n\n for ablation_start in range(ablate_over_range):\n ablated_x = self.ablator.forward(np.copy(x), column_pos=ablation_start)\n if ablation_start == 0:\n preds = self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n else:\n preds += self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n elif self.ablation_type == \"block\":\n for xcorner in range(rows_in_data):\n for ycorner in range(columns_in_data):\n ablated_x = self.ablator.forward(np.copy(x), row_pos=xcorner, column_pos=ycorner)\n if ycorner == 0 and xcorner == 0:\n preds = self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n else:\n preds += self._predict_classifier(\n ablated_x, batch_size=batch_size, training_mode=training_mode, **kwargs\n )\n return preds\n\n def eval_and_certify(\n self,\n x: np.ndarray,\n y: np.ndarray,\n size_to_certify: int,\n batch_size: int = 128,\n verbose: bool = True,\n ) -> tuple[\"tf.Tensor\", \"tf.Tensor\"]:\n \"\"\"\n Evaluates the normal and certified performance over the supplied data.\n\n :param x: Evaluation data.\n :param y: Evaluation labels.\n :param size_to_certify: The size of the patch to certify against.\n If not provided will default to the ablation size.\n :param batch_size: batch size when evaluating.\n :param verbose: If to display the progress bar\n :return: The accuracy and certified accuracy over the dataset\n \"\"\"\n import tensorflow as tf\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n pbar = tqdm(range(num_batch), disable=not verbose)\n accuracy = tf.constant(np.array(0.0), dtype=tf.dtypes.int32)\n cert_sum = tf.constant(np.array(0.0), dtype=tf.dtypes.int32)\n n_samples = 0\n\n for m in pbar:\n if m == (num_batch - 1):\n i_batch = np.copy(x_preprocessed[m * batch_size :])\n o_batch = y_preprocessed[m * batch_size :]\n else:\n i_batch = np.copy(x_preprocessed[m * batch_size : (m + 1) * batch_size])\n o_batch = y_preprocessed[m * batch_size : (m + 1) * batch_size]\n\n pred_counts = self.predict(i_batch)\n\n _, cert_and_correct, top_predicted_class = self.ablator.certify(\n pred_counts, size_to_certify=size_to_certify, label=o_batch\n )\n cert_sum += tf.math.reduce_sum(tf.where(cert_and_correct, 1, 0))\n accuracy += tf.math.reduce_sum(tf.where(top_predicted_class == np.argmax(o_batch, axis=-1), 1, 0))\n n_samples += len(cert_and_correct)\n\n pbar.set_description(f\"Normal Acc {accuracy / n_samples:.3f} \" f\"Cert Acc {cert_sum / n_samples:.3f}\")\n return (accuracy / n_samples), (cert_sum / n_samples)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/ablators/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains the ablators for the certified smoothing approaches.\n\"\"\"\n\nimport importlib\n\nfrom art.estimators.certification.derandomized_smoothing.ablators.tensorflow import ColumnAblator, BlockAblator\n\nif importlib.util.find_spec(\"torch\") is not None:\n from art.estimators.certification.derandomized_smoothing.ablators.pytorch import (\n ColumnAblatorPyTorch,\n BlockAblatorPyTorch,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/ablators/ablate.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract base class for the ablators.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n import torch\n\n\nclass BaseAblator(ABC):\n \"\"\"\n Base class defining the methods used for the ablators.\n \"\"\"\n\n @abstractmethod\n def __call__(\n self, x: np.ndarray, column_pos: int | list | None = None, row_pos: int | list | None = None\n ) -> np.ndarray:\n \"\"\"\n Ablate the image x at location specified by \"column_pos\" for the case of column ablation or at the location\n specified by \"column_pos\" and \"row_pos\" in the case of block ablation.\n\n :param x: input image.\n :param column_pos: column position to specify where to retain the image\n :param row_pos: row position to specify where to retain the image. Not used for ablation type \"column\".\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def certify(\n self, pred_counts: np.ndarray, size_to_certify: int, label: np.ndarray | \"tf.Tensor\"\n ) -> tuple[\"tf.Tensor\", \"tf.Tensor\", \"tf.Tensor\"] | tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Checks if based on the predictions supplied the classifications over the ablated datapoints result in a\n certified prediction against a patch attack of size size_to_certify.\n\n :param pred_counts: The cumulative predictions of the classifier over the ablation locations.\n :param size_to_certify: The size of the patch to check against.\n :param label: ground truth labels\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def ablate(self, x: np.ndarray, column_pos: int, row_pos: int) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Ablate the image x at location specified by \"column_pos\" for the case of column ablation or at the location\n specified by \"column_pos\" and \"row_pos\" in the case of block ablation.\n\n :param x: input image.\n :param column_pos: column position to specify where to retain the image\n :param row_pos: row position to specify where to retain the image. Not used for ablation type \"column\".\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def forward(\n self, x: np.ndarray, column_pos: int | None = None, row_pos: int | None = None\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Ablate batch of data at locations specified by column_pos and row_pos\n\n :param x: input image.\n :param column_pos: column position to specify where to retain the image\n :param row_pos: row position to specify where to retain the image. Not used for ablation type \"column\".\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/ablators/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Certified Patch Robustness via Smoothed Vision Transformers\n\n| Paper link Accepted version:\n https://openaccess.thecvf.com/content/CVPR2022/papers/Salman_Certified_Patch_Robustness_via_Smoothed_Vision_Transformers_CVPR_2022_paper.pdf\n\n| Paper link Arxiv version (more detail): https://arxiv.org/pdf/2110.07719.pdf\n\"\"\"\nfrom __future__ import annotations\n\nimport random\n\nimport numpy as np\nimport torch\n\nfrom art.estimators.certification.derandomized_smoothing.ablators.ablate import BaseAblator\n\n\nclass UpSamplerPyTorch(torch.nn.Module):\n \"\"\"\n Resizes datasets to the specified size.\n Usually for upscaling datasets like CIFAR to Imagenet format\n \"\"\"\n\n def __init__(self, input_size: int, final_size: int) -> None:\n \"\"\"\n Creates an upsampler to make the supplied data match the pre-trained ViT format\n\n :param input_size: Size of the current input data\n :param final_size: Desired final size\n \"\"\"\n super().__init__()\n self.upsample = torch.nn.Upsample(scale_factor=final_size / input_size)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Forward pass though the upsampler.\n\n :param x: Input data\n :return: The upsampled input data\n \"\"\"\n return self.upsample(x)\n\n\nclass ColumnAblatorPyTorch(torch.nn.Module, BaseAblator):\n \"\"\"\n Pure Pytorch implementation of stripe/column ablation.\n \"\"\"\n\n def __init__(\n self,\n ablation_size: int,\n channels_first: bool,\n mode: str,\n to_reshape: bool,\n ablation_mode: str = \"column\",\n original_shape: tuple | None = None,\n output_shape: tuple | None = None,\n algorithm: str = \"salman2021\",\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Creates a column ablator\n\n :param ablation_size: The size of the column we will retain.\n :param channels_first: If the input is in channels first format. Currently, required to be True.\n :param mode: If we are running the algorithm using a CNN or VIT.\n :param to_reshape: If the input requires reshaping.\n :param ablation_mode: The type of ablation to perform.\n :param original_shape: Original shape of the input.\n :param output_shape: Input shape expected by the ViT. Usually means upscaling the input to 224 x 224.\n :param algorithm: Either 'salman2021' or 'levine2020'.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n super().__init__()\n\n self.ablation_size = ablation_size\n self.channels_first = channels_first\n self.to_reshape = to_reshape\n self.add_ablation_mask = False\n self.additional_channels = False\n self.algorithm = algorithm\n self.original_shape = original_shape\n self.ablation_mode = ablation_mode\n\n if self.algorithm == \"levine2020\":\n self.additional_channels = True\n if self.algorithm == \"salman2021\" and mode == \"ViT\":\n self.add_ablation_mask = True\n\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self.device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self.device = torch.device(f\"cuda:{cuda_idx}\")\n\n if original_shape is not None and output_shape is not None:\n self.upsample = UpSamplerPyTorch(input_size=original_shape[1], final_size=output_shape[1])\n\n def ablate(self, x: torch.Tensor | np.ndarray, column_pos: int, row_pos: int | None = None) -> torch.Tensor:\n \"\"\"\n Ablates the input column wise\n\n :param x: Input data\n :param column_pos: location to start the retained column. NB, if row_ablation_mode is true then this will\n be used to act on the rows through transposing the image in ColumnAblatorPyTorch.forward\n :param row_pos: Unused.\n :return: The ablated input with 0s where the ablation occurred\n \"\"\"\n k = self.ablation_size\n\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(self.device)\n\n if column_pos + k > x.shape[-1]:\n x[:, :, :, (column_pos + k) % x.shape[-1] : column_pos] = 0.0\n else:\n x[:, :, :, :column_pos] = 0.0\n x[:, :, :, column_pos + k :] = 0.0\n return x\n\n def forward(self, x: torch.Tensor | np.ndarray, column_pos: int | None = None, row_pos=None) -> torch.Tensor:\n \"\"\"\n Forward pass though the ablator. We insert a new channel to keep track of the ablation location.\n\n :param x: Input data\n :param column_pos: The start position of the albation\n :param row_pos: Unused.\n :return: The albated input with an extra channel indicating the location of the ablation\n \"\"\"\n if row_pos is not None:\n raise ValueError(\"Use column_pos for a ColumnAblator. The row_pos argument is unused\")\n\n if self.original_shape is not None and x.shape[1] != self.original_shape[0] and self.algorithm == \"salman2021\":\n raise ValueError(f\"Ablator expected {self.original_shape[0]} input channels. Recived shape of {x.shape[1]}\")\n\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(self.device)\n\n if self.add_ablation_mask:\n ones = torch.torch.ones_like(x[:, 0:1, :, :]).to(self.device)\n x = torch.cat([x, ones], dim=1)\n\n if self.additional_channels:\n x = torch.cat([x, 1.0 - x], dim=1)\n\n if self.original_shape is not None and x.shape[1] != self.original_shape[0] and self.additional_channels:\n raise ValueError(\n f\"Ablator expected {self.original_shape[0]} input channels. Received shape of {x.shape[1]}\"\n )\n\n if self.ablation_mode == \"row\":\n x = torch.transpose(x, 3, 2)\n\n if column_pos is None:\n column_pos = random.randint(0, x.shape[3])\n\n ablated_x = self.ablate(x, column_pos=column_pos)\n\n if self.ablation_mode == \"row\":\n ablated_x = torch.transpose(ablated_x, 3, 2)\n\n if self.to_reshape:\n ablated_x = self.upsample(ablated_x)\n return ablated_x\n\n def certify(\n self,\n pred_counts: torch.Tensor | np.ndarray,\n size_to_certify: int,\n label: torch.Tensor | np.ndarray,\n ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n Performs certification of the predictions\n\n :param pred_counts: The model predictions over the ablated data.\n :param size_to_certify: The patch size we wish to check certification against\n :param label: The ground truth labels\n :return: A tuple consisting of: the certified predictions,\n the predictions which were certified and also correct,\n and the most predicted class across the different ablations on the input.\n \"\"\"\n\n if isinstance(pred_counts, np.ndarray):\n pred_counts = torch.from_numpy(pred_counts).to(self.device)\n\n if isinstance(label, np.ndarray):\n label = torch.from_numpy(label).to(self.device)\n\n num_of_classes = pred_counts.shape[-1]\n\n # NB! argmax and kthvalue handle ties between predicted counts differently.\n # The original implementation: https://github.com/MadryLab/smoothed-vit/blob/main/src/utils/smoothing.py#L98\n # uses argmax for the model predictions\n # (later called y_smoothed https://github.com/MadryLab/smoothed-vit/blob/main/src/utils/smoothing.py#L230)\n # and kthvalue for the certified predictions.\n # to be consistent with the original implementation we also follow this here.\n top_predicted_class_argmax = torch.argmax(pred_counts, dim=1)\n\n top_class_counts, top_predicted_class = pred_counts.kthvalue(num_of_classes, dim=1)\n second_class_counts, second_predicted_class = pred_counts.kthvalue(num_of_classes - 1, dim=1)\n\n cert = (top_class_counts - second_class_counts) > 2 * (size_to_certify + self.ablation_size - 1)\n\n if self.algorithm == \"levine2020\":\n tie_break_certs = (\n (top_class_counts - second_class_counts) == 2 * (size_to_certify + self.ablation_size - 1)\n ) & (top_predicted_class < second_predicted_class)\n cert = torch.logical_or(cert, tie_break_certs)\n\n cert_and_correct = cert & (label == top_predicted_class)\n\n return cert, cert_and_correct, top_predicted_class_argmax\n\n\nclass BlockAblatorPyTorch(torch.nn.Module, BaseAblator):\n \"\"\"\n Pure Pytorch implementation of block ablation.\n \"\"\"\n\n def __init__(\n self,\n ablation_size: int,\n channels_first: bool,\n mode: str,\n to_reshape: bool,\n original_shape: tuple | None = None,\n output_shape: tuple | None = None,\n algorithm: str = \"salman2021\",\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Creates a column ablator\n\n :param ablation_size: The size of the block we will retain.\n :param channels_first: If the input is in channels first format. Currently, required to be True.\n :param mode: If we are running the algorithm using a CNN or VIT.\n :param to_reshape: If the input requires reshaping.\n :param original_shape: Original shape of the input.\n :param output_shape: Input shape expected by the ViT. Usually means upscaling the input to 224 x 224.\n :param algorithm: Either 'salman2021' or 'levine2020'.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n super().__init__()\n\n self.ablation_size = ablation_size\n self.channels_first = channels_first\n self.to_reshape = to_reshape\n self.add_ablation_mask = False\n self.additional_channels = False\n self.algorithm = algorithm\n self.original_shape = original_shape\n\n if self.algorithm == \"levine2020\":\n self.additional_channels = True\n if self.algorithm == \"salman2021\" and mode == \"ViT\":\n self.add_ablation_mask = True\n\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self.device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self.device = torch.device(f\"cuda:{cuda_idx}\")\n\n if original_shape is not None and output_shape is not None:\n self.upsample = UpSamplerPyTorch(input_size=original_shape[1], final_size=output_shape[1])\n\n def ablate(self, x: torch.Tensor | np.ndarray, column_pos: int, row_pos: int) -> torch.Tensor:\n \"\"\"\n Ablates the input block wise\n\n :param x: Input data\n :param column_pos: The start position of the albation\n :param row_pos: The row start position of the albation\n :return: The ablated input with 0s where the ablation occurred\n \"\"\"\n\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(self.device)\n\n k = self.ablation_size\n # Column ablations\n if column_pos + k > x.shape[-1]:\n x[:, :, :, (column_pos + k) % x.shape[-1] : column_pos] = 0.0\n else:\n x[:, :, :, :column_pos] = 0.0\n x[:, :, :, column_pos + k :] = 0.0\n\n # Row ablations\n if row_pos + k > x.shape[-2]:\n x[:, :, (row_pos + k) % x.shape[-2] : row_pos, :] = 0.0\n else:\n x[:, :, :row_pos, :] = 0.0\n x[:, :, row_pos + k :, :] = 0.0\n return x\n\n def forward(\n self, x: torch.Tensor | np.ndarray, column_pos: int | None = None, row_pos: int | None = None\n ) -> torch.Tensor:\n \"\"\"\n Forward pass though the ablator. We insert a new channel to keep track of the ablation location.\n\n :param x: Input data\n :param column_pos: The start position of the albation\n :return: The albated input with an extra channel indicating the location of the ablation if running in\n \"\"\"\n if self.original_shape is not None and x.shape[1] != self.original_shape[0] and self.algorithm == \"salman2021\":\n raise ValueError(f\"Ablator expected {self.original_shape[0]} input channels. Recived shape of {x.shape[1]}\")\n\n if column_pos is None:\n column_pos = random.randint(0, x.shape[3])\n\n if row_pos is None:\n row_pos = random.randint(0, x.shape[2])\n\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(self.device)\n\n if self.add_ablation_mask:\n ones = torch.torch.ones_like(x[:, 0:1, :, :]).to(self.device)\n x = torch.cat([x, ones], dim=1)\n\n if self.additional_channels:\n x = torch.cat([x, 1.0 - x], dim=1)\n\n if self.original_shape is not None and x.shape[1] != self.original_shape[0] and self.additional_channels:\n raise ValueError(f\"Ablator expected {self.original_shape[0]} input channels. Recived shape of {x.shape[1]}\")\n\n ablated_x = self.ablate(x, column_pos=column_pos, row_pos=row_pos)\n\n if self.to_reshape:\n ablated_x = self.upsample(ablated_x)\n return ablated_x\n\n def certify(\n self,\n pred_counts: torch.Tensor | np.ndarray,\n size_to_certify: int,\n label: torch.Tensor | np.ndarray,\n ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n Performs certification of the predictions\n\n :param pred_counts: The model predictions over the ablated data.\n :param size_to_certify: The patch size we wish to check certification against\n :param label: The ground truth labels\n :return: A tuple consisting of: the certified predictions,\n the predictions which were certified and also correct,\n and the most predicted class across the different ablations on the input.\n \"\"\"\n\n if isinstance(pred_counts, np.ndarray):\n pred_counts = torch.from_numpy(pred_counts).to(self.device)\n\n if isinstance(label, np.ndarray):\n label = torch.from_numpy(label).to(self.device)\n\n # NB! argmax and kthvalue handle ties between predicted counts differently.\n # The original implementation: https://github.com/MadryLab/smoothed-vit/blob/main/src/utils/smoothing.py#L145\n # uses argmax for the model predictions\n # (later called y_smoothed https://github.com/MadryLab/smoothed-vit/blob/main/src/utils/smoothing.py#L230)\n # and kthvalue for the certified predictions.\n # to be consistent with the original implementation we also follow this here.\n top_predicted_class_argmax = torch.argmax(pred_counts, dim=1)\n\n num_of_classes = pred_counts.shape[-1]\n\n top_class_counts, top_predicted_class = pred_counts.kthvalue(num_of_classes, dim=1)\n second_class_counts, second_predicted_class = pred_counts.kthvalue(num_of_classes - 1, dim=1)\n\n cert = (top_class_counts - second_class_counts) > 2 * (size_to_certify + self.ablation_size - 1) ** 2\n\n cert_and_correct = cert & (label == top_predicted_class)\n\n if self.algorithm == \"levine2020\":\n tie_break_certs = (\n (top_class_counts - second_class_counts) == 2 * (size_to_certify + self.ablation_size - 1) ** 2\n ) & (top_predicted_class < second_predicted_class)\n cert = torch.logical_or(cert, tie_break_certs)\n return cert, cert_and_correct, top_predicted_class_argmax\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/ablators/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements (De)Randomized Smoothing for Certifiable Defense against Patch Attacks\n\n| Paper link: https://arxiv.org/abs/2002.10733\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom typing import TYPE_CHECKING\nimport random\n\nimport numpy as np\n\nfrom art.estimators.certification.derandomized_smoothing.ablators.ablate import BaseAblator\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\n\nclass ColumnAblator(BaseAblator):\n \"\"\"\n Implements the functionality for albating the image, and retaining only a column\n \"\"\"\n\n def __init__(self, ablation_size: int, channels_first: bool, row_ablation_mode: bool = False):\n \"\"\"\n Creates an ablator which will retain columns by default, or rows if operating in row_ablation_mode\n\n :param ablation_size: Size of the column (or row if running in row_ablation_mode) to retain.\n :param channels_first: If the input data will be in channels first or channels last format.\n :param row_ablation_mode: if True then the ablator will function by retaining rows rather than columns.\n \"\"\"\n super().__init__()\n self.ablation_size = ablation_size\n self.channels_first = channels_first\n self.row_ablation_mode = row_ablation_mode\n\n def __call__(\n self, x: np.ndarray, column_pos: int | list | None = None, row_pos: int | list | None = None\n ) -> np.ndarray:\n \"\"\"\n Performs ablation on the input x. If no column_pos is specified a random location will be selected.\n\n :param x: input image.\n :param column_pos: int indicating the start column to retain across all samples in the batch\n or list of ints of length equal to the number of samples to have a different\n column retained per sample. If not supplied a random location will be selected.\n NB, if row_ablation_mode is true then this will be used to act on the rows through\n transposing the image.\n :param row_pos: Unused\n :return: ablated image keeping only a column.\n \"\"\"\n return self.forward(x=x, column_pos=column_pos)\n\n def certify(\n self, pred_counts: \"tf.Tensor\", size_to_certify: int, label: np.ndarray | \"tf.Tensor\"\n ) -> tuple[\"tf.Tensor\", \"tf.Tensor\", \"tf.Tensor\"]:\n \"\"\"\n Checks if based on the predictions supplied the classifications over the ablated datapoints result in a\n certified prediction against a patch attack of size size_to_certify.\n\n :param preds: The cumulative predictions of the classifier over the ablation locations.\n :param size_to_certify: The size of the patch to check against.\n :param label: Ground truth labels\n :return: A tuple consisting of: the certified predictions,\n the predictions which were certified and also correct,\n and the most predicted class across the different ablations on the input.\n \"\"\"\n import tensorflow as tf\n\n result = tf.math.top_k(pred_counts, k=2)\n\n top_predicted_class, second_predicted_class = result.indices[:, 0], result.indices[:, 1]\n top_class_counts, second_class_counts = result.values[:, 0], result.values[:, 1]\n\n certs = (top_class_counts - second_class_counts) > 2 * (size_to_certify + self.ablation_size - 1)\n\n tie_break_certs = (\n (top_class_counts - second_class_counts) == 2 * (size_to_certify + self.ablation_size - 1)\n ) & (top_predicted_class < second_predicted_class)\n cert = tf.math.logical_or(certs, tie_break_certs)\n\n # NB, newer versions of pylint do not require this disabled.\n if label.ndim > 1:\n cert_and_correct = cert & (\n tf.math.argmax(label, axis=1) == tf.cast(top_predicted_class, dtype=tf.math.argmax(label, axis=1).dtype)\n )\n else:\n cert_and_correct = cert & (label == tf.cast(top_predicted_class, dtype=label.dtype))\n\n return cert, cert_and_correct, top_predicted_class\n\n def ablate(self, x: np.ndarray, column_pos: int, row_pos: int | None = None) -> np.ndarray:\n \"\"\"\n Ablates the image only retaining a column starting at \"pos\" of width \"self.ablation_size\"\n\n :param x: input image.\n :param column_pos: location to start the retained column. NB, if row_ablation_mode is true then this will\n be used to act on the rows through transposing the image.\n :param row_pos: Unused.\n :return: ablated image keeping only a column.\n \"\"\"\n if self.row_ablation_mode:\n x = np.transpose(x, (0, 1, 3, 2))\n\n k = self.ablation_size\n num_of_image_columns = x.shape[-1]\n\n if column_pos + k > num_of_image_columns:\n start_of_ablation = column_pos + k - num_of_image_columns\n x[:, :, :, start_of_ablation:column_pos] = 0.0\n else:\n x[:, :, :, :column_pos] = 0.0\n x[:, :, :, column_pos + k :] = 0.0\n\n if self.row_ablation_mode:\n x = np.transpose(x, (0, 1, 3, 2))\n\n return x\n\n def forward(\n self, x: np.ndarray, column_pos: int | list | None = None, row_pos: int | list | None = None\n ) -> np.ndarray:\n \"\"\"\n Performs ablation on the input x. If no column_pos is specified a random location will be selected.\n\n :param x: input batch.\n :param column_pos: int indicating the start column to retain across all samples in the batch\n or list of ints of length equal to the number of samples to have a different\n column retained per sample. If not supplied a random location will be selected.\n NB, if row_ablation_mode is true then this will be used to act on the rows through\n transposing the image.\n :param row_pos: Unused.\n :return: Batch ablated according to the locations in column_pos. Data is channel extended to indicate to a\n model if a position is ablated.\n \"\"\"\n if not self.channels_first:\n x = np.transpose(x, (0, 3, 1, 2))\n\n x = np.concatenate([x, 1.0 - x], axis=1)\n\n if column_pos is None:\n column_pos = random.randint(0, x.shape[3])\n\n if isinstance(column_pos, list):\n assert len(column_pos) == len(x)\n for i, pos in enumerate(column_pos):\n x[i : i + 1] = self.ablate(x[i : i + 1], pos)\n else:\n x = self.ablate(x, column_pos)\n\n if not self.channels_first:\n x = np.transpose(x, (0, 2, 3, 1))\n\n return x\n\n\nclass BlockAblator(BaseAblator):\n \"\"\"\n Implements the functionality for albating the image, and retaining only a block\n \"\"\"\n\n def __init__(self, ablation_size: int, channels_first: bool):\n \"\"\"\n Creates an ablator which will retain blocks of the input data.\n\n :param ablation_size: Size of the column (or row if running in row_ablation_mode) to retain.\n :param channels_first: If the input data will be in channels first or channels last format.\n \"\"\"\n super().__init__()\n self.ablation_size = ablation_size\n self.channels_first = channels_first\n\n def __call__(\n self, x: np.ndarray, column_pos: int | list | None = None, row_pos: int | list | None = None\n ) -> np.ndarray:\n \"\"\"\n Performs ablation on the input x. If no row_pos/column_pos is specified a random location will be selected.\n\n :param x: input data\n :param column_pos: Specifies the column index to retain the image block. Either an int to apply the same\n position to all images in a batch, or a list of ints to apply a different\n column position per datapoint.\n :param row_pos: Specifies the row index to retain the image block. Either an int to apply the same position to\n all images in a batch, or a list of ints to apply a different row position per datapoint.\n :return: Data ablated at all locations aside from the specified block. Data is channel extended to indicate to a\n model if a position is ablated.\n \"\"\"\n return self.forward(x=x, row_pos=row_pos, column_pos=column_pos)\n\n def certify(\n self, pred_counts: \"tf.Tensor\" | np.ndarray, size_to_certify: int, label: np.ndarray | \"tf.Tensor\"\n ) -> tuple[\"tf.Tensor\", \"tf.Tensor\", \"tf.Tensor\"]:\n \"\"\"\n Checks if based on the predictions supplied the classifications over the ablated datapoints result in a\n certified prediction against a patch attack of size size_to_certify.\n\n :param pred_counts: The cumulative predictions of the classifier over the ablation locations.\n :param size_to_certify: The size of the patch to check against.\n :param label: Ground truth labels\n :return: A tuple consisting of: the certified predictions,\n the predictions which were certified and also correct,\n and the most predicted class across the different ablations on the input.\n \"\"\"\n import tensorflow as tf\n\n result = tf.math.top_k(pred_counts, k=2)\n\n top_predicted_class, second_predicted_class = result.indices[:, 0], result.indices[:, 1]\n top_class_counts, second_class_counts = result.values[:, 0], result.values[:, 1]\n\n certs = (top_class_counts - second_class_counts) > 2 * (size_to_certify + self.ablation_size - 1) ** 2\n tie_break_certs = (\n (top_class_counts - second_class_counts) == 2 * (size_to_certify + self.ablation_size - 1) ** 2\n ) & (top_predicted_class < second_predicted_class)\n cert = tf.math.logical_or(certs, tie_break_certs)\n\n # NB, newer versions of pylint do not require this disabled.\n if label.ndim > 1:\n cert_and_correct = cert & (\n tf.math.argmax(label, axis=1) == tf.cast(top_predicted_class, dtype=tf.math.argmax(label, axis=1).dtype)\n )\n else:\n cert_and_correct = cert & (label == tf.cast(top_predicted_class, dtype=label.dtype))\n\n return cert, cert_and_correct, top_predicted_class\n\n def forward(\n self,\n x: np.ndarray,\n column_pos: int | list | None = None,\n row_pos: int | list | None = None,\n ) -> np.ndarray:\n \"\"\"\n Performs ablation on the input x. If no column_pos/row_pos are specified a random location will be selected.\n\n :param x: input data\n :param row_pos: Specifies the row index to retain the image block. Either an int to apply the same position to\n all images in a batch, or a list of ints to apply a different row position per datapoint.\n :param column_pos: Specifies the column index to retain the image block. Either an int to apply the same\n position to all images in a batch, or a list of ints to apply a different\n column position per datapoint.\n :return: Data ablated at all locations aside from the specified block. Data is channel extended to indicate to a\n model if a position is ablated.\n \"\"\"\n if not self.channels_first:\n x = np.transpose(x, (0, 3, 1, 2))\n\n if row_pos is None:\n row_pos = random.randint(0, x.shape[2])\n if column_pos is None:\n column_pos = random.randint(0, x.shape[3])\n\n x = np.concatenate([x, 1.0 - x], axis=1)\n\n if isinstance(row_pos, list) and isinstance(column_pos, list):\n for i, (row, col) in enumerate(zip(row_pos, column_pos)):\n x[i : i + 1] = self.ablate(x[i : i + 1], row_pos=row, column_pos=col)\n elif isinstance(row_pos, int) and isinstance(column_pos, int):\n x = self.ablate(x, row_pos=row_pos, column_pos=column_pos)\n\n if not self.channels_first:\n x = np.transpose(x, (0, 2, 3, 1))\n return x\n\n def ablate(self, x: np.ndarray, column_pos: int, row_pos: int) -> np.ndarray:\n \"\"\"\n Ablates the image only retaining a block starting at (row_pos, column_pos) of height/width \"self.ablation_size\"\n\n :param x: input data\n :param row_pos: Specifies the row index where to retain the image block.\n :param column_pos: Specifies the column index where to retain the image block.\n :return: Data ablated at all locations aside from the specified block.\n \"\"\"\n k = self.ablation_size\n # Column ablations\n if column_pos + k > x.shape[-1]:\n x[:, :, :, (column_pos + k) % x.shape[-1] : column_pos] = 0.0\n else:\n x[:, :, :, :column_pos] = 0.0\n x[:, :, :, column_pos + k :] = 0.0\n\n # Row ablations\n if row_pos + k > x.shape[-2]:\n x[:, :, (row_pos + k) % x.shape[-2] : row_pos, :] = 0.0\n else:\n x[:, :, :row_pos, :] = 0.0\n x[:, :, row_pos + k :, :] = 0.0\n return x\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/derandomized_smoothing/vision_transformers/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# PatchEmbed class adapted from the implementation in https://github.com/MadryLab/smoothed-vit\n#\n# Original License:\n#\n# MIT License\n#\n# Copyright (c) 2021 Madry Lab\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE\n\n\"\"\"\nImplements functionality for running Vision Transformers in ART\n\"\"\"\nfrom __future__ import annotations\n\nimport torch\nfrom timm.models.vision_transformer import VisionTransformer\n\n\nclass PatchEmbed(torch.nn.Module):\n \"\"\"\n Image to Patch Embedding\n\n Class adapted from the implementation in https://github.com/MadryLab/smoothed-vit\n\n Original License stated above.\n \"\"\"\n\n def __init__(self, patch_size: int = 16, in_channels: int = 1, embed_dim: int = 768):\n \"\"\"\n Specifies the configuration for the convolutional layer.\n\n :param patch_size: The patch size used by the ViT.\n :param in_channels: Number of input channels.\n :param embed_dim: The embedding dimension used by the ViT.\n \"\"\"\n super().__init__()\n self.patch_size = patch_size\n self.in_channels = in_channels\n self.embed_dim = embed_dim\n self.proj: torch.nn.Conv2d | None = None\n\n def create(self, patch_size=None, embed_dim=None, device=\"cpu\", **kwargs) -> None:\n \"\"\"\n Creates a convolution that mimics the embedding layer to be used for the ablation mask to\n track where the image was ablated.\n\n :param patch_size: The patch size used by the ViT.\n :param embed_dim: The embedding dimension used by the ViT.\n :param device: Which device to set the embedding layer to.\n :param kwargs: Handles the remaining kwargs from the ViT configuration.\n \"\"\"\n\n if patch_size is not None:\n self.patch_size = patch_size\n if embed_dim is not None:\n self.embed_dim = embed_dim\n\n self.proj = torch.nn.Conv2d(\n in_channels=self.in_channels,\n out_channels=self.embed_dim,\n kernel_size=self.patch_size,\n stride=self.patch_size,\n bias=False,\n )\n w_shape = self.proj.weight.shape\n self.proj.weight = torch.nn.Parameter(torch.ones(w_shape).to(device))\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Forward pass through the embedder. We are simply tracking the positions of the ablation mask so no gradients\n are required.\n\n :param x: Input data corresponding to the ablation mask\n :return: The embedded input\n \"\"\"\n if self.proj is not None:\n with torch.no_grad():\n x = self.proj(x).flatten(2).transpose(1, 2)\n return x\n raise ValueError(\"Projection layer not yet created.\")\n\n\nclass PyTorchVisionTransformer(VisionTransformer):\n \"\"\"\n Model-specific class to define the forward pass of the Vision Transformer (ViT) in PyTorch.\n \"\"\"\n\n # Make as a class attribute to avoid being included in the\n # state dictionaries of the ViT Model.\n ablation_mask_embedder = PatchEmbed(in_channels=1)\n\n def __init__(self, **kwargs):\n \"\"\"\n Create a PyTorchVisionTransformer instance\n\n :param kwargs: keyword arguments required to create the mask embedder and the vision transformer class\n \"\"\"\n self.to_drop_tokens = kwargs[\"drop_tokens\"]\n\n if kwargs[\"device_type\"] == \"cpu\" or not torch.cuda.is_available():\n self.device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self.device = torch.device(f\"cuda:{cuda_idx}\")\n\n del kwargs[\"drop_tokens\"]\n del kwargs[\"device_type\"]\n\n super().__init__(**kwargs)\n self.ablation_mask_embedder.create(device=self.device, **kwargs)\n\n self.in_chans = kwargs[\"in_chans\"]\n self.img_size = kwargs[\"img_size\"]\n\n @staticmethod\n def drop_tokens(x: torch.Tensor, indexes: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Drops the tokens which correspond to fully masked inputs\n\n :param x: Input data\n :param indexes: positions to be ablated\n :return: Input with tokens dropped where the input was fully ablated.\n \"\"\"\n x_no_cl, cls_token = x[:, 1:], x[:, 0:1]\n shape = x_no_cl.shape\n\n # reshape to temporarily remove batch\n x_no_cl = torch.reshape(x_no_cl, shape=(-1, shape[-1]))\n indexes = torch.reshape(indexes, shape=(-1,))\n indexes = indexes.nonzero(as_tuple=True)[0]\n x_no_cl = torch.index_select(x_no_cl, dim=0, index=indexes)\n x_no_cl = torch.reshape(x_no_cl, shape=(shape[0], -1, shape[-1]))\n return torch.cat((cls_token, x_no_cl), dim=1)\n\n def forward_features(self, x: torch.Tensor, attn_mask: torch.Tensor | None = None) -> torch.Tensor:\n \"\"\"\n The forward pass of the ViT.\n\n :param x: Input data.\n :param attn_mask: Attention mask.\n :return: The input processed by the ViT backbone\n \"\"\"\n\n ablated_input = False\n if x.shape[1] == self.in_chans + 1:\n ablated_input = True\n\n if ablated_input:\n x, ablation_mask = x[:, : self.in_chans], x[:, self.in_chans : self.in_chans + 1]\n\n x = self.patch_embed(x)\n x = self._pos_embed(x)\n\n if self.to_drop_tokens and ablated_input:\n ones = self.ablation_mask_embedder(ablation_mask)\n to_drop = torch.sum(ones, dim=2)\n indexes = torch.gt(torch.where(to_drop > 1, 1, 0), 0)\n x = self.drop_tokens(x, indexes)\n\n x = self.norm_pre(x)\n x = self.blocks(x)\n return self.norm(x)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/interval/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nInterval based certification estimators.\n\"\"\"\n\nfrom art.estimators.certification.interval.interval import PyTorchIntervalDense\nfrom art.estimators.certification.interval.interval import PyTorchIntervalConv2D\nfrom art.estimators.certification.interval.interval import PyTorchIntervalReLU\nfrom art.estimators.certification.interval.interval import PyTorchIntervalFlatten\nfrom art.estimators.certification.interval.interval import PyTorchIntervalBounds\nfrom art.estimators.certification.interval.pytorch import PyTorchIBPClassifier\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/interval/interval.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Interval bound propagation based layers\n\n| Paper link: https://ieeexplore.ieee.org/document/8418593\n\"\"\"\nfrom __future__ import annotations\n\nimport torch\nimport numpy as np\n\n\nclass PyTorchIntervalDense(torch.nn.Module):\n \"\"\"\n Class implementing a dense layer for the interval (box) domain.\n \"\"\"\n\n def __init__(self, in_features: int, out_features: int):\n super().__init__()\n\n self.weight = torch.nn.Parameter(\n torch.normal(mean=torch.zeros(out_features, in_features), std=torch.ones(out_features, in_features))\n )\n self.bias = torch.nn.Parameter(torch.normal(mean=torch.zeros(out_features), std=torch.ones(out_features)))\n\n def __call__(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n return self.forward(x)\n\n def forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Performs the forward pass of the dense layer in the interval (box) domain.\n\n :param x: interval representation of the datapoint.\n :return: output of the convolutional layer on x\n \"\"\"\n center = (x[:, 1] + x[:, 0]) / 2\n radius = (x[:, 1] - x[:, 0]) / 2\n\n center = torch.matmul(center, torch.transpose(self.weight, 0, 1)) + self.bias\n radius = torch.matmul(radius, torch.abs(torch.transpose(self.weight, 0, 1)))\n\n center = torch.unsqueeze(center, dim=1)\n radius = torch.unsqueeze(radius, dim=1)\n\n return torch.cat([center - radius, center + radius], dim=1)\n\n def concrete_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Performs the forward pass of the dense layer.\n\n :param x: concrete input to the convolutional layer.\n :return: output of the convolutional layer on x\n \"\"\"\n return torch.matmul(x, torch.transpose(self.weight, 0, 1)) + self.bias\n\n\nclass PyTorchIntervalConv2D(torch.nn.Module):\n \"\"\"\n Class implementing a convolutional layer in the interval/box domain.\n \"\"\"\n\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n kernel_size: int | tuple[int, int],\n input_shape: tuple[int, ...],\n device: str | \"torch.device\",\n stride: int | tuple[int, int] = 1,\n padding: int | tuple[int, int] = 0,\n dilation: int | tuple[int, int] = 0,\n bias: bool = True,\n supplied_input_weights: \"torch.Tensor\" | None = None,\n supplied_input_bias: \"torch.Tensor\" | None = None,\n to_debug: bool = False,\n ):\n \"\"\"\n Creates the equivalent dense weights for the specified convolutional layer.\n\n :param in_channels: Number of input channels\n :param out_channels: Number of output channels\n :param kernel_size: Shape of the convolutional kernel\n :param device: Device to put the weights onto\n :param stride: The convolution's stride\n :param padding: Size of padding to use\n :param dilation: Dilation to apply to the convolution\n :param bias: If to include a bias term\n :param supplied_input_weights: Load in a pre-defined set of convolutional weights with the correct specification\n :param supplied_input_bias: Load in a pre-defined set of convolutional bias with the correct specification\n :param to_debug: Helper parameter to help with debugging.\n \"\"\"\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.padding = padding\n self.dilation = dilation\n self.stride = stride\n self.device = device\n self.include_bias = bias\n self.cnn: \"torch.nn.Conv2d\" | None = None\n\n super().__init__()\n self.conv = torch.nn.Conv2d(\n in_channels=1,\n out_channels=out_channels * in_channels,\n kernel_size=kernel_size,\n padding=padding,\n dilation=dilation,\n bias=False,\n stride=stride,\n ).to(device)\n self.bias_to_grad = None\n\n if bias:\n self.bias_to_grad = torch.nn.Parameter(torch.rand(out_channels).to(device))\n\n if to_debug:\n self.conv_debug = torch.nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n bias=bias,\n stride=stride,\n padding=padding,\n dilation=dilation,\n ).to(device)\n\n if isinstance(kernel_size, tuple):\n self.conv.weight = torch.nn.Parameter(\n torch.reshape(\n torch.tensor(self.conv_debug.weight.data.cpu().detach().numpy()),\n (out_channels * in_channels, 1, kernel_size[0], kernel_size[1]),\n ).to(device)\n )\n else:\n self.conv.weight = torch.nn.Parameter(\n torch.reshape(\n torch.tensor(self.conv_debug.weight.data.cpu().detach().numpy()),\n (out_channels * in_channels, 1, kernel_size, kernel_size),\n ).to(device)\n )\n if bias and self.conv_debug.bias is not None:\n self.bias_to_grad = torch.nn.Parameter(\n torch.tensor(self.conv_debug.bias.data.cpu().detach().numpy()).to(device)\n )\n\n if supplied_input_weights is not None:\n if isinstance(kernel_size, tuple):\n self.conv.weight = torch.nn.Parameter(\n torch.reshape(\n supplied_input_weights,\n (out_channels * in_channels, 1, kernel_size[0], kernel_size[1]),\n )\n )\n else:\n self.conv.weight = torch.nn.Parameter(\n torch.reshape(supplied_input_weights, (out_channels * in_channels, 1, kernel_size, kernel_size))\n )\n\n if supplied_input_bias is not None:\n self.bias_to_grad = torch.nn.Parameter(supplied_input_bias.to(device))\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.input_height = input_shape[2]\n self.input_width = input_shape[3]\n\n self.output_height: int = 0\n self.output_width: int = 0\n\n self.dense_weights, self.bias = self.convert_to_dense(device)\n\n self.dense_weights = self.dense_weights.to(device)\n if self.bias is not None:\n self.bias = self.bias.to(device)\n\n def re_convert(self, device: str | \"torch.device\") -> None:\n \"\"\"\n Re converts the weights into a dense equivalent layer.\n Must be called after every backwards if multiple gradients wish to be taken (like for crafting pgd).\n \"\"\"\n self.dense_weights, self.bias = self.convert_to_dense(device)\n self.dense_weights = self.dense_weights.to(device)\n if self.bias is not None:\n self.bias = self.bias.to(device)\n\n def convert_to_dense(self, device: str | \"torch.device\") -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Converts the initialised convolutional layer into an equivalent dense layer.\n\n This function was adapted from:\n https://github.com/deepmind/interval-bound-propagation/blob/217a14d12686e08ebb5cfea1f2748cce58a55913/interval_bound_propagation/src/layer_utils.py#L90\n\n Here, we adapt the tf1 functionality to work with pytorch.\n\n Original license:\n\n coding=utf-8\n\n Copyright 2019 The Interval Bound Propagation Authors.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n See the License for the specific language governing permissions and\n limitations under the License.\n\n :return: The dense weights and bias equivalent to a Conv layer.\n \"\"\"\n\n diagonal_input = torch.reshape(\n torch.eye(self.input_height * self.input_width),\n shape=[self.input_height * self.input_width, 1, self.input_height, self.input_width],\n ).to(device)\n conv_output = self.conv(diagonal_input)\n self.output_height = int(conv_output.shape[2])\n self.output_width = int(conv_output.shape[3])\n\n # conv is of shape (input_height * input_width, out_channels * in_channels, output_height, output_width).\n # Reshape it to (input_height * input_width * output_channels,\n # output_height * output_width * input_channels).\n\n weights = torch.reshape(\n conv_output,\n shape=(\n [\n self.input_height * self.input_width,\n self.out_channels,\n self.in_channels,\n self.output_height,\n self.output_width,\n ]\n ),\n )\n weights = torch.permute(weights, (2, 0, 1, 3, 4))\n weights = torch.reshape(\n weights,\n shape=(\n [\n self.input_height * self.input_width * self.in_channels,\n self.output_height * self.output_width * self.out_channels,\n ]\n ),\n )\n\n if self.bias_to_grad is not None:\n self.bias = torch.unsqueeze(self.bias_to_grad, dim=-1)\n bias = self.bias.expand(-1, self.output_height * self.output_width)\n bias = bias.flatten()\n else:\n bias = None\n return torch.transpose(weights, 0, 1), bias\n\n def forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Performs the forward pass of the convolutional layer in the interval (box) domain by using\n the equivalent dense representation.\n\n :param x: interval representation of the datapoint.\n :return: output of the convolutional layer on x\n \"\"\"\n if self.bias is None:\n raise ValueError(\"self.bias is None, therefore this function cannot calculate the forward pass.\")\n\n x = torch.reshape(x, (x.shape[0], 2, -1))\n\n center = (x[:, 1] + x[:, 0]) / 2\n radius = (x[:, 1] - x[:, 0]) / 2\n\n center = torch.matmul(center, torch.transpose(self.dense_weights, 0, 1)) + self.bias\n radius = torch.matmul(radius, torch.abs(torch.transpose(self.dense_weights, 0, 1)))\n\n center = torch.unsqueeze(center, dim=1)\n radius = torch.unsqueeze(radius, dim=1)\n\n x = torch.cat([center - radius, center + radius], dim=1)\n return x.reshape((-1, 2, self.out_channels, self.output_height, self.output_width))\n\n def concrete_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Performs the forward pass using the equivalent dense representation of the convolutional layer.\n\n :param x: concrete input to the convolutional layer.\n :return: output of the convolutional layer on x\n \"\"\"\n x = torch.reshape(x, (x.shape[0], -1))\n if self.bias is None:\n x = torch.matmul(x, torch.transpose(self.dense_weights, 0, 1))\n else:\n x = torch.matmul(x, torch.transpose(self.dense_weights, 0, 1)) + self.bias\n return x.reshape((-1, self.out_channels, self.output_height, self.output_width))\n\n def conv_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Method for efficiently interfacing with adversarial attacks.\n\n Backpropagating through concrete_forward is too slow if adversarial attacks need to be generated on-the fly\n or require a large amount of iterations.\n\n This method will create a regular conv layer with the right parameters to use.\n\n :param x: concrete input to the convolutional layer.\n :return: output of the convolutional layer on x\n \"\"\"\n if self.cnn is None:\n self.cnn = torch.nn.Conv2d(\n in_channels=self.in_channels,\n out_channels=self.out_channels,\n kernel_size=self.kernel_size,\n bias=self.include_bias,\n stride=self.stride,\n padding=self.padding,\n dilation=self.dilation,\n ).to(self.device)\n if isinstance(self.kernel_size, tuple):\n self.cnn.weight.data = torch.reshape(\n torch.tensor(self.conv.weight.data.cpu().detach().numpy()),\n (self.out_channels, self.in_channels, self.kernel_size[0], self.kernel_size[1]),\n ).to(self.device)\n else:\n self.cnn.weight.data = torch.reshape(\n torch.tensor(self.conv.weight.data.cpu().detach().numpy()),\n (self.out_channels, self.in_channels, self.kernel_size, self.kernel_size),\n ).to(self.device)\n if self.cnn.bias is not None and self.bias_to_grad is not None:\n self.cnn.bias.data = torch.tensor(self.bias_to_grad.data.cpu().detach().numpy()).to(self.device)\n\n if self.cnn is not None:\n return self.cnn(x)\n raise ValueError(\"The convolutional layer for attack mode was not created properly\")\n\n\nclass PyTorchIntervalFlatten(torch.nn.Module):\n \"\"\"\n Layer to handle flattening on both interval and concrete data\n \"\"\"\n\n def __call__(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n return self.concrete_forward(x)\n\n @staticmethod\n def forward(x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Flattens the provided abstract input\n\n :param x: datapoint in the interval domain\n :return: Flattened input preserving the batch and bounds dimensions.\n \"\"\"\n return torch.reshape(x, (x.shape[0], 2, -1))\n\n @staticmethod\n def concrete_forward(x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Flattens the provided concrete input\n\n :param x: datapoint in the concrete domain\n :return: Flattened input preserving the batch dimension.\n \"\"\"\n return torch.reshape(x, (x.shape[0], -1))\n\n\nclass PyTorchIntervalReLU(torch.nn.Module):\n \"\"\"\n ReLU-activation on both interval and concrete data\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.activation = torch.nn.ReLU()\n\n def __call__(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n return self.forward(x)\n\n def forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Abstract pass through the ReLU function\n\n :param x: abstract input to the activation function.\n :return: abstract outputs from the ReLU.\n \"\"\"\n return self.activation(x)\n\n def concrete_forward(self, x: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Concrete pass through the ReLU function\n\n :param x: concrete input to the activation function.\n :return: concrete outputs from the ReLU.\n \"\"\"\n return self.activation(x)\n\n\nclass PyTorchIntervalBounds:\n \"\"\"\n Class providing functionality for computing operations related to interval bounds\n \"\"\"\n\n def __init__(\n self,\n *args,\n **kwargs,\n ) -> None:\n super().__init__(*args, **kwargs) # type: ignore\n\n @staticmethod\n def certify(preds: np.ndarray, labels: np.ndarray) -> np.ndarray:\n \"\"\"\n Check if the data has been certifiably classified correct.\n\n :param preds: interval predictions\n :param labels: associated labels (not one-hot encoded).\n :return: array of True or False if predictions are certifiable\n \"\"\"\n\n cert_bounds = np.copy(preds[:, 1]) # Take the upper bounds of all the predictions\n for i, label in enumerate(labels):\n cert_bounds[i, label] = preds[i, 0, label] # Replace the correct prediction with its lower bound\n return np.argmax(cert_bounds, axis=1) == labels\n\n @staticmethod\n def concrete_to_interval(\n x: np.ndarray,\n bounds: float | list[float] | np.ndarray,\n limits: list[float] | np.ndarray | None = None,\n ) -> np.ndarray:\n \"\"\"\n Helper function converts a datapoint it into its interval representation\n\n :param x: input datapoint of shape [batch size, feature_1, feature_2, ...]\n :param bounds: Either a scalar to apply to the whole datapoint, or an array of [2, feature_1, feature_2]\n where bounds[0] are the lower bounds and bounds[1] are the upper bound\n :param limits: if to clip to a range with limits[0] being the lower bounds and limits[1] being upper bounds.\n :return: Data of the form [batch_size, 2, feature_1, feature_2, ...]\n where [batch_size, 0, x.shape] are the lower bounds and [batch_size, 1, x.shape] are the upper bounds.\n \"\"\"\n\n x = np.expand_dims(x, axis=1)\n\n if isinstance(bounds, float):\n up_x = x + bounds\n lb_x = x - bounds\n elif isinstance(bounds, (list, np.ndarray)):\n up_x = x + bounds[1]\n lb_x = x - bounds[0]\n else:\n raise ValueError(\"Bounds must be a float, list, or numpy array.\")\n\n final_batched_input = np.concatenate((lb_x, up_x), axis=1)\n\n if limits is not None:\n return np.clip(final_batched_input, limits[0], limits[1])\n\n return final_batched_input\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/interval/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements certification using interval (box) domain certification.\n\n| Paper link: https://ieeexplore.ieee.org/document/8418593\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import Any, TYPE_CHECKING\n\nimport logging\nimport warnings\n\nimport numpy as np\nimport torch\n\nfrom art.estimators.certification.interval.interval import (\n PyTorchIntervalConv2D,\n PyTorchIntervalDense,\n PyTorchIntervalReLU,\n PyTorchIntervalBounds,\n)\nfrom art.estimators.classification.pytorch import PyTorchClassifier\n\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\n\nclass ConvertedModel(torch.nn.Module):\n \"\"\"\n Class which converts the supplied pytorch model into an equivalent model\n which uses abstract operations\n \"\"\"\n\n def __init__(self, model: \"torch.nn.Module\", channels_first: bool, input_shape: tuple[int, ...]):\n super().__init__()\n modules = []\n self.interim_shapes: list[tuple] = []\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.forward_mode: str\n self.forward_mode = \"abstract\"\n self.reshape_op_num = -1\n\n def forward_hook(input_module, hook_input, hook_output):\n modules.append(input_module)\n self.interim_shapes.append(tuple(hook_input[0].shape))\n\n for module in model.children():\n module.register_forward_hook(forward_hook)\n\n if channels_first:\n input_for_hook = torch.rand(input_shape).to(self.device)\n else:\n raise ValueError(\"Please provide data in channels first format\")\n\n input_for_hook = torch.unsqueeze(input_for_hook, dim=0)\n model(input_for_hook) # hooks are fired sequentially from model input to the output\n\n self.ops = torch.nn.ModuleList()\n for module, shapes in zip(modules, self.interim_shapes):\n weights_to_supply = None\n bias_to_supply = None\n if isinstance(module, torch.nn.modules.conv.Conv2d):\n if module.weight is not None:\n weights_to_supply = torch.tensor(np.copy(module.weight.data.cpu().detach().numpy())).to(self.device)\n if module.bias is not None:\n bias_to_supply = torch.tensor(np.copy(module.bias.data.cpu().detach().numpy())).to(self.device)\n\n interval_conv = PyTorchIntervalConv2D(\n input_shape=shapes,\n in_channels=module.in_channels,\n out_channels=module.out_channels,\n kernel_size=module.kernel_size, # type: ignore\n stride=module.stride, # type: ignore\n supplied_input_weights=weights_to_supply,\n supplied_input_bias=bias_to_supply,\n device=self.device,\n dilation=module.dilation, # type: ignore\n padding=module.padding, # type: ignore\n )\n\n self.ops.append(interval_conv)\n elif isinstance(module, torch.nn.modules.linear.Linear):\n interval_dense = PyTorchIntervalDense(in_features=module.in_features, out_features=module.out_features)\n interval_dense.weight.data = module.weight.data.to(self.device)\n interval_dense.bias.data = module.bias.data.to(self.device)\n self.ops.append(interval_dense)\n\n elif isinstance(module, torch.nn.modules.activation.ReLU):\n self.ops.append(PyTorchIntervalReLU())\n else:\n raise ValueError(\"Supported Operations are Conv2D, Linear, and RelU\")\n\n for op_num, op in enumerate(self.ops):\n # as reshapes are not modules we infer when the reshape from convolutional to dense occurs\n if isinstance(op, PyTorchIntervalDense):\n # if the preceeding op was a convolution:\n if isinstance(self.ops[op_num - 1], PyTorchIntervalConv2D):\n self.reshape_op_num = op_num\n print(\"Inferred reshape on op num\", op_num)\n # if the preceeding op was a relu and the one before the activation was a convolution\n if isinstance(self.ops[op_num - 1], PyTorchIntervalReLU) and isinstance(\n self.ops[op_num - 2], PyTorchIntervalConv2D\n ):\n self.reshape_op_num = op_num\n print(\"Inferred reshape on op num\", op_num)\n\n def forward(self, x: np.ndarray) -> \"torch.Tensor\":\n \"\"\"\n Performs the neural network forward pass, either using abstract operations or concrete ones\n depending on the value of self.forward_mode\n\n :param x: input data, either regular data if running in concrete mode, or in an interval form with shape:\n x[batch_size, 2, feature_1, feature_2, ...] where axis=1 corresponds to the [lower, upper] bounds.\n :return: regular model predictions if in concrete mode, or interval predictions if running in abstract mode\n \"\"\"\n\n if self.forward_mode in [\"concrete\", \"attack\"]:\n return self.concrete_forward(x)\n if self.forward_mode == \"abstract\":\n if x.shape[1] == 2:\n return self.abstract_forward(x)\n raise ValueError(\"axis=1 for the input must be of size 2 representing lower and upper bounds\")\n raise ValueError(\"forward_mode must be set to abstract or concrete\")\n\n def abstract_forward(self, x_interval: np.ndarray) -> \"torch.Tensor\":\n \"\"\"\n Do the forward pass through the NN with interval arithmetic.\n\n :param x_interval: data in interval form with shape:\n x_interval[batch_size, 2, feature_1, feature_2, ...] where axis=1 corresponds to the [lower, upper] bounds.\n :return: interval predictions\n \"\"\"\n\n x = torch.from_numpy(x_interval.astype(\"float32\")).to(self.device)\n\n for op_num, op in enumerate(self.ops):\n # as reshapes are not modules we infer when the reshape from convolutional to dense occurs\n if self.reshape_op_num == op_num:\n x = x.reshape((x.shape[0], 2, -1))\n x = op.forward(x)\n return x\n\n def concrete_forward(self, in_x: np.ndarray | \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Do the forward pass using the concrete operations\n\n :param in_x: regular (concrete) data.\n :return: normal model predictions\n \"\"\"\n if isinstance(in_x, np.ndarray):\n x = torch.from_numpy(in_x.astype(\"float32\")).to(self.device)\n else:\n x = in_x\n for op_num, op in enumerate(self.ops):\n # as reshapes are not modules we infer when the reshape from convolutional to dense occurs\n if self.reshape_op_num == op_num:\n x = x.reshape((x.shape[0], -1))\n if isinstance(op, PyTorchIntervalConv2D) and self.forward_mode == \"attack\":\n x = op.conv_forward(x)\n else:\n x = op.concrete_forward(x) # type: ignore\n return x\n\n def set_forward_mode(self, mode: str) -> None:\n \"\"\"\n Helper function to set the forward mode of the model\n\n :param mode: either concrete, abstract, or attack to signify how to run the forward pass\n \"\"\"\n assert mode in {\"concrete\", \"abstract\", \"attack\"}\n self.forward_mode = mode\n\n def re_convert(self) -> None:\n \"\"\"\n After an update on the convolutional weights, re-convert weights into the equivalent dense layer.\n \"\"\"\n for op in self.ops:\n if isinstance(op, PyTorchIntervalConv2D):\n op.re_convert(self.device)\n\n\nclass PyTorchIBPClassifier(PyTorchIntervalBounds, PyTorchClassifier):\n \"\"\"\n Implementation of Interval based certification for neural network robustness.\n We use the interval (also called box) representation of a datapoint as it travels through the network\n to then verify if it can have its class changed given a certain perturbation.\n\n | Paper link: https://ieeexplore.ieee.org/document/8418593\n\n This classifier has 3 modes which can be set via: classifier.model.set_forward_mode('mode')\n\n 'mode' can be one of:\n + 'abstract': When we wish to certify datapoints and have abstract predictions\n + 'concrete': When normal predictions need to be made\n + 'attack': When we are interfacing with an ART attack (for example PGD).\n \"\"\"\n\n estimator_params = PyTorchClassifier.estimator_params\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n concrete_to_interval: Callable | None = None,\n ):\n \"\"\"\n Create a certifier based on the interval (also called box) domain.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param concrete_to_interval: Optional argument. Function which takes in a concrete data point and the bound\n and converts the datapoint to the interval domain via:\n\n interval_sample = concrete_to_interval(sample, bound, limits)\n\n If left as None, by default we apply the bound to every feature equally and\n adjust the intervals such that it remains in the 0 - 1 range.\n \"\"\"\n\n warnings.warn(\n \"\\nThis estimator does not support networks which have dense layers before convolutional. \"\n \"We currently infer a reshape when a neural network goes from convolutional layers to \"\n \"dense layers. If your use case does not fall into this pattern then consider \"\n \"directly building a certifier network with the \"\n \"custom layers found in art.estimators.certification.interval.interval.py\\n\"\n )\n converted_model = ConvertedModel(model, channels_first, input_shape)\n\n if TYPE_CHECKING:\n converted_optimizer: torch.optim.Adam | torch.optim.SGD | None\n if optimizer is not None:\n opt_state_dict = optimizer.state_dict()\n if isinstance(optimizer, torch.optim.Adam):\n logging.info(\"Converting Adam Optimiser\")\n converted_optimizer = torch.optim.Adam(converted_model.parameters(), lr=1e-4)\n elif isinstance(optimizer, torch.optim.SGD):\n logging.info(\"Converting SGD Optimiser\")\n converted_optimizer = torch.optim.SGD(converted_model.parameters(), lr=1e-4)\n else:\n raise ValueError(\"Optimiser not supported for conversion\")\n\n converted_optimizer.load_state_dict(opt_state_dict)\n else:\n converted_optimizer = None\n\n self.provided_concrete_to_interval = concrete_to_interval\n\n super().__init__(\n model=converted_model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=converted_optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n\n def predict_intervals(\n self,\n x: np.ndarray,\n is_interval: bool = False,\n bounds: float | list[float] | np.ndarray | None = None,\n limits: list[float] | np.ndarray | None = None,\n batch_size: int = 128,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Produce interval predictions over the supplied data\n\n :param x: The datapoint, either:\n\n 1. In the interval format of x[batch_size, 2, feature_1, feature_2, ...]\n where axis=1 corresponds to the [lower, upper] bounds.\n\n 2. Or in regular concrete form, in which case the bounds/limits need to be supplied.\n :param is_interval: if the datapoint is already in the correct interval format.\n :param bounds: The perturbation range.\n :param limits: The clipping to apply to the interval data.\n :param batch_size: batch size to use when looping through the data\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n :return: interval predictions over the supplied dataset\n \"\"\"\n\n if len(x) < batch_size:\n batch_size = len(x)\n\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n self._model.train(mode=training_mode)\n\n if is_interval:\n x_interval = x_preprocessed\n elif bounds is None:\n raise ValueError(\"If x is not provided as an interval please provide bounds (and optionally limits)\")\n else:\n if self.provided_concrete_to_interval is None:\n x_interval = self.concrete_to_interval(x=x_preprocessed, bounds=bounds, limits=limits)\n else:\n x_interval = self.provided_concrete_to_interval(x_preprocessed, bounds, limits)\n\n num_batches = int(len(x_interval) / batch_size)\n\n interval_predictions = []\n\n for bnum in range(num_batches):\n x_batch_interval = x_interval[batch_size * bnum : batch_size * (bnum + 1)]\n abstract_preds = self.model.forward(x_batch_interval)\n interval_predictions.append(abstract_preds)\n\n if len(x_interval) % batch_size > 0:\n x_batch_interval = x_interval[batch_size * num_batches :]\n abstract_preds = self.model.forward(x_batch_interval)\n interval_predictions.append(abstract_preds)\n\n return torch.concat(interval_predictions, dim=0).cpu().detach().numpy()\n\n def apply_preprocessing(self, x: np.ndarray, y: np.ndarray, fit: bool) -> tuple[Any, Any]:\n \"\"\"\n Access function to get preprocessing\n\n :param x: unprocessed input data.\n :param y: unprocessed labels.\n :param fit: `True` if the function is call before fit/training and `False` if the function is called before a\n predict operation.\n :return: Tuple with the processed input data and labels.\n \"\"\"\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=fit)\n return x_preprocessed, y_preprocessed\n\n @staticmethod\n def get_accuracy(preds: np.ndarray | \"torch.Tensor\", labels: np.ndarray | \"torch.Tensor\") -> np.ndarray:\n \"\"\"\n Helper function to print out the accuracy during training\n\n :param preds: (concrete) model predictions\n :param labels: ground truth labels (not one hot)\n :return: prediction accuracy\n \"\"\"\n if isinstance(preds, torch.Tensor):\n preds = preds.detach().cpu().numpy()\n\n if isinstance(labels, torch.Tensor):\n labels = labels.detach().cpu().numpy()\n\n return np.sum(np.argmax(preds, axis=1) == labels) / len(labels)\n\n def concrete_loss(self, output: \"torch.Tensor\", target: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Access function to get the classifier loss\n\n :param output: model predictions\n :param target: ground truth labels\n :return: loss value\n \"\"\"\n return self._loss(output, target)\n\n @staticmethod\n def interval_loss_cce(prediction: \"torch.Tensor\", target: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Computes the categorical cross entropy loss with the correct class having the lower bound prediction,\n and the other classes having their upper bound predictions.\n\n :param prediction: model predictions.\n :param target: target classes. NB not one hot.\n :return: scalar loss value\n \"\"\"\n upper_preds = prediction[:, 1, :]\n criterion = torch.nn.CrossEntropyLoss()\n for i, j in enumerate(target):\n # for the prediction corresponding to the target class, take the lower bound predictions\n upper_preds[i, j] = prediction[i, 0, j]\n return criterion(upper_preds, target)\n\n def re_convert(self) -> None:\n \"\"\"\n Convert all the convolutional layers into their dense representations\n \"\"\"\n self.model.re_convert() # type: ignore\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/object_seeker/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nObjectSeeker estimators.\n\"\"\"\n\nfrom art.estimators.certification.object_seeker.object_seeker import ObjectSeekerMixin\nfrom art.estimators.certification.object_seeker.pytorch import PyTorchObjectSeeker\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/object_seeker/object_seeker.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (c) 2022 Chong Xiang\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the ObjectSeeker certifiably robust defense.\n\n| Paper link: https://arxiv.org/abs/2202.01811\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport abc\nimport logging\n\nimport numpy as np\nfrom sklearn.cluster import DBSCAN\nfrom tqdm.auto import tqdm\n\nfrom art.utils import intersection_over_area\n\nlogger = logging.getLogger(__name__)\n\n\nclass ObjectSeekerMixin(abc.ABC):\n \"\"\"\n Implementation of the ObjectSeeker certifiable robust defense applied to object detection models.\n The original implementation is https://github.com/inspire-group/ObjectSeeker\n\n | Paper link: https://arxiv.org/abs/2202.01811\n \"\"\"\n\n def __init__(\n self,\n *args,\n num_lines: int = 3,\n confidence_threshold: float = 0.3,\n iou_threshold: float = 0.5,\n prune_threshold: float = 0.5,\n epsilon: float = 0.1,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Create an ObjectSeeker wrapper.\n\n :param num_lines: The number of divisions both vertically and horizontally to make masked predictions.\n :param confidence_threshold: The confidence threshold to discard bounding boxes.\n :param iou_threshold: The IoU threshold to discard overlapping bounding boxes.\n :param prune_threshold: The IoA threshold for pruning and duplicated bounding boxes.\n :param epsilon: The maximum distance between bounding boxes when merging using DBSCAN.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(*args, **kwargs) # type: ignore\n self.num_lines = num_lines\n self.confidence_threshold = confidence_threshold\n self.iou_threshold = iou_threshold\n self.prune_threshold = prune_threshold\n self.epsilon = epsilon\n self.verbose = verbose\n\n @abc.abstractmethod\n def _image_dimensions(self) -> tuple[int, int]:\n \"\"\"\n Get the height and width of a sample input image.\n\n :return: Tuple containing the height and width of a sample input image.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def _masked_predictions(\n self, x_i: np.ndarray, batch_size: int = 128, **kwargs\n ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:\n \"\"\"\n Create masked copies of the image for each of lines following the ObjectSeeker algorithm. Then creates\n predictions on the base unmasked image and each of the masked image.\n\n :param x_i: A single image of shape CHW or HWC.\n :param batch_size: Batch size.\n :return: Predictions for the base unmasked image and merged predictions for the masked image.\n \"\"\"\n raise NotImplementedError\n\n def _prune_boxes(\n self, masked_preds: dict[str, np.ndarray], base_preds: dict[str, np.ndarray]\n ) -> dict[str, np.ndarray]:\n \"\"\"\n Remove bounding boxes from the masked predictions of a single image based on the IoA score with the boxes\n on the base unmasked predictions.\n\n :param masked_preds: The merged masked predictions of a single image.\n :param base_preds: The base unmasked predictions of a single image.\n :return: The filtered masked predictions with extraneous boxes removed.\n \"\"\"\n masked_boxes = masked_preds[\"boxes\"]\n masked_labels = masked_preds[\"labels\"]\n masked_scores = masked_preds[\"scores\"]\n\n base_boxes = base_preds[\"boxes\"]\n base_labels = base_preds[\"labels\"]\n\n keep_indices = []\n for idx, (masked_box, masked_label) in enumerate(zip(masked_boxes, masked_labels)):\n keep = True\n for base_box, base_label in zip(base_boxes, base_labels):\n if masked_label == base_label:\n ioa = intersection_over_area(masked_box, base_box)\n if ioa >= self.prune_threshold:\n keep = False\n break\n\n if keep:\n keep_indices.append(idx)\n\n pruned_preds = {\n \"boxes\": masked_boxes[keep_indices],\n \"labels\": masked_labels[keep_indices],\n \"scores\": masked_scores[keep_indices],\n }\n return pruned_preds\n\n def _unionize_clusters(self, masked_preds: dict[str, np.ndarray]) -> dict[str, np.ndarray]:\n \"\"\"\n Cluster the bounding boxes for the pruned masked predictions.\n\n :param masked_preds: The merged masked predictions of a single image already pruned.\n :return: The clustered masked predictions with overlapping boxes merged.\n \"\"\"\n boxes = masked_preds[\"boxes\"]\n labels = masked_preds[\"labels\"]\n scores = masked_preds[\"scores\"]\n\n # Skip clustering if not enough bounding boxes\n if len(boxes) <= 1:\n return masked_preds\n\n unionized_boxes = []\n unionized_labels = []\n unionized_scores = []\n\n unique_labels = np.unique(labels)\n for label in unique_labels:\n # Select bounding boxes of same class\n mask = labels == label\n selected_boxes = boxes[mask]\n selected_scores = scores[mask]\n\n # Calculate pairwise distances between bounding boxes\n areas = (selected_boxes[:, 2] - selected_boxes[:, 0]) * (selected_boxes[:, 3] - selected_boxes[:, 1])\n top_left = np.maximum(selected_boxes[:, None, :2], selected_boxes[:, :2])\n bottom_right = np.minimum(selected_boxes[:, None, 2:], selected_boxes[:, 2:])\n pairwise_intersection = np.prod(np.clip(bottom_right - top_left, 0, None), axis=2)\n pairwise_ioa = pairwise_intersection / (areas[:, None])\n distances = 1 - np.maximum(pairwise_ioa, pairwise_ioa.T)\n\n # Cluster bounding boxes\n dbscan = DBSCAN(eps=self.epsilon, min_samples=1, metric=\"precomputed\")\n clusters = dbscan.fit_predict(distances)\n num_clusters = np.max(clusters) + 1\n\n for cluster in range(num_clusters):\n # Merge all boxes in the cluster\n clustered_boxes = selected_boxes[clusters == cluster]\n\n clustered_box = [\n np.min(clustered_boxes[:, 0]),\n np.min(clustered_boxes[:, 1]),\n np.max(clustered_boxes[:, 2]),\n np.max(clustered_boxes[:, 3]),\n ]\n clustered_score = np.max(selected_scores)\n\n unionized_boxes.append(clustered_box)\n unionized_labels.append(label)\n unionized_scores.append(clustered_score)\n\n unionized_predictions = {\n \"boxes\": np.asarray(unionized_boxes),\n \"labels\": np.asarray(unionized_labels),\n \"scores\": np.asarray(unionized_scores),\n }\n return unionized_predictions\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape NCHW or NHWC.\n :param batch_size: Batch size.\n :return: Predictions of format `list[dict[str, np.ndarray]]`, one for each input image. The fields of the dict\n are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image\n - scores [N]: the scores or each prediction.\n \"\"\"\n predictions = []\n\n for x_i in tqdm(x, desc=\"ObjectSeeker\", disable=not self.verbose):\n base_preds, masked_preds = self._masked_predictions(x_i, batch_size=batch_size, **kwargs)\n pruned_preds = self._prune_boxes(masked_preds, base_preds)\n unionized_preds = self._unionize_clusters(pruned_preds)\n\n preds = {\n \"boxes\": np.concatenate([base_preds[\"boxes\"], unionized_preds[\"boxes\"]]),\n \"labels\": np.concatenate([base_preds[\"labels\"], unionized_preds[\"labels\"]]),\n \"scores\": np.concatenate([base_preds[\"scores\"], unionized_preds[\"scores\"]]),\n }\n\n predictions.append(preds)\n\n return predictions\n\n def certify(\n self,\n x: np.ndarray,\n patch_size: float = 0.01,\n offset: float = 0.1,\n batch_size: int = 128,\n ) -> list[np.ndarray]:\n \"\"\"\n Checks if there is certifiable IoA robustness for each predicted bounding box.\n\n :param x: Sample input with shape as expected by the model.\n :param patch_size: The size of the patch to check against.\n :param offset: The offset to distinguish between the far and near patches.\n :return: A list containing an array of bools for each bounding box per image indicating if the bounding\n box is certified against the given patch.\n \"\"\"\n height, width = self._image_dimensions()\n\n patch_size = np.sqrt(height * width * patch_size)\n height_offset = offset * height\n width_offset = offset * width\n\n # Get predictions\n predictions = self.predict(x, batch_size=batch_size)\n\n certifications: list[np.ndarray] = []\n\n for pred in tqdm(predictions, desc=\"ObjectSeeker\", disable=not self.verbose):\n boxes = pred[\"boxes\"]\n\n # Far patch\n far_patch_map = np.ones((len(boxes), height, width), dtype=bool)\n for i, box in enumerate(boxes):\n x_1 = int(max(0, box[1] - patch_size - height_offset))\n x_2 = int(min(box[3] + height_offset + 1, height))\n y_1 = int(max(0, box[0] - patch_size - width_offset))\n y_2 = int(min(box[2] + width_offset + 1, width))\n far_patch_map[i, x_1:x_2, y_1:y_2] = False\n far_vulnerable = np.any(far_patch_map, axis=(-2, -1))\n\n # Close patch\n close_patch_map = np.ones((len(boxes), height, width), dtype=bool)\n for i, box in enumerate(boxes):\n x_1 = int(max(0, box[1] - patch_size))\n x_2 = int(min(box[3] + 1, height))\n y_1 = int(max(0, box[0] - patch_size))\n y_2 = int(min(box[2] + 1, width))\n close_patch_map[i, x_1:x_2, y_1:y_2] = False\n close_vulnerable = np.any(close_patch_map, axis=(-2, -1))\n\n # Over patch\n close_patch_map = np.ones((len(boxes), height, width), dtype=bool)\n for i, box in enumerate(boxes):\n x_1 = int(max(0, box[1] - patch_size))\n x_2 = int(min(box[3] + 1, height))\n y_1 = int(max(0, box[0] - patch_size))\n y_2 = int(min(box[2] + 1, width))\n close_patch_map[i, x_1:x_2, y_1:y_2] = True\n over_vulnerable = np.any(close_patch_map, axis=(-2, -1))\n\n cert = np.logical_and.reduce((far_vulnerable, close_vulnerable, over_vulnerable))\n certifications.append(cert)\n\n return certifications\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/object_seeker/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the ObjectSeeker certifiably robust defense.\n\n| Paper link: https://arxiv.org/abs/2202.01811\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport sys\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.certification.object_seeker.object_seeker import ObjectSeekerMixin\nfrom art.estimators.object_detection import (\n PyTorchObjectDetector,\n PyTorchFasterRCNN,\n PyTorchYolo,\n PyTorchDetectionTransformer,\n)\nfrom art.utils import non_maximum_suppression\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchObjectSeeker(ObjectSeekerMixin, PyTorchObjectDetector):\n \"\"\"\n Implementation of the ObjectSeeker certifiable robust defense applied to object detection models.\n The original implementation is https://github.com/inspire-group/ObjectSeeker\n\n | Paper link: https://arxiv.org/abs/2202.01811\n \"\"\"\n\n estimator_params = PyTorchObjectDetector.estimator_params + [\n \"attack_losses\",\n \"num_lines\",\n \"confidence_threshold\",\n \"iou_threshold\",\n \"prune_threshold\",\n \"epsilon\",\n ]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n input_shape: tuple[int, ...] = (3, 416, 416),\n optimizer: \"torch.optim.Optimizer\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool = True,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n attack_losses: tuple[str, ...] = (\n \"loss_classifier\",\n \"loss_box_reg\",\n \"loss_objectness\",\n \"loss_rpn_box_reg\",\n ),\n detector_type: Literal[\"Faster-RCNN\", \"YOLO\", \"DETR\"] = \"YOLO\",\n num_lines: int = 3,\n confidence_threshold: float = 0.3,\n iou_threshold: float = 0.5,\n prune_threshold: float = 0.5,\n epsilon: float = 0.1,\n device_type: str = \"gpu\",\n verbose: bool = False,\n ):\n \"\"\"\n Create an ObjectSeeker classifier.\n\n :param model: Object detection model. The output of the model is `list[dict[str, torch.Tensor]]`,\n one for each input image. The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores of each prediction.\n :param input_shape: The shape of one input sample.\n :param optimizer: The optimizer for training the classifier.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param attack_losses: Tuple of any combination of strings of loss components: 'loss_classifier', 'loss_box_reg',\n 'loss_objectness', and 'loss_rpn_box_reg'.\n :param detector_type: The type of object detector being used: 'Faster-RCNN' | 'YOLO' | 'DETR'\n :param num_lines: The number of divisions both vertically and horizontally to make masked predictions.\n :param confidence_threshold: The confidence threshold to discard bounding boxes.\n :param iou_threshold: The IoU threshold to discard overlapping bounding boxes.\n :param prune_threshold: The IoA threshold for pruning and duplicated bounding boxes.\n :param epsilon: The maximum distance between bounding boxes when merging using DBSCAN.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n num_lines=num_lines,\n confidence_threshold=confidence_threshold,\n iou_threshold=iou_threshold,\n prune_threshold=prune_threshold,\n epsilon=epsilon,\n verbose=verbose,\n )\n\n self._input_shape = input_shape\n self._channels_first = channels_first\n self._optimizer = optimizer\n self._attack_losses = attack_losses\n self.detector_type = detector_type\n\n detector_ctor: type\n if detector_type == \"Faster-RCNN\":\n detector_ctor = PyTorchFasterRCNN\n elif detector_type == \"YOLO\":\n detector_ctor = PyTorchYolo\n elif detector_type == \"DETR\":\n detector_ctor = PyTorchDetectionTransformer\n else:\n detector_ctor = PyTorchObjectDetector\n\n self.detector = detector_ctor(\n model=model,\n input_shape=input_shape,\n optimizer=optimizer,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n attack_losses=attack_losses,\n device_type=device_type,\n )\n\n def _image_dimensions(self) -> tuple[int, int]:\n \"\"\"\n Return the height and width of a sample input image.\n\n :return: Tuple containing the height and width of a sample input image.\n \"\"\"\n if self.channels_first:\n _, height, width = self.input_shape\n else:\n height, width, _ = self.input_shape\n\n return height, width\n\n def _masked_predictions(\n self, x_i: np.ndarray, batch_size: int = 128, **kwargs\n ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:\n \"\"\"\n Create masked copies of the image for each of lines following the ObjectSeeker algorithm. Then creates\n predictions on the base unmasked image and each of the masked image.\n\n :param x_i: A single image of shape CHW or HWC.\n :param batch_size: Batch size.\n :return: Predictions for the base unmasked image and merged predictions for the masked image.\n \"\"\"\n x_mask = np.repeat(x_i[np.newaxis], self.num_lines * 4 + 1, axis=0)\n\n if self.channels_first:\n height = self.input_shape[1]\n width = self.input_shape[2]\n else:\n height = self.input_shape[0]\n width = self.input_shape[1]\n x_mask = np.transpose(x_mask, (0, 3, 1, 2))\n\n idx = 1\n\n # Left masks\n for k in range(1, self.num_lines + 1):\n boundary = int(width / (self.num_lines + 1) * k)\n x_mask[idx, :, :, :boundary] = 0\n idx += 1\n\n # Right masks\n for k in range(1, self.num_lines + 1):\n boundary = width - int(width / (self.num_lines + 1) * k)\n x_mask[idx, :, :, boundary:] = 0\n idx += 1\n\n # Top masks\n for k in range(1, self.num_lines + 1):\n boundary = int(height / (self.num_lines + 1) * k)\n x_mask[idx, :, :boundary, :] = 0\n idx += 1\n\n # Bottom masks\n for k in range(1, self.num_lines + 1):\n boundary = height - int(height / (self.num_lines + 1) * k)\n x_mask[idx, :, boundary:, :] = 0\n idx += 1\n\n if not self.channels_first:\n x_mask = np.transpose(x_mask, (0, 2, 3, 1))\n\n predictions = self.detector.predict(x=x_mask, batch_size=batch_size, **kwargs)\n filtered_predictions = [\n non_maximum_suppression(\n pred, iou_threshold=self.iou_threshold, confidence_threshold=self.confidence_threshold\n )\n for pred in predictions\n ]\n\n # Extract base predictions\n base_predictions = filtered_predictions[0]\n\n # Extract and merge masked predictions\n boxes = np.concatenate([pred[\"boxes\"] for pred in filtered_predictions[1:]])\n labels = np.concatenate([pred[\"labels\"] for pred in filtered_predictions[1:]])\n scores = np.concatenate([pred[\"scores\"] for pred in filtered_predictions[1:]])\n merged_predictions = {\n \"boxes\": boxes,\n \"labels\": labels,\n \"scores\": scores,\n }\n masked_predictions = non_maximum_suppression(\n merged_predictions, iou_threshold=self.iou_threshold, confidence_threshold=self.confidence_threshold\n )\n\n return base_predictions, masked_predictions\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape NCHW or NHWC.\n :param batch_size: Batch size.\n :return: Predictions of format `list[dict[str, np.ndarray]]`, one for each input image. The fields of the dict\n are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image\n - scores [N]: the scores or each prediction.\n \"\"\"\n return ObjectSeekerMixin.predict(self, x=x, batch_size=batch_size, **kwargs)\n\n def fit(\n self,\n x: np.ndarray,\n y: list[dict[str, np.ndarray | \"torch.Tensor\"]],\n batch_size: int = 128,\n nb_epochs: int = 10,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, np.ndarray | torch.Tensor]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n self.detector.fit(\n x=x,\n y=y,\n batch_size=batch_size,\n nb_epochs=nb_epochs,\n drop_last=drop_last,\n scheduler=scheduler,\n **kwargs,\n )\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n return self.detector.get_activations(\n x=x,\n layer=layer,\n batch_size=batch_size,\n framework=framework,\n )\n\n def loss_gradient(\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]], **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, np.ndarray | torch.Tensor]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Loss gradients of the same shape as `x`.\n \"\"\"\n return self.detector.loss_gradient(\n x=x,\n y=y, # type: ignore\n **kwargs,\n )\n\n def compute_losses(\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]]\n ) -> dict[str, np.ndarray]:\n \"\"\"\n Compute all loss components.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, np.ndarray | torch.Tensor]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Dictionary of loss components.\n \"\"\"\n return self.detector.compute_losses(\n x=x,\n y=y,\n )\n\n def compute_loss( # type: ignore\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]], **kwargs\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Loss.\n \"\"\"\n return self.detector.compute_loss(\n x=x,\n y=y,\n **kwargs,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nRandomized smoothing estimators.\n\"\"\"\n\nfrom art.estimators.certification.randomized_smoothing.randomized_smoothing import RandomizedSmoothingMixin\n\nfrom art.estimators.certification.randomized_smoothing.numpy import NumpyRandomizedSmoothing\nfrom art.estimators.certification.randomized_smoothing.pytorch import PyTorchRandomizedSmoothing\nfrom art.estimators.certification.randomized_smoothing.tensorflow import TensorFlowV2RandomizedSmoothing\nfrom art.estimators.certification.randomized_smoothing.smooth_mix.pytorch import PyTorchSmoothMix\nfrom art.estimators.certification.randomized_smoothing.macer.pytorch import PyTorchMACER\nfrom art.estimators.certification.randomized_smoothing.macer.tensorflow import TensorFlowV2MACER\nfrom art.estimators.certification.randomized_smoothing.smooth_adv.pytorch import PyTorchSmoothAdv\nfrom art.estimators.certification.randomized_smoothing.smooth_adv.tensorflow import TensorFlowV2SmoothAdv\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Randomized Smoothing applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/1902.02918\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport warnings\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin, NeuralNetworkMixin\nfrom art.estimators.certification.randomized_smoothing.randomized_smoothing import RandomizedSmoothingMixin\nfrom art.estimators.classification import ClassifierMixin, ClassGradientsMixin\nfrom art.defences.preprocessor.gaussian_augmentation import GaussianAugmentation\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_NEURALNETWORK_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass NumpyRandomizedSmoothing(\n RandomizedSmoothingMixin,\n ClassGradientsMixin,\n ClassifierMixin,\n NeuralNetworkMixin,\n LossGradientsMixin,\n BaseEstimator,\n):\n \"\"\"\n Implementation of Randomized Smoothing applied to classifier predictions and gradients, as introduced\n in Cohen et al. (2019).\n\n | Paper link: https://arxiv.org/abs/1902.02918\n \"\"\"\n\n estimator_params = (\n BaseEstimator.estimator_params\n + NeuralNetworkMixin.estimator_params\n + ClassifierMixin.estimator_params\n + [\"classifier\", \"sample_size\", \"scale\", \"alpha\"]\n )\n\n def __init__(\n self, classifier: \"CLASSIFIER_NEURALNETWORK_TYPE\", sample_size: int, scale: float = 0.1, alpha: float = 0.001\n ):\n \"\"\"\n Create a randomized smoothing wrapper.\n :param classifier: The Classifier we want to wrap the functionality for the purpose of smoothing.\n :param sample_size: Number of samples for smoothing\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing\n \"\"\"\n if classifier.preprocessing_defences is not None:\n warnings.warn(\n \"\\n With the current backend Gaussian noise will be added by Randomized Smoothing \"\n \"BEFORE the application of preprocessing defences. Please ensure this conforms to your use case.\\n\"\n )\n\n super().__init__(\n model=classifier.model,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n self._input_shape = classifier.input_shape\n self.nb_classes = classifier.nb_classes\n\n self.classifier = classifier\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n return self._input_shape\n\n def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n return self.classifier.predict(x=x, batch_size=batch_size, training_mode=training_mode, **kwargs)\n\n def _fit_classifier(self, x: np.ndarray, y: np.ndarray, batch_size: int, nb_epochs: int, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param batch_size: Batch size.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n\n g_a = GaussianAugmentation(sigma=self.scale, augmentation=False)\n for _ in range(nb_epochs):\n x_rs, _ = g_a(x)\n x_rs = x_rs.astype(ART_NUMPY_DTYPE)\n self.classifier.fit(x_rs, y, batch_size=batch_size, nb_epochs=1, **kwargs)\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the given classifier's loss function w.r.t. `x` of the original classifier.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Correct labels, one-hot encoded.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n return self.classifier.loss_gradient(x=x, y=y, training_mode=training_mode, **kwargs) # type: ignore\n\n def class_gradient(\n self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, training_mode: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives of the given classifier w.r.t. `x` of original classifier.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n return self.classifier.class_gradient(x=x, label=label, training_mode=training_mode, **kwargs) # type: ignore\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n return self.classifier.compute_loss(x=x, y=y, **kwargs) # type: ignore\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n return self.classifier.get_activations( # type: ignore\n x=x, layer=layer, batch_size=batch_size, framework=framework\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Randomized Smoothing applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/1902.02918\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport warnings\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.certification.randomized_smoothing.randomized_smoothing import RandomizedSmoothingMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchRandomizedSmoothing(RandomizedSmoothingMixin, PyTorchClassifier):\n \"\"\"\n Implementation of Randomized Smoothing applied to classifier predictions and gradients, as introduced\n in Cohen et al. (2019).\n\n | Paper link: https://arxiv.org/abs/1902.02918\n \"\"\"\n\n estimator_params = PyTorchClassifier.estimator_params + [\"sample_size\", \"scale\", \"alpha\"]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n ):\n \"\"\"\n Create a randomized smoothing classifier.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n \"\"\"\n if preprocessing_defences is not None:\n warnings.warn(\n \"\\n With the current backend (Pytorch) Gaussian noise will be added by Randomized Smoothing \"\n \"AFTER the application of preprocessing defences. Please ensure this conforms to your use case.\\n\"\n )\n\n super().__init__(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n\n def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:\n x = x.astype(ART_NUMPY_DTYPE)\n return PyTorchClassifier.predict(self, x=x, batch_size=batch_size, training_mode=training_mode, **kwargs)\n\n def _fit_classifier(self, x: np.ndarray, y: np.ndarray, batch_size: int, nb_epochs: int, **kwargs) -> None:\n x = x.astype(ART_NUMPY_DTYPE)\n return PyTorchClassifier.fit(self, x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n y_tensor = torch.from_numpy(y_preprocessed)\n dataset = TensorDataset(x_tensor, y_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)\n\n # Start training\n for _ in trange(nb_epochs, disable=not verbose):\n for x_batch, y_batch in dataloader:\n # Move inputs to device\n x_batch = x_batch.to(self._device)\n y_batch = y_batch.to(self._device)\n\n # Add random noise for randomized smoothing\n x_batch += torch.randn_like(x_batch) * self.scale\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Perform prediction\n try:\n model_outputs = self._model(x_batch)\n except ValueError as err:\n if \"Expected more than 1 value per channel when training\" in str(err):\n logger.exception(\n \"Try dropping the last incomplete batch by setting drop_last=True in \"\n \"method PyTorchClassifier.fit.\"\n )\n raise err\n\n # Form the loss function\n loss = self._loss(model_outputs[-1], y_batch)\n\n # Do training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self._optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n def predict( # type: ignore\n self, x: np.ndarray, batch_size: int = 128, verbose: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Perform prediction of the given classifier for a batch of inputs, taking an expectation over transformations.\n\n :param x: Input samples.\n :param batch_size: Batch size.\n :param verbose: Display training progress bar.\n :param is_abstain: True if function will abstain from prediction and return 0s. Default: True\n :type is_abstain: `boolean`\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n return RandomizedSmoothingMixin.predict(\n self, x, batch_size=batch_size, verbose=verbose, training_mode=False, **kwargs\n )\n\n def loss_gradient( # type: ignore\n self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param sampling: True if loss gradients should be determined with Monte Carlo sampling.\n :type sampling: `bool`\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import torch\n\n sampling = kwargs.get(\"sampling\")\n\n if sampling:\n self._model.train(mode=training_mode)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n # Check label shape\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n # Convert the inputs to Tensors\n inputs_t = torch.from_numpy(x_preprocessed).to(self._device)\n inputs_t.requires_grad = True\n\n # Convert the labels to Tensors\n labels_t = torch.from_numpy(y_preprocessed).to(self._device)\n inputs_repeat_t = inputs_t.repeat_interleave(self.sample_size, 0)\n\n noise = torch.randn_like(inputs_repeat_t, device=self._device) * self.scale\n inputs_noise_t = inputs_repeat_t + noise\n if self.clip_values is not None:\n inputs_noise_t.clamp(\n torch.tensor(self.clip_values[0]),\n torch.tensor(self.clip_values[1]),\n )\n\n model_outputs = self._model(inputs_noise_t)[-1]\n softmax = torch.nn.functional.softmax(model_outputs, dim=1)\n average_softmax = (\n softmax.reshape(-1, self.sample_size, model_outputs.shape[-1]).mean(1, keepdim=True).squeeze(1)\n )\n log_softmax = torch.log(average_softmax.clamp(min=1e-20))\n loss = torch.nn.functional.nll_loss(log_softmax, labels_t)\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n loss.backward()\n gradients = inputs_t.grad.cpu().numpy().copy() # type: ignore\n gradients = self._apply_preprocessing_gradient(x, gradients)\n assert gradients.shape == x.shape\n\n else:\n gradients = PyTorchClassifier.loss_gradient(self, x=x, y=y, training_mode=training_mode, **kwargs)\n\n return gradients\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives of the given classifier w.r.t. `x` of original classifier.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/randomized_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Randomized Smoothing applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/1902.02918\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom abc import ABC\nimport logging\n\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass RandomizedSmoothingMixin(ABC):\n \"\"\"\n Implementation of Randomized Smoothing applied to classifier predictions and gradients, as introduced\n in Cohen et al. (2019).\n\n | Paper link: https://arxiv.org/abs/1902.02918\n \"\"\"\n\n def __init__(\n self,\n sample_size: int,\n *args,\n scale: float = 0.1,\n alpha: float = 0.001,\n **kwargs,\n ) -> None:\n \"\"\"\n Create a randomized smoothing wrapper.\n\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n \"\"\"\n super().__init__(*args, **kwargs) # type: ignore\n self.sample_size = sample_size\n self.scale = scale\n self.alpha = alpha\n\n def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, batch_size: int = 128, verbose: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction of the given classifier for a batch of inputs, taking an expectation over transformations.\n\n :param x: Input samples.\n :param batch_size: Batch size.\n :param verbose: Display training progress bar.\n :param is_abstain: True if function will abstain from prediction and return 0s. Default: True\n :type is_abstain: `boolean`\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n from scipy.stats import binomtest\n\n is_abstain = kwargs.get(\"is_abstain\")\n if is_abstain is not None and not isinstance(is_abstain, bool): # pragma: no cover\n raise ValueError(\"The argument is_abstain needs to be of type bool.\")\n if is_abstain is None:\n is_abstain = True\n\n logger.info(\"Applying randomized smoothing.\")\n n_abstained = 0\n prediction = []\n for x_i in tqdm(x, desc=\"Randomized smoothing\", disable=not verbose):\n # get class counts\n counts_pred = self._prediction_counts(x_i, batch_size=batch_size)\n top = counts_pred.argsort()[::-1]\n # conversion to int\n count1 = int(np.max(counts_pred))\n count2 = int(counts_pred[top[1]])\n\n # predict or abstain\n smooth_prediction = np.zeros(counts_pred.shape)\n # get p value from BinomTestResult object\n p_value = binomtest(count1, count1 + count2, p=0.5).pvalue\n if (not is_abstain) or (p_value <= self.alpha):\n smooth_prediction[np.argmax(counts_pred)] = 1\n elif is_abstain:\n n_abstained += 1\n\n prediction.append(smooth_prediction)\n if n_abstained > 0:\n logger.info(\"%s prediction(s) abstained.\", n_abstained)\n return np.array(prediction)\n\n def _fit_classifier(self, x: np.ndarray, y: np.ndarray, batch_size: int, nb_epochs: int, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param batch_size: Batch size.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n raise NotImplementedError\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param batch_size: Batch size.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n self._fit_classifier(x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def certify(self, x: np.ndarray, n: int, batch_size: int = 32) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Computes certifiable radius around input `x` and returns radius `r` and prediction.\n\n :param x: Sample input with shape as expected by the model.\n :param n: Number of samples for estimate certifiable radius.\n :param batch_size: Batch size.\n :return: Tuple of length 2 of the selected class and certified radius.\n \"\"\"\n prediction = []\n radius = []\n\n for x_i in x:\n\n # get sample prediction for classification\n counts_pred = self._prediction_counts(x_i, n=self.sample_size, batch_size=batch_size)\n class_select = int(np.argmax(counts_pred))\n\n # get sample prediction for certification\n counts_est = self._prediction_counts(x_i, n=n, batch_size=batch_size)\n count_class = counts_est[class_select]\n\n prob_class = self._lower_confidence_bound(count_class, n)\n\n if prob_class < 0.5:\n prediction.append(-1)\n radius.append(0.0)\n else:\n prediction.append(class_select)\n radius.append(self.scale * norm.ppf(prob_class))\n\n return np.array(prediction), np.array(radius)\n\n def _noisy_samples(self, x: np.ndarray, n: int | None = None) -> np.ndarray:\n \"\"\"\n Adds Gaussian noise to `x` to generate samples. Optionally augments `y` similarly.\n\n :param x: Sample input with shape as expected by the model.\n :param n: Number of noisy samples to create.\n :return: Array of samples of the same shape as `x`.\n \"\"\"\n # set default value to sample_size\n if n is None:\n n = self.sample_size\n\n # augment x\n x = np.expand_dims(x, axis=0)\n x = np.repeat(x, n, axis=0)\n x = x + np.random.normal(scale=self.scale, size=x.shape).astype(ART_NUMPY_DTYPE)\n\n return x\n\n def _prediction_counts(self, x: np.ndarray, n: int | None = None, batch_size: int = 128) -> np.ndarray:\n \"\"\"\n Makes predictions and then converts probability distribution to counts.\n\n :param x: Sample input with shape as expected by the model.\n :param n: Number of noisy samples to create.\n :param batch_size: Size of batches.\n :return: Array of counts with length equal to number of columns of `x`.\n \"\"\"\n # sample and predict\n x_new = self._noisy_samples(x, n=n)\n predictions = self._predict_classifier(x=x_new, batch_size=batch_size, training_mode=False)\n\n # convert to binary predictions\n idx = np.argmax(predictions, axis=-1)\n pred = np.zeros(predictions.shape)\n pred[np.arange(pred.shape[0]), idx] = 1\n\n # get class counts\n counts = np.sum(pred, axis=0)\n\n return counts\n\n def _lower_confidence_bound(self, n_class_samples: int, n_total_samples: int) -> float:\n \"\"\"\n Uses Clopper-Pearson method to return a (1-alpha) lower confidence bound on bernoulli proportion\n\n :param n_class_samples: Number of samples of a specific class.\n :param n_total_samples: Number of samples for certification.\n :return: Lower bound on the binomial proportion w.p. (1-alpha) over samples.\n \"\"\"\n from statsmodels.stats.proportion import proportion_confint\n\n return proportion_confint(n_class_samples, n_total_samples, alpha=2 * self.alpha, method=\"beta\")[0]\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Randomized Smoothing applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/1902.02918\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport warnings\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.estimators.certification.randomized_smoothing.randomized_smoothing import RandomizedSmoothingMixin\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2RandomizedSmoothing(RandomizedSmoothingMixin, TensorFlowV2Classifier):\n \"\"\"\n Implementation of Randomized Smoothing applied to classifier predictions and gradients, as introduced\n in Cohen et al. (2019).\n\n | Paper link: https://arxiv.org/abs/1902.02918\n \"\"\"\n\n estimator_params = TensorFlowV2Classifier.estimator_params + [\"sample_size\", \"scale\", \"alpha\"]\n\n def __init__(\n self,\n model,\n nb_classes: int,\n input_shape: tuple[int, ...],\n loss_object: \"tf.Tensor\" | None = None,\n optimizer: \"tf.keras.optimizers.Optimizer\" | None = None,\n train_step: Callable | None = None,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n ):\n \"\"\"\n Create a randomized smoothing classifier.\n\n :param model: a python functions or callable class defining the model and providing it prediction as output.\n :type model: `function` or `callable class`\n :param nb_classes: the number of classes in the classification task.\n :param input_shape: Shape of one input for the classifier, e.g. for MNIST input_shape=(28, 28, 1).\n :param loss_object: The loss function for which to compute gradients. This parameter is applied for training\n the model and computing gradients of the loss w.r.t. the input.\n :param optimizer: The optimizer used to train the classifier.\n :param train_step: A function that applies a gradient update to the trainable variables with signature\n `train_step(model, images, labels)`. This will override the default training loop that uses the\n provided `loss_object` and `optimizer` parameters. It is recommended to use the `@tf.function`\n decorator, if possible, for efficient training.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n \"\"\"\n if preprocessing_defences is not None:\n warnings.warn(\n \"\\nWith the current backend (Tensorflow), Gaussian noise will be added by Randomized Smoothing \"\n \"AFTER the application of preprocessing defences. Please ensure this conforms to your use case.\\n\"\n )\n\n super().__init__(\n model=model,\n nb_classes=nb_classes,\n input_shape=input_shape,\n loss_object=loss_object,\n optimizer=optimizer,\n train_step=train_step,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n\n def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:\n return TensorFlowV2Classifier.predict(self, x=x, batch_size=batch_size, training_mode=training_mode, **kwargs)\n\n def _fit_classifier(self, x: np.ndarray, y: np.ndarray, batch_size: int, nb_epochs: int, **kwargs) -> None:\n return TensorFlowV2Classifier.fit(self, x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def fit(\n self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, verbose: bool = False, **kwargs\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports\n \"scheduler\" which is an optional function that will be called at the end of every\n epoch to adjust the learning rate.\n \"\"\"\n import tensorflow as tf\n\n if self._train_step is None: # pragma: no cover\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\n \"A loss function `loss_object` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\n \"An optimizer `optimizer` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n\n @tf.function\n def train_step(model, images, labels):\n with tf.GradientTape() as tape:\n predictions = model(images, training=True)\n loss = self.loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n self.optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n else:\n train_step = self._train_step\n\n scheduler = kwargs.get(\"scheduler\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n train_ds = tf.data.Dataset.from_tensor_slices((x_preprocessed, y_preprocessed)).shuffle(10000).batch(batch_size)\n\n for epoch in trange(nb_epochs, disable=not verbose):\n for images, labels in train_ds:\n # Add random noise for randomized smoothing\n images += tf.random.normal(shape=images.shape, mean=0.0, stddev=self.scale)\n train_step(self.model, images, labels)\n\n if scheduler is not None:\n scheduler(epoch)\n\n def predict( # type: ignore\n self, x: np.ndarray, batch_size: int = 128, verbose: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Perform prediction of the given classifier for a batch of inputs, taking an expectation over transformations.\n\n :param x: Input samples.\n :param batch_size: Batch size.\n :param verbose: Display training progress bar.\n :param is_abstain: True if function will abstain from prediction and return 0s. Default: True\n :type is_abstain: `boolean`\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n return RandomizedSmoothingMixin.predict(\n self, x, batch_size=batch_size, verbose=verbose, training_mode=False, **kwargs\n )\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Correct labels, one-vs-rest encoding.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param sampling: True if loss gradients should be determined with Monte Carlo sampling.\n :type sampling: `bool`\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import tensorflow as tf\n\n sampling = kwargs.get(\"sampling\")\n\n if sampling:\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y, fit=False)\n\n if tf.executing_eagerly():\n with tf.GradientTape() as tape:\n inputs_t = tf.convert_to_tensor(x_preprocessed)\n tape.watch(inputs_t)\n\n inputs_repeat_t = tf.repeat(inputs_t, repeats=self.sample_size, axis=0)\n\n noise = tf.random.normal(\n shape=inputs_repeat_t.shape,\n mean=0.0,\n stddev=self.scale,\n dtype=inputs_repeat_t.dtype,\n seed=None,\n name=None,\n )\n\n inputs_noise_t = inputs_repeat_t + noise\n if self.clip_values is not None:\n inputs_noise_t = tf.clip_by_value(\n inputs_noise_t,\n clip_value_min=self.clip_values[0],\n clip_value_max=self.clip_values[1],\n name=None,\n )\n\n model_outputs = self._model(inputs_noise_t, training=training_mode)\n softmax = tf.nn.softmax(model_outputs, axis=1, name=None)\n average_softmax = tf.reduce_mean(\n tf.reshape(softmax, shape=(-1, self.sample_size, model_outputs.shape[-1])), axis=1\n )\n\n loss = tf.reduce_mean(\n tf.keras.losses.categorical_crossentropy(\n y_true=y, y_pred=average_softmax, from_logits=False, label_smoothing=0\n )\n )\n\n gradients = tape.gradient(loss, inputs_t).numpy()\n else: # pragma: no cover\n raise ValueError(\"Expecting eager execution.\")\n\n # Apply preprocessing gradients\n gradients = self._apply_preprocessing_gradient(x, gradients)\n\n else:\n gradients = TensorFlowV2Classifier.loss_gradient(self, x=x, y=y, training_mode=training_mode, **kwargs)\n\n return gradients\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives of the given classifier w.r.t. `x` of original classifier.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n raise NotImplementedError\n\n def compute_loss(\n self, x: np.ndarray, y: np.ndarray, reduction: str = \"none\", training_mode: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/macer/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements MACER applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/2001.02378\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.estimators.certification.randomized_smoothing.pytorch import PyTorchRandomizedSmoothing\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchMACER(PyTorchRandomizedSmoothing):\n \"\"\"\n Implementation of MACER training, as introduced in Zhai et al. (2020)\n\n | Paper link: https://arxiv.org/abs/2001.02378\n \"\"\"\n\n estimator_params = PyTorchRandomizedSmoothing.estimator_params + [\n \"beta\",\n \"gamma\",\n \"lmbda\",\n \"gauss_num\",\n ]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n beta: float = 16.0,\n gamma: float = 8.0,\n lmbda: float = 12.0,\n gaussian_samples: int = 16,\n ) -> None:\n \"\"\"\n Create a MACER classifier.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n :param beta: The inverse temperature.\n :param gamma: The hinge factor.\n :param lmbda: The trade-off factor.\n :param gaussian_samples: The number of gaussian samples per input.\n \"\"\"\n super().__init__(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n self.beta = beta\n self.gamma = gamma\n self.lmbda = lmbda\n self.gaussian_samples = gaussian_samples\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n import torch.nn.functional as F\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n y_tensor = torch.from_numpy(y_preprocessed)\n dataset = TensorDataset(x_tensor, y_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)\n\n m = torch.distributions.normal.Normal(\n torch.tensor([0.0], device=self.device), torch.tensor([1.0], device=self.device)\n )\n\n # Start training\n for _ in trange(nb_epochs, disable=not verbose):\n for x_batch, y_batch in dataloader:\n # Move inputs to GPU\n x_batch = x_batch.to(self.device)\n y_batch = y_batch.to(self.device)\n\n input_size = len(x_batch)\n\n # Tile samples for Gaussian augmentation\n new_shape = [input_size * self.gaussian_samples]\n new_shape.extend(x_batch[0].shape)\n x_batch = x_batch.repeat((1, self.gaussian_samples, 1, 1)).view(new_shape)\n\n # Add random noise for randomized smoothing\n noise = torch.randn_like(x_batch, device=self.device) * self.scale\n noisy_inputs = x_batch + noise\n\n # Get model outputs\n outputs = self.model(noisy_inputs)\n outputs = outputs.reshape((input_size, self.gaussian_samples, self.nb_classes))\n\n # Classification loss\n outputs_softmax = F.softmax(outputs, dim=2).mean(dim=1)\n outputs_log_softmax = torch.log(outputs_softmax + 1e-10)\n classification_loss = F.nll_loss(outputs_log_softmax, y_batch, reduction=\"sum\")\n\n # Robustness loss\n beta_outputs = outputs * self.beta\n beta_outputs_softmax = F.softmax(beta_outputs, dim=2).mean(dim=1)\n top2_score, top2_idx = torch.topk(beta_outputs_softmax, 2)\n indices_correct = top2_idx[:, 0] == y_batch\n out0, out1 = top2_score[indices_correct, 0], top2_score[indices_correct, 1]\n robustness_loss = m.icdf(out1) - m.icdf(out0)\n indices = (\n ~torch.isnan(robustness_loss)\n & ~torch.isinf(robustness_loss)\n & (torch.abs(robustness_loss) <= self.gamma)\n )\n out0, out1 = out0[indices], out1[indices]\n robustness_loss = m.icdf(out1) - m.icdf(out0) + self.gamma\n robustness_loss = torch.sum(robustness_loss) * self.scale / 2\n\n # Final objective function\n loss = classification_loss + self.lmbda * robustness_loss\n loss /= input_size\n self._optimizer.zero_grad()\n loss.backward()\n self._optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/macer/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements MACER applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/2001.02378\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.estimators.certification.randomized_smoothing.tensorflow import TensorFlowV2RandomizedSmoothing\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2MACER(TensorFlowV2RandomizedSmoothing):\n \"\"\"\n Implementation of MACER training, as introduced in Zhai et al. (2020)\n\n | Paper link: https://arxiv.org/abs/2001.02378\n \"\"\"\n\n estimator_params = TensorFlowV2RandomizedSmoothing.estimator_params + [\n \"beta\",\n \"gamma\",\n \"lmbda\",\n \"gauss_num\",\n ]\n\n def __init__(\n self,\n model,\n nb_classes: int,\n input_shape: tuple[int, ...],\n loss_object: \"tf.Tensor\" | None = None,\n optimizer: \"tf.keras.optimizers.Optimizer\" | None = None,\n train_step: Callable | None = None,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n beta: float = 16.0,\n gamma: float = 8.0,\n lmbda: float = 12.0,\n gaussian_samples: int = 16,\n ) -> None:\n \"\"\"\n Create a MACER classifier.\n\n :param model: a python functions or callable class defining the model and providing it prediction as output.\n :type model: `function` or `callable class`\n :param nb_classes: the number of classes in the classification task.\n :param input_shape: Shape of one input for the classifier, e.g. for MNIST input_shape=(28, 28, 1).\n :param loss_object: The loss function for which to compute gradients. This parameter is applied for training\n the model and computing gradients of the loss w.r.t. the input.\n :param optimizer: The optimizer used to train the classifier.\n :param train_step: A function that applies a gradient update to the trainable variables with signature\n `train_step(model, images, labels)`. This will override the default training loop that uses the\n provided `loss_object` and `optimizer` parameters. It is recommended to use the `@tf.function`\n decorator, if possible, for efficient training.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n :param beta: The inverse temperature.\n :param gamma: The hinge factor.\n :param lmbda: The trade-off factor.\n :param gaussian_samples: The number of gaussian samples per input.\n \"\"\"\n super().__init__(\n model=model,\n nb_classes=nb_classes,\n input_shape=input_shape,\n loss_object=loss_object,\n optimizer=optimizer,\n train_step=train_step,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n self.beta = beta\n self.gamma = gamma\n self.lmbda = lmbda\n self.gaussian_samples = gaussian_samples\n\n def fit(\n self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, verbose: bool = False, **kwargs\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports\n \"scheduler\" which is an optional function that will be called at the end of every\n epoch to adjust the learning rate.\n \"\"\"\n import tensorflow as tf\n\n if self._train_step is None: # pragma: no cover\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\n \"An optimizer `optimizer` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n\n @tf.function\n def train_step(model, images, labels):\n with tf.GradientTape() as tape:\n input_size = len(labels)\n\n outputs = self.model(images, training=True)\n outputs = tf.reshape(outputs, [input_size, self.gaussian_samples, self.nb_classes])\n\n # Classification loss\n outputs_softmax = tf.reduce_mean(tf.nn.softmax(outputs, axis=2), axis=1)\n outputs_log_softmax = tf.math.log(outputs_softmax + 1e-10)\n indices = tf.stack([np.arange(input_size), labels], axis=1)\n nll_loss = tf.gather_nd(outputs_log_softmax, indices=indices)\n classification_loss = -tf.reduce_sum(nll_loss)\n\n # Robustness loss\n beta_outputs = outputs * self.beta\n beta_outputs_softmax = tf.reduce_mean(tf.nn.softmax(beta_outputs, axis=2), axis=1)\n top2_score, top2_idx = tf.math.top_k(beta_outputs_softmax, k=2)\n indices_correct = tf.cast(top2_idx[:, 0], labels.dtype) == labels\n out = tf.boolean_mask(top2_score, indices_correct)\n out0, out1 = out[:, 0], out[:, 1]\n icdf_out1 = tf.math.erfinv(2 * out1 - 1) * np.sqrt(2)\n icdf_out0 = tf.math.erfinv(2 * out0 - 1) * np.sqrt(2)\n robustness_loss = icdf_out1 - icdf_out0\n indices = (\n ~tf.math.is_nan(robustness_loss)\n & ~tf.math.is_inf(robustness_loss)\n & (tf.abs(robustness_loss) <= self.gamma)\n )\n out0, out1 = out0[indices], out1[indices]\n icdf_out1 = tf.math.erfinv(2 * out1 - 1) * np.sqrt(2)\n icdf_out0 = tf.math.erfinv(2 * out0 - 1) * np.sqrt(2)\n robustness_loss = icdf_out1 - icdf_out0 + self.gamma\n robustness_loss = tf.reduce_sum(robustness_loss) * self.scale / 2\n\n # Final objective function\n loss = classification_loss + self.lmbda * robustness_loss\n loss /= input_size\n\n gradients = tape.gradient(loss, model.trainable_variables)\n self._optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n else:\n train_step = self._train_step\n\n scheduler = kwargs.get(\"scheduler\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n train_ds = tf.data.Dataset.from_tensor_slices((x_preprocessed, y_preprocessed)).shuffle(10000).batch(batch_size)\n\n for epoch in trange(nb_epochs, disable=not verbose):\n for images, labels in train_ds:\n # Tile samples for Gaussian augmentation\n input_size = len(images)\n new_shape = [input_size * self.gaussian_samples]\n new_shape.extend(images[0].shape)\n images = tf.reshape(tf.tile(images, (1, 1, 1, self.gaussian_samples)), new_shape)\n\n # Add random noise for randomized smoothing\n noise = tf.random.normal(shape=images.shape, mean=0.0, stddev=self.scale)\n noisy_inputs = images + noise\n\n train_step(self.model, noisy_inputs, labels)\n\n if scheduler is not None:\n scheduler(epoch)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/smooth_adv/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements SmoothAdv applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/1906.04584\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.estimators.certification.randomized_smoothing.pytorch import PyTorchRandomizedSmoothing\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchSmoothAdv(PyTorchRandomizedSmoothing):\n \"\"\"\n Implementation of SmoothAdv training, as introduced in Salman et al. (2019)\n\n | Paper link: https://arxiv.org/abs/1906.04584\n \"\"\"\n\n estimator_params = PyTorchRandomizedSmoothing.estimator_params + [\n \"epsilon\",\n \"num_noise_vec\",\n \"num_steps\",\n \"warmup\",\n ]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n epsilon: float = 1.0,\n num_noise_vec: int = 1,\n num_steps: int = 10,\n warmup: int = 1,\n ) -> None:\n \"\"\"\n Create a SmoothAdv classifier.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n :param epsilon: The maximum perturbation that can be induced.\n :param num_noise_vec: The number of noise vectors.\n :param num_steps: The number of attack updates.\n :param warmup: The warm-up strategy that is gradually increased up to the original value.\n \"\"\"\n super().__init__(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n self.epsilon = epsilon\n self.num_noise_vec = num_noise_vec\n self.num_steps = num_steps\n self.warmup = warmup\n\n classifier = PyTorchClassifier(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n self.attack = ProjectedGradientDescent(classifier, eps=self.epsilon, max_iter=1, verbose=False)\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n y_tensor = torch.from_numpy(y_preprocessed)\n dataset = TensorDataset(x_tensor, y_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)\n\n # Start training\n for epoch in trange(nb_epochs, disable=not verbose):\n self.attack.norm = min(self.epsilon, (epoch + 1) * self.epsilon / self.warmup)\n\n for x_batch, y_batch in dataloader:\n mini_batch_size = len(x_batch) // self.num_noise_vec\n\n for mini_batch in range(self.num_noise_vec):\n # Create mini batch\n inputs = x_batch[mini_batch * mini_batch_size : (mini_batch + 1) * mini_batch_size]\n labels = y_batch[mini_batch * mini_batch_size : (mini_batch + 1) * mini_batch_size]\n\n # Move inputs to GPU\n inputs = inputs.to(self.device)\n labels = labels.to(self.device)\n\n noise = torch.randn_like(inputs) * self.scale\n\n # Attack and find adversarial examples\n self.model.eval()\n original_inputs = inputs.cpu().detach().numpy()\n noise_for_attack = noise.cpu().detach().numpy()\n perturbation_delta = np.zeros_like(original_inputs)\n for _ in range(self.num_steps):\n perturbed_inputs = original_inputs + perturbation_delta\n adv_ex = self.attack.generate(perturbed_inputs + noise_for_attack)\n perturbation_delta = adv_ex - perturbed_inputs - noise_for_attack\n\n # Update perturbed inputs after last iteration\n perturbed_inputs = original_inputs + perturbation_delta\n self.model.train()\n noisy_inputs = torch.from_numpy(perturbed_inputs).to(self.device) + noise\n\n targets = labels.unsqueeze(1).repeat(1, self.num_noise_vec).reshape(-1, 1).squeeze()\n outputs = self.model(noisy_inputs)\n loss = self.loss(outputs, targets)\n\n # Compute gradient and do SGD step\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/smooth_adv/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements SmoothAdv applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/1906.04584\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.estimators.certification.randomized_smoothing.tensorflow import TensorFlowV2RandomizedSmoothing\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2SmoothAdv(TensorFlowV2RandomizedSmoothing):\n \"\"\"\n Implementation of SmoothAdv training, as introduced in Salman et al. (2019)\n\n | Paper link: https://arxiv.org/abs/1906.04584\n \"\"\"\n\n estimator_params = TensorFlowV2RandomizedSmoothing.estimator_params + [\n \"epsilon\",\n \"num_noise_vec\",\n \"num_steps\",\n \"warmup\",\n ]\n\n def __init__(\n self,\n model,\n nb_classes: int,\n input_shape: tuple[int, ...],\n loss_object: \"tf.Tensor\" | None = None,\n optimizer: \"tf.keras.optimizers.Optimizer\" | None = None,\n train_step: Callable | None = None,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n epsilon: float = 1.0,\n num_noise_vec: int = 1,\n num_steps: int = 10,\n warmup: int = 1,\n ) -> None:\n \"\"\"\n Create a MACER classifier.\n\n :param model: a python functions or callable class defining the model and providing it prediction as output.\n :type model: `function` or `callable class`\n :param nb_classes: the number of classes in the classification task.\n :param input_shape: Shape of one input for the classifier, e.g. for MNIST input_shape=(28, 28, 1).\n :param loss_object: The loss function for which to compute gradients. This parameter is applied for training\n the model and computing gradients of the loss w.r.t. the input.\n :param optimizer: The optimizer used to train the classifier.\n :param train_step: A function that applies a gradient update to the trainable variables with signature\n `train_step(model, images, labels)`. This will override the default training loop that uses the\n provided `loss_object` and `optimizer` parameters. It is recommended to use the `@tf.function`\n decorator, if possible, for efficient training.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n :param epsilon: The maximum perturbation that can be induced.\n :param num_noise_vec: The number of noise vectors.\n :param num_steps: The number of attack updates.\n :param warmup: The warm-up strategy that is gradually increased up to the original value.\n \"\"\"\n super().__init__(\n model=model,\n nb_classes=nb_classes,\n input_shape=input_shape,\n loss_object=loss_object,\n optimizer=optimizer,\n train_step=train_step,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n self.epsilon = epsilon\n self.num_noise_vec = num_noise_vec\n self.num_steps = num_steps\n self.warmup = warmup\n\n classifier = TensorFlowV2Classifier(\n model=model,\n nb_classes=nb_classes,\n input_shape=input_shape,\n loss_object=loss_object,\n optimizer=optimizer,\n train_step=train_step,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self.attack = ProjectedGradientDescent(classifier, eps=self.epsilon, max_iter=1, verbose=False)\n\n def fit(\n self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, verbose: bool = False, **kwargs\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports\n \"scheduler\" which is an optional function that will be called at the end of every\n epoch to adjust the learning rate.\n \"\"\"\n import tensorflow as tf\n\n if self._train_step is None: # pragma: no cover\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\n \"A loss function `loss_object` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\n \"An optimizer `optimizer` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n\n @tf.function\n def train_step(model, images, labels):\n with tf.GradientTape() as tape:\n predictions = model(images, training=True)\n loss = self.loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n self.optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n else:\n train_step = self._train_step\n\n scheduler = kwargs.get(\"scheduler\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n train_ds = tf.data.Dataset.from_tensor_slices((x_preprocessed, y_preprocessed)).shuffle(10000).batch(batch_size)\n\n for epoch in trange(nb_epochs, disable=not verbose):\n self.attack.norm = min(self.epsilon, (epoch + 1) * self.epsilon / self.warmup)\n\n for x_batch, y_batch in train_ds:\n mini_batch_size = len(x_batch) // self.num_noise_vec\n\n for mini_batch in range(self.num_noise_vec):\n # Create mini batch\n inputs = x_batch[mini_batch * mini_batch_size : (mini_batch + 1) * mini_batch_size]\n labels = y_batch[mini_batch * mini_batch_size : (mini_batch + 1) * mini_batch_size]\n\n # Tile samples for Gaussian augmentation\n inputs = tf.reshape(tf.tile(inputs, (1, self.num_noise_vec, 1, 1)), x_batch.shape)\n noise = tf.random.normal(inputs.shape, mean=0.0, stddev=self.scale)\n\n original_inputs = inputs.numpy()\n noise_for_attack = noise.numpy()\n perturbation_delta = np.zeros_like(original_inputs)\n for _ in range(self.num_steps):\n perturbed_inputs = original_inputs + perturbation_delta\n adv_ex = self.attack.generate(perturbed_inputs + noise_for_attack)\n perturbation_delta = adv_ex - perturbed_inputs - noise_for_attack\n\n # Add random noise for randomized smoothing\n perturbed_inputs = original_inputs + perturbation_delta\n noisy_inputs = tf.convert_to_tensor(perturbed_inputs) + noise\n\n train_step(self.model, noisy_inputs, labels)\n\n if scheduler is not None:\n scheduler(epoch)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/certification/randomized_smoothing/smooth_mix/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (c) 2021 Jongheon Jeong\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements SmoothMix applied to classifier predictions.\n\n| Paper link: https://arxiv.org/abs/2111.09277\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import trange\nimport numpy as np\n\nfrom art.estimators.certification.randomized_smoothing.pytorch import PyTorchRandomizedSmoothing\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchSmoothMix(PyTorchRandomizedSmoothing):\n \"\"\"\n Implementation of SmoothMix training, as introduced in Jeong et al. (2021)\n\n | Paper link: https://arxiv.org/abs/2111.09277\n \"\"\"\n\n estimator_params = PyTorchRandomizedSmoothing.estimator_params + [\n \"eta\",\n \"num_noise_vec\",\n \"num_steps\",\n \"warmup\",\n \"mix_step\",\n \"maxnorm_s\",\n \"maxnorm\",\n ]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n sample_size: int = 32,\n scale: float = 0.1,\n alpha: float = 0.001,\n eta: float = 1.0,\n num_noise_vec: int = 1,\n num_steps: int = 10,\n warmup: int = 1,\n mix_step: int = 0,\n maxnorm_s: float | None = None,\n maxnorm: float | None = None,\n ) -> None:\n \"\"\"\n Create a SmoothMix classifier.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param sample_size: Number of samples for smoothing.\n :param scale: Standard deviation of Gaussian noise added.\n :param alpha: The failure probability of smoothing.\n :param eta: The relative strength of the mixup loss.\n :param num_noise_vec: The number of noise vectors.\n :param num_steps: The number of attack updates.\n :param warmup: The warm-up strategy that is gradually increased up to the original value.\n :param mix_step: Determines which sample to use for the clean side.\n :param maxnorm_s: The initial value of `alpha * mix_step`.\n :param maxnorm: The initial value of `alpha * mix_step` for adversarial examples.\n \"\"\"\n super().__init__(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n sample_size=sample_size,\n scale=scale,\n alpha=alpha,\n )\n self.eta = eta\n self.num_noise_vec = num_noise_vec\n self.num_steps = num_steps\n self.warmup = warmup\n self.mix_step = mix_step\n self.maxnorm_s = maxnorm_s\n self.maxnorm = maxnorm\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n import torch.nn.functional as F\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n y_tensor = torch.from_numpy(y_preprocessed)\n dataset = TensorDataset(x_tensor, y_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)\n\n # Start training\n for epoch in trange(nb_epochs, disable=not verbose):\n warmup_v = min(1.0, (epoch + 1) / self.warmup)\n\n for x_batch, y_batch in dataloader:\n mini_batch_size = len(x_batch) // self.num_noise_vec\n\n for mini_batch in range(self.num_noise_vec):\n # Create mini batch\n inputs = x_batch[mini_batch * mini_batch_size : (mini_batch + 1) * mini_batch_size]\n labels = y_batch[mini_batch * mini_batch_size : (mini_batch + 1) * mini_batch_size]\n\n # Move inputs to GPU\n inputs = inputs.to(self.device)\n labels = labels.to(self.device)\n\n noises = [torch.randn_like(inputs) * self.scale for _ in range(self.num_noise_vec)]\n\n # Attack and find adversarial examples\n self._model.eval()\n inputs, inputs_adv = self._smooth_mix_pgd_attack(inputs, labels, noises, warmup_v)\n self._model.train(mode=training_mode)\n\n in_clean_c = torch.cat([inputs + noise for noise in noises], dim=0)\n logits_c = self._model(in_clean_c)[-1]\n labels_c = labels.repeat(self.num_noise_vec)\n\n logits_c_chunk = torch.chunk(logits_c, self.num_noise_vec, dim=0)\n clean_sm = F.softmax(torch.stack(logits_c_chunk), dim=-1)\n clean_avg_sm = torch.mean(clean_sm, dim=0)\n loss_xent = F.cross_entropy(logits_c, labels_c, reduction=\"none\")\n\n # mix adversarial examples\n in_mix, labels_mix = self._mix_data(inputs, inputs_adv, clean_avg_sm)\n in_mix_c = torch.cat([in_mix + noise for noise in noises], dim=0)\n labels_mix_c = labels_mix.repeat(self.num_noise_vec, 1)\n logits_mix_c = F.log_softmax(self._model(in_mix_c)[-1], dim=1)\n\n preds = torch.argmax(clean_avg_sm, dim=-1)\n ind_correct = (preds == labels).float()\n ind_correct = ind_correct.repeat(self.num_noise_vec)\n\n loss_mixup = F.kl_div(logits_mix_c, labels_mix_c, reduction=\"none\").sum(1)\n loss = loss_xent.mean() + self.eta * warmup_v * (ind_correct * loss_mixup).mean()\n\n # compute gradient and do SGD step\n self._optimizer.zero_grad()\n loss.backward()\n self._optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n def _smooth_mix_pgd_attack(\n self,\n inputs: \"torch.Tensor\",\n labels: \"torch.Tensor\",\n noises: list[\"torch.Tensor\"],\n warmup_v: float,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n The authors' implementation of the SmoothMixPGD attack.\n Code modified from https://github.com/jh-jeong/smoothmix/blob/main/code/train.py\n\n :param inputs: The batch inputs\n :param labels: The batch labels for the inputs\n :param noises: The noise applied to each input in the attack\n \"\"\"\n import torch\n import torch.nn.functional as F\n\n def _batch_l2_norm(x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Perform a batch L2 norm\n\n :param x: The inputs to compute the batch L2 norm of\n \"\"\"\n x_flat = x.reshape(x.size(0), -1)\n return torch.norm(x_flat, dim=1)\n\n def _project(x: torch.Tensor, x_0: torch.Tensor, maxnorm: float | None = None):\n \"\"\"\n Apply a projection of the current inputs with the maxnorm\n\n :param x: The inputs to apply a projection on (either original or adversarial)\n :param x_0: The unperterbed inputs to apply the projection on\n :param maxnorm: The maxnorm value to apply to x\n \"\"\"\n if maxnorm is not None:\n eta = x - x_0\n eta = eta.renorm(p=2, dim=0, maxnorm=maxnorm)\n x = x_0 + eta\n x = torch.clamp(x, 0, 1)\n x = x.detach()\n return x\n\n adv = inputs.detach()\n init = inputs.detach()\n for i in range(self.num_steps):\n if i == self.mix_step:\n init = adv.detach()\n adv.requires_grad_()\n\n softmax = [F.softmax(self._model(adv + noise)[-1], dim=1) for noise in noises]\n avg_softmax = torch.mean(torch.stack(softmax), dim=0)\n log_softmax = torch.log(avg_softmax.clamp(min=1e-20))\n loss = F.nll_loss(log_softmax, labels, reduction=\"sum\")\n\n grad = torch.autograd.grad(loss, [adv])[0]\n grad_norm = _batch_l2_norm(grad).view(-1, 1, 1, 1)\n grad = grad / (grad_norm + 1e-8)\n adv = adv + self.alpha * grad\n\n adv = _project(adv, inputs, self.maxnorm)\n\n if self.maxnorm_s is None:\n maxnorm_s = self.alpha * self.mix_step * warmup_v\n else:\n maxnorm_s = self.maxnorm_s * warmup_v\n init = _project(init, inputs, maxnorm_s)\n\n return init, adv\n\n def _mix_data(\n self, inputs: \"torch.Tensor\", inputs_adv: \"torch.Tensor\", labels: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Returns mixed inputs and labels.\n\n :param inputs: Training data\n :param inputs_adv: Adversarial training data\n :param labels: Training labels\n \"\"\"\n import torch\n\n eye = torch.eye(self.nb_classes, device=self.device)\n unif = eye.mean(0, keepdim=True)\n lam = torch.rand(inputs.size(0), device=self.device) / 2\n\n mixed_inputs = (1 - lam).view(-1, 1, 1, 1) * inputs + lam.view(-1, 1, 1, 1) * inputs_adv\n mixed_labels = (1 - lam).view(-1, 1) * labels + lam.view(-1, 1) * unif\n\n return mixed_inputs, mixed_labels\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/GPy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a wrapper class for GPy Gaussian Process classification models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport os\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierClassLossGradients\nfrom art import config\n\nif TYPE_CHECKING:\n\n from GPy.models import GPClassification\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\n# pylint: disable=invalid-name\nclass GPyGaussianProcessClassifier(ClassifierClassLossGradients):\n \"\"\"\n Wrapper class for GPy Gaussian Process classification models.\n \"\"\"\n\n def __init__(\n self,\n model: \"GPClassification\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance GPY Gaussian Process classification models.\n\n :param model: GPY Gaussian Process Classification model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n from GPy.models import GPClassification\n\n if not isinstance(model, GPClassification): # pragma: no cover\n raise TypeError(\"Model must be of type GPy.models.GPClassification\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self.nb_classes = 2 # always binary\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n def class_gradient( # type: ignore\n self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, eps: float = 0.0001, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param eps: Fraction added to the diagonal elements of the input `x`.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n grads = np.zeros((np.shape(x_preprocessed)[0], 2, np.shape(x)[1]))\n for i in range(np.shape(x_preprocessed)[0]):\n # Get gradient for the two classes GPC can maximally have\n for i_c in range(2):\n ind = self.predict(x[i].reshape(1, -1))[0, i_c]\n sur = self.predict(\n np.repeat(x_preprocessed[i].reshape(1, -1), np.shape(x_preprocessed)[1], 0)\n + eps * np.eye(np.shape(x_preprocessed)[1])\n )[:, i_c]\n grads[i, i_c] = ((sur - ind) * eps).reshape(1, -1)\n\n grads = self._apply_preprocessing_gradient(x, grads)\n\n if label is not None:\n return grads[:, label, :].reshape(np.shape(x_preprocessed)[0], 1, np.shape(x_preprocessed)[1])\n\n return grads\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y, fit=False)\n\n eps = 0.00001\n grads = np.zeros(np.shape(x))\n for i in range(np.shape(x)[0]):\n # 1.0 - to mimic loss, [0,np.argmax] to get right class\n ind = 1.0 - self.predict(x_preprocessed[i].reshape(1, -1))[0, np.argmax(y[i])]\n sur = (\n 1.0\n - self.predict(\n np.repeat(x_preprocessed[i].reshape(1, -1), np.shape(x_preprocessed)[1], 0)\n + eps * np.eye(np.shape(x_preprocessed)[1])\n )[:, np.argmax(y[i])]\n )\n grads[i] = ((sur - ind) * eps).reshape(1, -1)\n\n grads = self._apply_preprocessing_gradient(x, grads)\n\n return grads\n\n def predict(self, x: np.ndarray, logits: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param logits: `True` if the prediction should be done without squashing function.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Perform prediction\n out = np.zeros((np.shape(x_preprocessed)[0], 2))\n if logits:\n # output the non-squashed version\n out[:, 0] = self.model.predict_noiseless(x_preprocessed)[0].reshape(-1)\n out[:, 1] = -1.0 * out[:, 0]\n else:\n # output normal prediction, scale up to two values\n out[:, 0] = self.model.predict(x_preprocessed)[0].reshape(-1)\n out[:, 1] = 1.0 - out[:, 0]\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=out, fit=False)\n\n return predictions\n\n def predict_uncertainty(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform uncertainty prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of uncertainty predictions of shape `(nb_inputs)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Perform prediction\n out = self.model.predict_noiseless(x_preprocessed)[1]\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=out, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data. Not used, as given to model in initialized earlier.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, path: str | None = None) -> None: # pragma: no cover\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n self.model.save_model(full_path, save_data=False)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nClassifier API for applying all attacks. Use the :class:`.Classifier` wrapper to be able to apply an attack to a\npreexisting model.\n\"\"\"\n\nfrom art.estimators.classification.classifier import (\n ClassifierMixin,\n ClassGradientsMixin,\n)\n\nfrom art.estimators.classification.blackbox import BlackBoxClassifier, BlackBoxClassifierNeuralNetwork\nfrom art.estimators.classification.catboost import CatBoostARTClassifier\nfrom art.estimators.classification.deep_partition_ensemble import DeepPartitionEnsemble\nfrom art.estimators.classification.detector_classifier import DetectorClassifier\nfrom art.estimators.classification.ensemble import EnsembleClassifier\nfrom art.estimators.classification.GPy import GPyGaussianProcessClassifier\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.classification.lightgbm import LightGBMClassifier\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.classification.hugging_face import HuggingFaceClassifierPyTorch\nfrom art.estimators.classification.query_efficient_bb import QueryEfficientGradientEstimationClassifier\nfrom art.estimators.classification.scikitlearn import SklearnClassifier\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.estimators.classification.xgboost import XGBoostClassifier\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/blackbox.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `BlackBoxClassifier` for black-box classifiers.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nfrom functools import total_ordering\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin, Classifier\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass BlackBoxClassifier(ClassifierMixin, BaseEstimator):\n \"\"\"\n Class for black-box classifiers.\n \"\"\"\n\n estimator_params = Classifier.estimator_params + [\"nb_classes\", \"input_shape\", \"predict_fn\"]\n\n def __init__(\n self,\n predict_fn: Callable[[np.ndarray], np.ndarray],\n input_shape: tuple[int, ...],\n nb_classes: int,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n fuzzy_float_compare: bool = False,\n ):\n \"\"\"\n Create a `Classifier` instance for a black-box model.\n\n :param predict_fn: Function that takes in an `np.ndarray` of input data and returns the one-hot encoded matrix\n of predicted classes or tuple of the form `(inputs, labels)` containing the predicted labels for each\n input.\n :param input_shape: Size of input.\n :param nb_classes: Number of prediction classes.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param fuzzy_float_compare: If `predict_fn` is a tuple mapping inputs to labels, and this is True, looking up\n inputs in the table will be done using `numpy.isclose`. Only set to True if really needed, since this\n severely affects performance.\n \"\"\"\n super().__init__(\n model=None,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n if callable(predict_fn):\n self._predict_fn = predict_fn\n else:\n self._predict_fn = _make_lookup_predict_fn(predict_fn, fuzzy_float_compare)\n self._input_shape = input_shape\n self.nb_classes = nb_classes\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def predict_fn(self) -> Callable:\n \"\"\"\n Return the prediction function.\n\n :return: The prediction function.\n \"\"\"\n return self._predict_fn # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n from art.config import ART_NUMPY_DTYPE\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n predictions = np.zeros((x_preprocessed.shape[0], self.nb_classes), dtype=ART_NUMPY_DTYPE)\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = (\n batch_index * batch_size,\n min((batch_index + 1) * batch_size, x_preprocessed.shape[0]),\n )\n predictions[begin:end] = self.predict_fn(x_preprocessed[begin:end])\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=predictions, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels, one-vs-rest encoding.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs or the number of steps per epoch as part of this argument will result in as error.\n :raises `NotImplementedException`: This method is not supported for black-box classifiers.\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. For Keras, .h5 format is used.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n :raises `NotImplementedException`: This method is not supported for black-box classifiers.\n \"\"\"\n raise NotImplementedError\n\n\nclass BlackBoxClassifierNeuralNetwork(NeuralNetworkMixin, ClassifierMixin, BaseEstimator):\n \"\"\"\n Class for black-box neural network classifiers.\n \"\"\"\n\n estimator_params = (\n NeuralNetworkMixin.estimator_params\n + ClassifierMixin.estimator_params\n + BaseEstimator.estimator_params\n + [\"nb_classes\", \"input_shape\", \"predict_fn\"]\n )\n\n def __init__(\n self,\n predict_fn: Callable[[np.ndarray], np.ndarray],\n input_shape: tuple[int, ...],\n nb_classes: int,\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0, 1),\n fuzzy_float_compare: bool = False,\n ):\n \"\"\"\n Create a `Classifier` instance for a black-box model.\n\n :param predict_fn: Function that takes in an `np.ndarray` of input data and returns the one-hot encoded matrix\n of predicted classes or tuple of the form `(inputs, labels)` containing the predicted labels for each\n input.\n :param input_shape: Size of input.\n :param nb_classes: Number of prediction classes.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param fuzzy_float_compare: If `predict_fn` is a tuple mapping inputs to labels, and this is True, looking up\n inputs in the table will be done using `numpy.isclose`. Only set to True if really needed, since this\n severely affects performance.\n \"\"\"\n super().__init__(\n model=None,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n if callable(predict_fn):\n self._predict_fn = predict_fn\n else:\n self._predict_fn = _make_lookup_predict_fn(predict_fn, fuzzy_float_compare)\n self._input_shape = input_shape\n self.nb_classes = nb_classes\n self._learning_phase = None\n self._layer_names = None\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Test set.\n :param batch_size: Size of batches.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n from art.config import ART_NUMPY_DTYPE\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n predictions = np.zeros((x_preprocessed.shape[0], self.nb_classes), dtype=ART_NUMPY_DTYPE)\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = (\n batch_index * batch_size,\n min((batch_index + 1) * batch_size, x_preprocessed.shape[0]),\n )\n predictions[begin:end] = self._predict_fn(x_preprocessed[begin:end])\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=predictions, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the model of the estimator on the training data `x` and `y`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param batch_size: Batch size.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n raise NotImplementedError\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n \"\"\"\n Return the output of a specific layer for samples `x` where `layer` is the index of the layer between 0 and\n `nb_layers - 1 or the name of the layer. The number of layers can be determined by counting the results\n returned by calling `layer_names`.\n\n :param x: Samples\n :param layer: Index or name of the layer.\n :param batch_size: Batch size.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n raise NotImplementedError\n\n def loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n raise NotImplementedError\n\n\n@total_ordering\nclass FuzzyMapping:\n \"\"\"\n Class for a sample/label pair to be used in a `SortedList`.\n \"\"\"\n\n def __init__(self, key: np.ndarray, value=None):\n \"\"\"\n Create an instance of a key/value to pair to be used in a `SortedList`.\n\n :param key: The sample to be matched against.\n :param value: The mapped value.\n \"\"\"\n self.key = key\n self.value = value\n\n def __eq__(self, other):\n return np.all(np.isclose(self.key, other.key))\n\n def __ge__(self, other):\n # This implements >= comparison, so we can use this class in a `SortedList`. The `total_ordering` decorator\n # automatically generates the rest of the comparison magic functions based on this one\n\n close_cells = np.isclose(self.key, other.key)\n if np.all(close_cells):\n return True\n\n # If the keys are not exactly the same (up to floating-point inaccuracies), we compare the value of the first\n # index which is not the same to decide on an ordering\n\n compare_idx = np.unravel_index(np.argmin(close_cells), shape=self.key.shape)\n return self.key[compare_idx] >= other.key[compare_idx]\n\n\ndef _make_lookup_predict_fn(existing_predictions: tuple[np.ndarray, np.ndarray], fuzzy_float_compare: bool) -> Callable:\n \"\"\"\n Makes a predict_fn callback based on a table of existing predictions.\n\n :param existing_predictions: Tuple of (samples, labels).\n :param fuzzy_float_compare: Look up predictions using `np.isclose`, only set to True if really needed, since this\n severely affects performance.\n :return: Prediction function.\n \"\"\"\n\n samples, labels = existing_predictions\n\n if fuzzy_float_compare:\n from sortedcontainers import SortedList\n\n # Construct a search-tree of the predictions, using fuzzy float comparison\n sorted_predictions = SortedList([FuzzyMapping(key, value) for key, value in zip(samples, labels)])\n\n def fuzzy_predict_fn(batch):\n predictions = []\n for row in batch:\n try:\n match_idx = sorted_predictions.index(FuzzyMapping(row))\n except ValueError as err: # pragma: no cover\n raise ValueError(\"No existing prediction for queried input\") from err\n\n predictions.append(sorted_predictions[match_idx].value)\n\n return np.array(predictions)\n\n return fuzzy_predict_fn\n\n # Construct a dictionary to map from samples to predictions. We use the bytes of the `ndarray` as the key,\n # because the `ndarray` itself is not hashable\n mapping = {}\n for x, y in zip(samples, labels):\n mapping[x.tobytes()] = y\n\n def predict_fn(batch):\n predictions = []\n for row in batch:\n row_bytes = row.tobytes()\n if row.tobytes() not in mapping:\n raise ValueError(\"No existing prediction for queried input\")\n\n predictions.append(mapping[row_bytes])\n\n return np.array(predictions)\n\n return predict_fn\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/catboost.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `CatBoostARTClassifier` for CatBoost models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport os\nimport pickle\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierDecisionTree\nfrom art import config\n\nif TYPE_CHECKING:\n\n from catboost.core import CatBoostClassifier\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass CatBoostARTClassifier(ClassifierDecisionTree):\n \"\"\"\n Class for importing CatBoost models.\n \"\"\"\n\n estimator_params = ClassifierDecisionTree.estimator_params + [\"nb_features\"]\n\n def __init__(\n self,\n model: \"CatBoostClassifier\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n nb_features: int | None = None,\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a CatBoost model.\n\n :param model: CatBoost model.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param nb_features: Number of features.\n \"\"\"\n\n from catboost.core import CatBoostClassifier\n\n if not isinstance(model, CatBoostClassifier): # pragma: no cover\n raise TypeError(\"Model must be of type catboost.core.CatBoostClassifier\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n self._input_shape = (nb_features,)\n nb_classes = self._get_nb_classes()\n if nb_classes != -1:\n self.nb_classes = nb_classes\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def nb_features(self) -> int:\n \"\"\"\n Return the number of features.\n\n :return: The number of features.\n \"\"\"\n return self._input_shape[0] # type: ignore\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit` function in `catboost.core.CatBoostClassifier` and will be passed to this function as such.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n self._model.fit(x_preprocessed, y_preprocessed, **kwargs)\n self.nb_classes = self._get_nb_classes()\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Perform prediction\n predictions = self._model.predict_proba(x_preprocessed)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=predictions, fit=False)\n\n return predictions\n\n def _get_nb_classes(self) -> int:\n \"\"\"\n Return the number of output classes.\n\n :return: Number of classes in the data.\n \"\"\"\n if self._model.classes_ is not None:\n return len(self._model.classes_)\n\n return -1\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder): # pragma: no cover\n os.makedirs(folder)\n\n with open(full_path + \".pickle\", \"wb\") as file_pickle:\n pickle.dump(self._model, file=file_pickle)\n\n def get_trees(self):\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/classifier.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements mixin abstract base classes defining properties for all classifiers in ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, ABCMeta, abstractmethod\n\n\nimport numpy as np\n\nfrom art.estimators.estimator import (\n BaseEstimator,\n NeuralNetworkMixin,\n LossGradientsMixin,\n DecisionTreeMixin,\n)\n\n\nclass InputFilter(ABCMeta):\n \"\"\"\n Metaclass to ensure that inputs are ndarray for all the subclass generate and extract calls.\n \"\"\"\n\n def __init__(cls, name, bases, clsdict):\n \"\"\"\n This function overrides any existing generate or extract methods with a new method that\n ensures the input is a ndarray. There is an assumption that the input object has implemented\n __array__ with np.array calls.\n \"\"\"\n\n def make_replacement(fdict, func_name, has_y):\n \"\"\"\n This function overrides creates replacement functions dynamically.\n \"\"\"\n\n def replacement_function(self, *args, **kwargs):\n if len(args) > 0:\n lst = list(args)\n else:\n lst = []\n\n if \"x\" in kwargs: # pragma: no cover\n if not isinstance(kwargs[\"x\"], np.ndarray):\n kwargs[\"x\"] = np.array(kwargs[\"x\"])\n else:\n if not isinstance(args[0], np.ndarray):\n lst[0] = np.array(args[0])\n\n if \"y\" in kwargs: # pragma: no cover\n if kwargs[\"y\"] is not None and not isinstance(kwargs[\"y\"], np.ndarray):\n kwargs[\"y\"] = np.array(kwargs[\"y\"])\n elif has_y: # pragma: no cover\n if not isinstance(args[1], np.ndarray):\n lst[1] = np.array(args[1])\n\n if len(args) > 0:\n args = tuple(lst)\n return fdict[func_name](self, *args, **kwargs)\n\n replacement_function.__doc__ = fdict[func_name].__doc__\n replacement_function.__name__ = \"new_\" + func_name\n return replacement_function\n\n replacement_list_no_y = [\"predict\"]\n replacement_list_has_y = [\"fit\"]\n\n for item in replacement_list_no_y:\n if item in clsdict:\n new_function = make_replacement(clsdict, item, False)\n setattr(cls, item, new_function)\n for item in replacement_list_has_y:\n if item in clsdict:\n new_function = make_replacement(clsdict, item, True)\n setattr(cls, item, new_function)\n\n\nclass ClassifierMixin(ABC, metaclass=InputFilter):\n \"\"\"\n Mixin abstract base class defining functionality for classifiers.\n \"\"\"\n\n estimator_params = [\"nb_classes\"]\n\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs) # type: ignore\n self._nb_classes: int = -1\n\n @property\n def nb_classes(self) -> int:\n \"\"\"\n Return the number of output classes.\n\n :return: Number of classes in the data.\n \"\"\"\n return self._nb_classes # type: ignore\n\n @nb_classes.setter\n def nb_classes(self, nb_classes: int):\n \"\"\"\n Set the number of output classes.\n \"\"\"\n if nb_classes is None or (isinstance(nb_classes, (int, np.integer)) and nb_classes < 2):\n raise ValueError(\"nb_classes must be greater than or equal to 2.\")\n\n self._nb_classes = nb_classes\n\n\nclass ClassGradientsMixin(ABC):\n \"\"\"\n Mixin abstract base class defining classifiers providing access to class gradients. A classifier of this type can\n be combined with certain white-box attacks. This mixin abstract base class has to be mixed in with\n class `Classifier`.\n \"\"\"\n\n @abstractmethod\n def class_gradient(self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Samples.\n :type x: `np.ndarray` or `pandas.DataFrame`\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :return: Gradients of input features w.r.t. each class in the form `(batch_size, nb_classes, input_shape)` when\n computing for all classes, otherwise shape becomes `(batch_size, 1, input_shape)` when `label`\n parameter is specified.\n \"\"\"\n raise NotImplementedError\n\n\nclass Classifier(ClassifierMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + ClassifierMixin.estimator_params\n\n\nclass ClassifierLossGradients(ClassifierMixin, LossGradientsMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + ClassifierMixin.estimator_params\n\n\nclass ClassifierClassLossGradients(ClassGradientsMixin, ClassifierMixin, LossGradientsMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + ClassifierMixin.estimator_params\n\n\nclass ClassifierNeuralNetwork(\n ClassGradientsMixin, ClassifierMixin, LossGradientsMixin, NeuralNetworkMixin, BaseEstimator, ABC\n):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n estimator_params = (\n BaseEstimator.estimator_params + NeuralNetworkMixin.estimator_params + ClassifierMixin.estimator_params\n )\n\n @abstractmethod\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. This function is not supported for\n ensembles.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n raise NotImplementedError\n\n def clone_for_refitting(self) -> \"ClassifierNeuralNetwork\":\n \"\"\"\n Clone classifier for refitting.\n \"\"\"\n raise NotImplementedError\n\n\nclass ClassifierDecisionTree(DecisionTreeMixin, ClassifierMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + ClassifierMixin.estimator_params\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/deep_partition_ensemble.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nCreates a Deep Partition Aggregation ensemble classifier.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nimport warnings\nfrom typing import TYPE_CHECKING\n\nimport copy\nimport numpy as np\n\nfrom art.estimators.classification.ensemble import EnsembleClassifier\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE, CLASSIFIER_NEURALNETWORK_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass DeepPartitionEnsemble(EnsembleClassifier):\n \"\"\"\n Implementation of Deep Partition Aggregation Defense. Training data is partitioned into\n disjoint buckets based on a hash function and a classifier is trained on each bucket.\n\n | Paper link: https://arxiv.org/abs/2006.14768\n \"\"\"\n\n estimator_params = EnsembleClassifier.estimator_params + [\n \"hash_function\",\n \"ensemble_size\",\n ]\n\n def __init__(\n self,\n classifiers: \"CLASSIFIER_NEURALNETWORK_TYPE\" | list[\"CLASSIFIER_NEURALNETWORK_TYPE\"],\n hash_function: Callable | None = None,\n ensemble_size: int = 50,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n :param classifiers: The base model definition to use for defining the ensemble.\n If a list, the list must be the same size as the ensemble size.\n :param hash_function: The function used to partition the training data. If empty, the hash function\n will use the sum of the input values modulo the ensemble size for partitioning.\n :param ensemble_size: The number of models in the ensemble.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier. Not applicable\n in this classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one. Not applicable in this classifier.\n \"\"\"\n self.can_fit = False # self.fit() cannot be used with models loaded from disk\n if not isinstance(classifiers, list):\n warnings.warn(\n \"If a single classifier is passed, it should not have been loaded \\\n from disk due to cloning errors with models loaded from disk. If you are \\\n using pre-trained model(s), create a list of Estimator objects the same \\\n length as the ensemble size\"\n )\n self.can_fit = True\n\n if hasattr(classifiers, \"clone_for_refitting\"):\n # Initialize the ensemble based on the provided architecture\n # Use ART's cloning if possible\n try:\n classifiers = [classifiers.clone_for_refitting() for _ in range(ensemble_size)] # type: ignore\n except ValueError as error:\n warnings.warn(\"Switching to deepcopy due to ART Cloning Error: \" + str(error))\n classifiers = [copy.deepcopy(classifiers) for _ in range(ensemble_size)] # type: ignore\n else:\n classifiers = [copy.deepcopy(classifiers) for _ in range(ensemble_size)]\n elif isinstance(classifiers, list) and len(classifiers) != ensemble_size:\n raise ValueError(\"The length of the classifier list must be the same as the ensemble size\")\n\n super().__init__(\n classifiers=classifiers,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n if hash_function is None:\n\n def default_hash(x):\n return int(np.sum(x)) % ensemble_size\n\n self.hash_function = default_hash\n else:\n self.hash_function = hash_function\n\n self.ensemble_size = ensemble_size\n\n def predict(\n self, x: np.ndarray, batch_size: int = 128, raw: bool = False, max_aggregate: bool = True, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs. Aggregation will be performed on the prediction from\n each classifier if max_aggregate is True. Otherwise, the probabilities will be summed instead.\n For logits output set max_aggregate=True, as logits are not comparable between models and should\n not be aggregated using a sum.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param raw: Return the individual classifier raw outputs (not aggregated).\n :param max_aggregate: Aggregate the predicted classes of each classifier if True. If false, aggregation\n is done using a sum. If raw is true, this arg is ignored\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`, or of shape\n `(nb_classifiers, nb_inputs, nb_classes)` if `raw=True`.\n \"\"\"\n\n if raw:\n return super().predict(x, batch_size=batch_size, raw=True, **kwargs)\n\n # Aggregate based on top-1 prediction from each classifier\n if max_aggregate:\n preds = super().predict(x, batch_size=batch_size, raw=True, **kwargs)\n aggregated_preds = np.zeros_like(preds, shape=preds.shape[1:])\n for i in range(preds.shape[0]):\n aggregated_preds[np.arange(len(aggregated_preds)), np.argmax(preds[i], axis=1)] += 1\n return aggregated_preds\n\n # Aggregate based on summing predictions from each classifier\n return super().predict(x, batch_size=batch_size, raw=False, **kwargs)\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 20,\n train_dict: dict | None = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`. Each classifier will be trained with the\n same parameters unless train_dict is provided. If train_dict is provided, the model id's\n specified will use the training parameters in train_dict instead.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param train_dict: A dictionary of training args if certain models need specialized arguments.\n The key should be the model's partition id and this will override any default training\n parameters including batch_size and nb_epochs.\n :param kwargs: Dictionary of framework-specific arguments.\n \"\"\"\n if self.can_fit:\n # First, partition the data using the hash function\n partition_ind = [[] for _ in range(self.ensemble_size)] # type: list[list[int]]\n for i, p_x in enumerate(x):\n partition_id = int(self.hash_function(p_x))\n partition_ind[partition_id].append(i)\n\n # Then, train each model on its assigned partition\n for i in range(self.ensemble_size):\n current_x = x[np.array(partition_ind[i])]\n current_y = y[np.array(partition_ind[i])]\n\n if train_dict is not None and i in train_dict.keys():\n self.classifiers[i].fit(current_x, current_y, **train_dict[i])\n else:\n self.classifiers[i].fit(current_x, current_y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n else:\n warnings.warn(\"Cannot call fit() for an ensemble of pre-trained classifiers.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/detector_classifier.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the base class `DetectorClassifier` for classifier and detector combinations.\n\nPaper link:\n https://arxiv.org/abs/1705.07263\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierNeuralNetwork\n\nif TYPE_CHECKING:\n from art.utils import PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass DetectorClassifier(ClassifierNeuralNetwork):\n \"\"\"\n This class implements a Classifier extension that wraps a classifier and a detector.\n More details in https://arxiv.org/abs/1705.07263\n \"\"\"\n\n estimator_params = ClassifierNeuralNetwork.estimator_params + [\"classifier\", \"detector\"]\n\n def __init__(\n self,\n classifier: ClassifierNeuralNetwork,\n detector: ClassifierNeuralNetwork,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Initialization for the DetectorClassifier.\n\n :param classifier: A trained classifier.\n :param detector: A trained detector applied for the binary classification.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier. Not applicable\n in this classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one. Not applicable in this classifier.\n \"\"\"\n if preprocessing_defences is not None:\n raise NotImplementedError(\"Preprocessing is not applicable in this classifier.\")\n\n super().__init__(\n model=None,\n clip_values=classifier.clip_values,\n preprocessing=preprocessing,\n channels_first=classifier.channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n )\n\n self.classifier = classifier\n self.detector = detector\n self.nb_classes = classifier.nb_classes + 1\n self._input_shape = classifier.input_shape\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Compute the prediction logits\n classifier_outputs = self.classifier.predict(x=x, batch_size=batch_size)\n detector_outputs = self.detector.predict(x=x, batch_size=batch_size)\n detector_outputs = (np.reshape(detector_outputs, [-1]) + 1) * np.max(classifier_outputs, axis=1)\n detector_outputs = np.reshape(detector_outputs, [-1, 1])\n combined_outputs = np.concatenate([classifier_outputs, detector_outputs], axis=1)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=combined_outputs, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n :raises `NotImplementedException`: This method is not supported for detector-classifiers.\n \"\"\"\n raise NotImplementedError\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n :raises `NotImplementedException`: This method is not supported for detector-classifiers.\n \"\"\"\n raise NotImplementedError\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n if not ( # pragma: no cover\n (label is None)\n or (isinstance(label, int) and label in range(self.nb_classes))\n or (\n isinstance(label, np.ndarray)\n and len(label.shape) == 1\n and (label < self.nb_classes).all()\n and label.shape[0] == x.shape[0]\n )\n ):\n raise ValueError(f\"Label {label} is out of range.\")\n\n # Compute the gradient and return\n if label is None:\n combined_grads = self._compute_combined_grads(x, label=None)\n\n elif isinstance(label, int):\n if label < self.nb_classes - 1:\n # Compute and return from the classifier gradients\n combined_grads = self.classifier.class_gradient(x=x, label=label, training_mode=training_mode, **kwargs)\n\n else:\n # First compute the classifier gradients\n classifier_grads = self.classifier.class_gradient(\n x=x, label=None, training_mode=training_mode, **kwargs\n )\n\n # Then compute the detector gradients\n detector_grads = self.detector.class_gradient(x=x, label=0, training_mode=training_mode, **kwargs)\n\n # Chain the detector gradients for the first component\n classifier_preds = self.classifier.predict(x=x)\n maxind_classifier_preds = np.argmax(classifier_preds, axis=1)\n max_classifier_preds = classifier_preds[np.arange(x.shape[0]), maxind_classifier_preds]\n first_detector_grads = max_classifier_preds[:, None, None, None, None] * detector_grads\n\n # Chain the detector gradients for the second component\n max_classifier_grads = classifier_grads[np.arange(len(classifier_grads)), maxind_classifier_preds]\n detector_preds = self.detector.predict(x=x)\n second_detector_grads = max_classifier_grads * (detector_preds + 1)[:, None, None]\n second_detector_grads = second_detector_grads[None, ...]\n second_detector_grads = np.swapaxes(second_detector_grads, 0, 1)\n\n # Update detector gradients\n combined_grads = first_detector_grads + second_detector_grads\n\n else:\n # Compute indexes for classifier labels and detector labels\n classifier_idx = np.where(label < self.nb_classes - 1)\n detector_idx = np.where(label == self.nb_classes - 1)\n\n # Initialize the combined gradients\n combined_grads = np.zeros(shape=(x.shape[0], 1, x.shape[1], x.shape[2], x.shape[3]))\n\n # First compute the classifier gradients for classifier_idx\n if classifier_idx:\n combined_grads[classifier_idx] = self.classifier.class_gradient(\n x=x[classifier_idx], label=label[classifier_idx].tolist(), training_mode=training_mode, **kwargs\n )\n\n # Then compute the detector gradients for detector_idx\n if detector_idx:\n # First compute the classifier gradients for detector_idx\n classifier_grads = self.classifier.class_gradient(\n x=x[detector_idx], label=None, training_mode=training_mode, **kwargs\n )\n\n # Then compute the detector gradients for detector_idx\n detector_grads = self.detector.class_gradient(\n x=x[detector_idx], label=0, training_mode=training_mode, **kwargs\n )\n\n # Chain the detector gradients for the first component\n classifier_preds = self.classifier.predict(x=x[detector_idx])\n maxind_classifier_preds = np.argmax(classifier_preds, axis=1)\n max_classifier_preds = classifier_preds[np.arange(len(detector_idx)), maxind_classifier_preds]\n first_detector_grads = max_classifier_preds[:, None, None, None, None] * detector_grads\n\n # Chain the detector gradients for the second component\n max_classifier_grads = classifier_grads[np.arange(len(classifier_grads)), maxind_classifier_preds]\n detector_preds = self.detector.predict(x=x[detector_idx])\n second_detector_grads = max_classifier_grads * (detector_preds + 1)[:, None, None]\n second_detector_grads = second_detector_grads[None, ...]\n second_detector_grads = np.swapaxes(second_detector_grads, 0, 1)\n\n # Update detector gradients\n detector_grads = first_detector_grads + second_detector_grads\n\n # Reassign the combined gradients\n combined_grads[detector_idx] = detector_grads\n\n return combined_grads\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of the same shape as `x`.\n :raises `NotImplementedException`: This method is not supported for detector-classifiers.\n \"\"\"\n raise NotImplementedError\n\n @property\n def layer_names(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable. This function is not supported for the\n Classifier and Detector classes.\n\n :return: The hidden layers in the model, input and output layers excluded.\n :raises `NotImplementedException`: This method is not supported for detector-classifiers.\n \"\"\"\n raise NotImplementedError\n\n def get_activations(\n self, x: np.ndarray, layer: int | str, batch_size: int = 128, framework: bool = False\n ) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations.\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n :raises `NotImplementedException`: This method is not supported for detector-classifiers.\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n self.classifier.save(filename=filename + \"_classifier\", path=path)\n self.detector.save(filename=filename + \"_detector\", path=path)\n\n def clone_for_refitting(self) -> \"DetectorClassifier\":\n \"\"\"\n Clone classifier for refitting.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(classifier={self.classifier}, \"\n f\"detector={self.detector}, postprocessing_defences={self.postprocessing_defences}, \"\n f\"preprocessing={self.preprocessing}\"\n )\n return repr_\n\n def _compute_combined_grads(self, x: np.ndarray, label: int | list[int] | None = None) -> np.ndarray:\n # Compute the classifier gradients\n classifier_grads = self.classifier.class_gradient(x=x, label=label)\n\n # Then compute the detector gradients\n detector_grads = self.detector.class_gradient(x=x, label=label)\n\n # Chain the detector gradients for the first component\n classifier_preds = self.classifier.predict(x=x)\n maxind_classifier_preds = np.argmax(classifier_preds, axis=1)\n max_classifier_preds = classifier_preds[np.arange(classifier_preds.shape[0]), maxind_classifier_preds]\n first_detector_grads = max_classifier_preds[:, None, None, None, None] * detector_grads\n\n # Chain the detector gradients for the second component\n max_classifier_grads = classifier_grads[np.arange(len(classifier_grads)), maxind_classifier_preds]\n detector_preds = self.detector.predict(x=x)\n second_detector_grads = max_classifier_grads * (detector_preds + 1)[:, None, None]\n second_detector_grads = second_detector_grads[None, ...]\n second_detector_grads = np.swapaxes(second_detector_grads, 0, 1)\n\n # Update detector gradients\n detector_grads = first_detector_grads + second_detector_grads\n\n # Combine the gradients\n combined_logits_grads = np.concatenate([classifier_grads, detector_grads], axis=1)\n\n return combined_logits_grads\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/ensemble.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `EnsembleClassifier` for ensembles of multiple classifiers.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierNeuralNetwork\nfrom art.estimators.estimator import NeuralNetworkMixin\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE, CLASSIFIER_NEURALNETWORK_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass EnsembleClassifier(ClassifierNeuralNetwork):\n \"\"\"\n Class allowing to aggregate multiple classifiers as an ensemble. The individual classifiers are expected to be\n trained when the ensemble is created and no training procedures are provided through this class.\n \"\"\"\n\n estimator_params = ClassifierNeuralNetwork.estimator_params + [\n \"classifiers\",\n \"classifier_weights\",\n ]\n\n def __init__(\n self,\n classifiers: list[\"CLASSIFIER_NEURALNETWORK_TYPE\"],\n classifier_weights: list | np.ndarray | None = None,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Initialize a :class:`.EnsembleClassifier` object. The data range values and colour channel index have to\n be consistent for all the classifiers in the ensemble.\n\n :param classifiers: List of :class:`.Classifier` instances to be ensembled together.\n :param classifier_weights: List of weights, one scalar per classifier, to assign to their prediction when\n aggregating results. If `None`, all classifiers are assigned the same weight.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier. Not applicable\n in this classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one. Not applicable in this classifier.\n \"\"\"\n if preprocessing_defences is not None:\n raise NotImplementedError(\"Preprocessing is not applicable in this classifier.\")\n\n super().__init__(\n model=None,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._nb_classifiers = len(classifiers)\n\n # Assert all classifiers are the right shape(s)\n for classifier in classifiers:\n if not isinstance(classifier, NeuralNetworkMixin): # pragma: no cover\n raise TypeError(f\"Expected type `Classifier`, found {type(classifier)} instead.\")\n\n if (\n isinstance(classifier.clip_values, np.ndarray)\n and isinstance(self.clip_values, np.ndarray)\n and not np.array_equal(self.clip_values, classifier.clip_values)\n ): # pragma: no cover\n raise ValueError(\n f\"Incompatible `clip_values` between classifiers in the ensemble. Found {self.clip_values} and \"\n f\"{classifier.clip_values}.\"\n )\n\n if classifier.nb_classes != classifiers[0].nb_classes: # pragma: no cover\n raise ValueError(\n f\"Incompatible output shapes between classifiers in the ensemble. Found {classifier.nb_classes} \"\n f\"and {classifiers[0].nb_classes}.\"\n )\n\n if classifier.input_shape != classifiers[0].input_shape: # pragma: no cover\n raise ValueError(\n f\"Incompatible input shapes between classifiers in the ensemble. Found {classifier.input_shape} \"\n f\"and {classifiers[0].input_shape}.\"\n )\n\n self._input_shape = classifiers[0].input_shape\n self.nb_classes = classifiers[0].nb_classes\n\n # Set weights for classifiers\n if classifier_weights is None:\n self._classifier_weights = np.ones(self._nb_classifiers) / self._nb_classifiers\n else:\n self._classifier_weights = np.array(classifier_weights)\n\n # check for consistent channels_first in ensemble members\n for i_cls, cls in enumerate(classifiers):\n if cls.channels_first != self.channels_first: # pragma: no cover\n raise ValueError(\n f\"The channels_first boolean of classifier {i_cls} is {cls.channels_first} while this ensemble \"\n f\"expects a channels_first boolean of {self.channels_first}. The channels_first booleans of all \"\n f\"classifiers and the ensemble need ot be identical.\"\n )\n\n self._classifiers = classifiers\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def classifiers(self) -> list[ClassifierNeuralNetwork]:\n \"\"\"\n Return the Classifier instances that are ensembled together.\n\n :return: Classifier instances that are ensembled together.\n \"\"\"\n return self._classifiers # type: ignore\n\n @property\n def classifier_weights(self) -> np.ndarray:\n \"\"\"\n Return the list of classifier weights to assign to their prediction when aggregating results.\n\n :return: The list of classifier weights to assign to their prediction when aggregating results.\n \"\"\"\n return self._classifier_weights # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, raw: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs. Predictions from classifiers should only be aggregated if they all\n have the same type of output (e.g., probabilities). Otherwise, use `raw=True` to get predictions from all\n models without aggregation. The same option should be used for logits output, as logits are not comparable\n between models and should not be aggregated.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param raw: Return the individual classifier raw outputs (not aggregated).\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`, or of shape\n `(nb_classifiers, nb_inputs, nb_classes)` if `raw=True`.\n \"\"\"\n preds = np.array(\n [self.classifier_weights[i] * self.classifiers[i].predict(x) for i in range(self._nb_classifiers)]\n )\n if raw:\n return preds\n\n # Aggregate predictions only at probabilities level, as logits are not comparable between models\n var_z = np.sum(preds, axis=0)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=var_z, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`. This function is not supported for ensembles.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments.\n :raises `NotImplementedException`: This method is not supported for ensembles.\n \"\"\"\n raise NotImplementedError\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the generator that yields batches as specified. This function is not supported for\n ensembles.\n\n :param generator: Batch generator providing `(x, y)` for each epoch. If the generator can be used for native\n training in Keras, it will.\n :param nb_epochs: Number of epochs to use for trainings.\n :param kwargs: Dictionary of framework-specific argument.\n :raises `NotImplementedException`: This method is not supported for ensembles.\n \"\"\"\n raise NotImplementedError\n\n @property\n def layer_names(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable. This function is not supported for ensembles.\n\n :return: The hidden layers in the model, input and output layers excluded.\n :raises `NotImplementedException`: This method is not supported for ensembles.\n \"\"\"\n raise NotImplementedError\n\n def get_activations(\n self, x: np.ndarray, layer: int | str, batch_size: int = 128, framework: bool = False\n ) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`. This function is not supported for ensembles.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations.\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n :raises `NotImplementedException`: This method is not supported for ensembles.\n \"\"\"\n raise NotImplementedError\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n raw: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If `None`, then gradients for all classes will be\n computed.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param raw: Return the individual classifier raw outputs (not aggregated).\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified. If `raw=True`, an additional\n dimension is added at the beginning of the array, indexing the different classifiers.\n \"\"\"\n grads = np.array(\n [\n self.classifier_weights[i]\n * self.classifiers[i].class_gradient(x=x, label=label, training_mode=training_mode, **kwargs)\n for i in range(self._nb_classifiers)\n ]\n )\n if raw:\n return grads\n\n return np.sum(grads, axis=0)\n\n def loss_gradient(\n self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, raw: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param raw: Return the individual classifier raw outputs (not aggregated).\n :return: Array of gradients of the same shape as `x`. If `raw=True`, shape becomes `[nb_classifiers, x.shape]`.\n \"\"\"\n grads = np.array(\n [\n self.classifier_weights[i]\n * self.classifiers[i].loss_gradient(x=x, y=y, training_mode=training_mode, **kwargs)\n for i in range(self._nb_classifiers)\n ]\n )\n if raw:\n return grads\n\n return np.sum(grads, axis=0)\n\n def clone_for_refitting(self) -> \"EnsembleClassifier\":\n \"\"\"\n Clone classifier for refitting.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(classifiers={self.classifiers}, \"\n f\"classifier_weights={self.classifier_weights!r}, channels_first={self.channels_first}, \"\n f\"clip_values={self.clip_values!r}, preprocessing_defences={self.preprocessing_defences}, \"\n f\"postprocessing_defences={self.postprocessing_defences}, preprocessing={self.preprocessing})\"\n )\n\n return repr_\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. This function is not supported for\n ensembles.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n :raises `NotImplementedException`: This method is not supported for ensembles.\n \"\"\"\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/hugging_face.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract estimator `HuggingFaceClassifier` using the PyTorchClassifier as a backend\nto interface with ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nimport six\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\n\nif TYPE_CHECKING:\n import torch\n import transformers\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n from transformers.modeling_outputs import ImageClassifierOutput\n\nlogger = logging.getLogger(__name__)\n\n\nclass HuggingFaceClassifierPyTorch(PyTorchClassifier):\n \"\"\"\n This class implements a classifier with the HuggingFace framework.\n \"\"\"\n\n def __init__(\n self,\n model: \"transformers.PreTrainedModel\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None,\n use_amp: bool = False,\n opt_level: str = \"O1\",\n loss_scale: float | str | None = \"dynamic\",\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n processor: Callable | None = None,\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Initialization of HuggingFaceClassifierPyTorch specifically for the PyTorch-based backend.\n\n :param model: Huggingface model which returns outputs of type ImageClassifierOutput from the `transformers`\n library. Must have the logits attribute set as output.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param optimizer: The optimizer used to train the classifier.\n :param use_amp: Whether to use the automatic mixed precision tool to enable mixed precision training or\n gradient computation, e.g. with loss gradient computation. When set to True, this option is\n only triggered if there are GPUs available.\n :param opt_level: Specify a pure or mixed precision optimization level. Used when use_amp is True. Accepted\n values are `O0`, `O1`, `O2`, and `O3`.\n :param loss_scale: Loss scaling. Used when use_amp is True. If passed as a string, must be a string\n representing a number, e.g., \u201c1.0\u201d, or the string \u201cdynamic\u201d.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last. Normally should be set to True for HF models based on\n a pytorch backend.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n :param processor: Optional argument. Function which takes in a batch of data and performs\n the preprocessing relevant to a given foundation model.\n Must be differentiable for gradient based defences and attacks.\n \"\"\"\n import torch\n\n self.processor = processor\n\n super().__init__(\n model=model,\n loss=loss,\n input_shape=input_shape,\n nb_classes=nb_classes,\n optimizer=optimizer,\n use_amp=use_amp,\n opt_level=opt_level,\n loss_scale=loss_scale,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n\n import functools\n\n def prefix_function(function: Callable, postfunction: Callable) -> Callable[[Any, Any], torch.Tensor]:\n \"\"\"\n Huggingface returns logit under outputs.logits. To make this compatible with ART we wrap the forward pass\n function of an HF model here, which automatically extracts the logits.\n\n :param function: The first function to run, in our case the forward pass of the model.\n :param postfunction: Second function to run, in this case simply extracts the logits.\n :return: model outputs.\n \"\"\"\n\n @functools.wraps(function)\n def run(*args, **kwargs) -> torch.Tensor:\n outputs = function(*args, **kwargs)\n return postfunction(outputs)\n\n return run\n\n def get_logits(outputs: \"ImageClassifierOutput\") -> torch.Tensor:\n \"\"\"\n Gets the logits attribute from ImageClassifierOutput\n\n :param outputs: outputs of type ImageClassifierOutput from a Huggingface\n :return: model's logit predictions.\n \"\"\"\n if isinstance(outputs, torch.Tensor):\n return outputs\n return outputs.logits\n\n self.model.forward = prefix_function(self.model.forward, get_logits) # type: ignore\n\n def _make_model_wrapper(self, model: \"torch.nn.Module\") -> \"torch.nn.Module\":\n # Try to import PyTorch and create an internal class that acts like a model wrapper extending torch.nn.Module\n import torch\n\n input_shape = self._input_shape\n input_for_hook = torch.rand(input_shape)\n # self.device may not match the device the raw model was passed into ART.\n # Check if the model is on cuda, if so set the hook input accordingly\n if next(model.parameters()).is_cuda:\n cuda_idx = torch.cuda.current_device()\n input_for_hook = input_for_hook.to(torch.device(f\"cuda:{cuda_idx}\"))\n\n input_for_hook = torch.unsqueeze(input_for_hook, dim=0)\n\n if self.processor is not None:\n input_for_hook = self.processor(input_for_hook)\n\n processor = self.processor\n try:\n # Define model wrapping class only if not defined before\n if not hasattr(self, \"_model_wrapper\"):\n\n class ModelWrapper(torch.nn.Module):\n \"\"\"\n This is a wrapper for the input model.\n \"\"\"\n\n def __init__(self, model: torch.nn.Module):\n \"\"\"\n Initialization by storing the input model.\n\n :param model: PyTorch model. The forward function of the model must return the logit output.\n \"\"\"\n super().__init__()\n self._model = model\n\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n This is where we get outputs from the input model.\n\n :param x: Input data.\n :type x: `torch.Tensor`\n :return: a list of output layers, where the last 2 layers are logit and final outputs.\n :rtype: `list`\n \"\"\"\n\n # disable pylint because access to _model required\n\n result = []\n\n if isinstance(self._model, torch.nn.Module):\n if processor is not None:\n x = processor(x)\n x = self._model.forward(x)\n result.append(x)\n\n else: # pragma: no cover\n raise TypeError(\"The input model must inherit from `nn.Module`.\")\n\n return result\n\n @property\n def get_layers(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n\n .. warning:: `get_layers` tries to infer the internal structure of the model.\n This feature comes with no guarantees on the correctness of the result.\n The intended order of the layers tries to match their order in the model, but this\n is not guaranteed either.\n \"\"\"\n\n result_dict = {}\n\n modules = []\n\n def forward_hook(input_module, hook_input, hook_output):\n logger.info(\"input_module is %s with id %i\", input_module, id(input_module))\n modules.append(id(input_module))\n\n handles = []\n\n for name, module in self._model.named_modules():\n logger.info(\n \"found %s with type %s and id %i and name %s with submods %i \",\n module,\n type(module),\n id(module),\n name,\n len(list(module.named_modules())),\n )\n\n if name != \"\" and len(list(module.named_modules())) == 1:\n handles.append(module.register_forward_hook(forward_hook))\n result_dict[id(module)] = name\n\n logger.info(\"mapping from id to name is %s\", result_dict)\n\n logger.info(\"------ Finished Registering Hooks------\")\n model(input_for_hook) # hooks are fired sequentially from model input to the output\n\n logger.info(\"------ Finished Fire Hooks------\")\n\n # Remove the hooks\n for hook in handles:\n hook.remove()\n\n logger.info(\"new result is: \")\n name_order = []\n for module in modules:\n name_order.append(result_dict[module])\n\n logger.info(name_order)\n\n return name_order\n\n # Set newly created class as private attribute\n self._model_wrapper = ModelWrapper # type: ignore\n\n # Use model wrapping class to wrap the PyTorch model received as argument\n return self._model_wrapper(model)\n\n except ImportError: # pragma: no cover\n raise ImportError(\"Could not find PyTorch (`torch`) installation.\") from ImportError\n\n def get_activations( # type: ignore\n self,\n x: np.ndarray | \"torch.Tensor\",\n layer: int | str | None = None,\n batch_size: int = 128,\n framework: bool = False,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n import torch\n\n self._model.eval()\n\n # Apply defences\n if framework:\n no_grad = False\n else:\n no_grad = True\n x_preprocessed, _ = self._apply_preprocessing(x=x, y=None, fit=False, no_grad=no_grad)\n\n # Get index of the extracted layer\n if isinstance(layer, six.string_types):\n if layer not in self._layer_names: # pragma: no cover\n raise ValueError(f\"Layer name {layer} not supported\")\n layer_index = self._layer_names.index(layer)\n\n elif isinstance(layer, int):\n layer_index = layer\n\n else: # pragma: no cover\n raise TypeError(\"Layer must be of type str or int\")\n\n def get_feature(name):\n # the hook signature\n def hook(model, input, output): # pylint: disable=redefined-builtin,unused-argument\n # TODO: this is using the input, rather than the output, to circumvent the fact\n # TODO: that flatten is not a layer in pytorch, and the activation defence expects\n # TODO: a flattened input. A better option is to refactor the activation defence\n # TODO: to not crash if non 2D inputs are provided.\n self._features[name] = input\n\n return hook\n\n if not hasattr(self, \"_features\"):\n self._features: dict[str, torch.Tensor] = {}\n # register forward hooks on the layers of choice\n handles = []\n\n lname = self._layer_names[layer_index]\n\n if layer not in self._features:\n for name, module in self.model.named_modules():\n if name == lname and len(list(module.named_modules())) == 1:\n handles.append(module.register_forward_hook(get_feature(name)))\n\n if framework:\n if isinstance(x_preprocessed, torch.Tensor):\n self._model(x_preprocessed)\n return self._features[self._layer_names[layer_index]][0]\n input_tensor = torch.from_numpy(x_preprocessed)\n self._model(input_tensor.to(self._device))\n return self._features[self._layer_names[layer_index]][0]\n\n # Run prediction with batch processing\n results = []\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Run prediction for the current batch\n self._model(torch.from_numpy(x_preprocessed[begin:end]).to(self._device))\n layer_output = self._features[self._layer_names[layer_index]]\n\n if isinstance(layer_output, tuple):\n results.append(layer_output[0].detach().cpu().numpy())\n else:\n results.append(layer_output.detach().cpu().numpy())\n\n results_array = np.concatenate(results)\n return results_array\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/keras.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `KerasClassifier` for Keras models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nimport os\nfrom typing import (\n Iterator,\n Union,\n TYPE_CHECKING,\n)\n\nimport numpy as np\n\nfrom art import config\nfrom art.estimators.keras import KerasEstimator\nfrom art.estimators.classification.classifier import (\n ClassifierMixin,\n ClassGradientsMixin,\n)\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\nKERAS_MODEL_TYPE = Union[\"tf.keras.models.Model\"] # pylint: disable=invalid-name\n\n\nclass KerasClassifier(ClassGradientsMixin, ClassifierMixin, KerasEstimator):\n \"\"\"\n Wrapper class for importing Keras models.\n \"\"\"\n\n estimator_params = (\n KerasEstimator.estimator_params\n + ClassifierMixin.estimator_params\n + [\"use_logits\", \"input_layer\", \"output_layer\"]\n )\n\n def __init__(\n self,\n model: KERAS_MODEL_TYPE,\n use_logits: bool = False,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n input_layer: int = 0,\n output_layer: int = 0,\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a Keras model. Assumes the `model` passed as argument is compiled.\n\n :param model: Keras model, neural network or other.\n :param use_logits: True if the output of the model are logits; false for probabilities or any other type of\n outputs. Logits output should be favored when possible to ensure attack efficiency.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param input_layer: The index of the layer to consider as input for models with multiple input layers. The layer\n with this index will be considered for computing gradients. For models with only one input\n layer this values is not required.\n :param output_layer: Which layer to consider as the output when the models have multiple output layers. The\n layer with this index will be considered for computing gradients. For models with only one\n output layer this values is not required.\n \"\"\"\n import tensorflow as tf\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n channels_first=channels_first,\n )\n self._model = model\n self._use_logits = use_logits\n if isinstance(model.output_shape, list):\n nb_classes = model.output_shape[output_layer][-1]\n else:\n nb_classes = model.output_shape[-1]\n\n # Check for binary classification\n if nb_classes == 1:\n nb_classes = 2\n self.nb_classes = nb_classes\n\n # Ensure model is built\n if not model.built:\n input_shape = model.layers[0].input_shape[1:] # Adjust as needed\n model.build((None, *input_shape))\n _ = model(tf.zeros((1, *input_shape))) # Force a call\n\n self._input = model.inputs[input_layer]\n self._output = model.outputs[output_layer]\n self._input_layer = input_layer\n self._output_layer = output_layer\n self._input_shape = tuple(self._input.shape[1:])\n self._layer_names = self._get_layers()\n\n @tf.function(reduce_retracing=True) # Compile this for speed\n def _forward_pass(model, x, training, batch_size):\n return model(x, training=training, batch_size=batch_size, verbose=False)\n\n self._forward_pass = _forward_pass\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def use_logits(self) -> bool:\n \"\"\"\n A boolean representing whether the outputs of the model are logits.\n\n :return: a boolean representing whether the outputs of the model are logits.\n \"\"\"\n return self._use_logits # type: ignore\n\n @property\n def input_layer(self) -> int:\n \"\"\"\n The index of the layer considered as input for models with multiple input layers.\n For models with only one input layer the index is 0.\n\n :return: The index of the layer considered as input for models with multiple input layers.\n \"\"\"\n return self._input_layer # type: ignore\n\n @property\n def output_layer(self) -> int:\n \"\"\"\n The index of the layer considered as output for models with multiple output layers.\n For models with only one output layer the index is 0.\n\n :return: The index of the layer considered as output for models with multiple output layers.\n \"\"\"\n return self._output_layer # type: ignore\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, reduction: str = \"none\", **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n import tensorflow as tf\n\n # Preprocess input\n y = check_and_transform_label_format(y, self.nb_classes) # type: ignore\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n shape_match = [i is None or i == j for i, j in zip(self._input_shape, x_preprocessed.shape[1:])]\n if not all(shape_match): # pragma: no cover\n raise ValueError(\n f\"Error when checking x: expected preprocessed x to have shape {self._input_shape} but got array with \"\n f\"shape {x_preprocessed.shape[1:]}.\"\n )\n\n # Adjust shape of y if necessary\n if (\n \"__name__\" in dir(self._model.loss) and self._model.loss.__name__ in [\"sparse_categorical_crossentropy\"]\n ) or isinstance(self._model.loss, tf.keras.losses.SparseCategoricalCrossentropy):\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n # Convert to tensors\n x_tf = tf.convert_to_tensor(x_preprocessed)\n y_tf = tf.convert_to_tensor(y_preprocessed)\n\n # Get predictions\n predictions = self._model(x_tf, training=False)\n\n # Compute loss (no need to access .loss attribute directly)\n loss_tensor = self._model.compiled_loss(y_tf, predictions)\n\n # Convert loss tensor to numpy\n loss_value = loss_tensor.numpy()\n\n # Apply user-specified reduction\n if reduction == \"none\":\n loss_value_list = []\n for i in range(x_tf.shape[0]):\n predictions_i = self._model(x_tf[i : i + 1], training=False)\n loss_tensor_i = self._model.compiled_loss(y_tf[i : i + 1], predictions_i)\n loss_value_list.append(loss_tensor_i.numpy())\n loss_value = np.array(loss_value_list)\n\n elif reduction == \"mean\":\n predictions = self._model(x_tf, training=False)\n loss_tensor = self._model.compiled_loss(y_tf, predictions)\n loss_value = loss_tensor.numpy()\n\n elif reduction == \"sum\":\n loss_value = 0\n for i in range(x_tf.shape[0]):\n predictions_i = self._model(x_tf[i : i + 1], training=False)\n loss_tensor_i = self._model.compiled_loss(y_tf[i : i + 1], predictions_i)\n loss_value += loss_tensor_i.numpy()\n\n return loss_value\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import tensorflow as tf\n\n # Preprocess input\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n shape_match = [i is None or i == j for i, j in zip(self._input_shape, x_preprocessed.shape[1:])]\n if not all(shape_match): # pragma: no cover\n raise ValueError(\n f\"Error when checking x: expected preprocessed x to have shape {self._input_shape} but got array with \"\n f\"shape {x_preprocessed.shape[1:]}\"\n )\n\n # Adjust shape of y if necessary (one-hot -> sparse)\n if (\n (isinstance(self._model.loss, str) and self._model.loss in [\"sparse_categorical_crossentropy\"])\n or (\n \"__name__\" in dir(self._model.loss) and self._model.loss.__name__ in [\"sparse_categorical_crossentropy\"]\n )\n or isinstance(self._model.loss, tf.keras.losses.SparseCategoricalCrossentropy)\n ):\n if y_preprocessed.ndim > 1 and y_preprocessed.shape[1] > 1:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n # Convert to tensors\n x_tf = tf.convert_to_tensor(x_preprocessed)\n y_tf = tf.convert_to_tensor(y_preprocessed)\n\n # Get the loss function\n loss_attr = self._model.loss\n\n if isinstance(loss_attr, str):\n # Loss is a string, get the Keras loss object\n loss_fn = tf.keras.losses.get(loss_attr)\n if hasattr(loss_fn, \"get_config\"):\n loss_fn = loss_fn.__class__.from_config(loss_fn.get_config())\n loss_fn.reduction = tf.keras.losses.Reduction.NONE\n\n elif hasattr(loss_attr, \"get_config\"):\n # Loss is a Keras loss object, like CategoricalCrossentropy()\n loss_fn = loss_attr.__class__.from_config(loss_attr.get_config())\n loss_fn.reduction = tf.keras.losses.Reduction.NONE\n\n elif callable(loss_attr):\n # Loss is a plain function (like a custom sparse_categorical_crossentropy)\n loss_fn = loss_attr\n import warnings\n\n warnings.warn(\n \"Loss function is a plain function, not a Keras loss object. \"\n \"Cannot set reduction; assuming per-sample loss.\"\n )\n\n else:\n raise TypeError(f\"Unsupported loss type: {type(loss_attr)}\")\n\n # Compute loss gradient w.r.t. input\n with tf.GradientTape() as tape:\n tape.watch(x_tf)\n y_pred = self._model(x_tf, training=training_mode)\n loss = loss_fn(y_tf, y_pred)\n\n gradients = tape.gradient(loss, x_tf)\n gradients = gradients.numpy()\n gradients = self._apply_preprocessing_gradient(x, gradients)\n assert gradients.shape == x.shape\n\n return gradients\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values are provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n import tensorflow as tf\n\n # Check label validity\n if not (\n label is None\n or (isinstance(label, (int, np.integer)) and 0 <= label < self.nb_classes)\n or (\n isinstance(label, np.ndarray)\n and label.ndim == 1\n and (label < self.nb_classes).all()\n and label.shape[0] == x.shape[0]\n )\n ):\n raise ValueError(f\"Label {label} is out of range.\") # pragma: no cover\n\n # Preprocess input\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n shape_match = [i is None or i == j for i, j in zip(self._input_shape, x_preprocessed.shape[1:])]\n if not all(shape_match): # pragma: no cover\n raise ValueError(\n f\"Error when checking x: expected preprocessed x to have shape {self._input_shape} but got array with \"\n f\"shape {x_preprocessed.shape[1:]}\"\n )\n\n x_tf = tf.convert_to_tensor(x_preprocessed)\n training = training_mode\n\n # Compute gradients\n with tf.GradientTape() as tape:\n tape.watch(x_tf)\n preds = self._model(x_tf, training=training) # Shape: (batch_size, nb_classes)\n\n grads = tape.batch_jacobian(preds, x_tf) # Shape: (batch_size, nb_classes, input_shape...)\n\n if label is None:\n gradients = grads.numpy() # Shape: (batch_size, nb_classes, input_shape...)\n elif isinstance(label, (int, np.integer)):\n gradients = grads[:, label : label + 1, ...].numpy() # Shape: (batch_size, 1, input_shape...)\n else:\n # label is an array\n label = np.asarray(label)\n gradients = np.stack(\n [grads[i, label[i], ...] for i in range(x_tf.shape[0])], axis=0\n ) # Shape: (batch_size, input_shape...)\n gradients = np.expand_dims(gradients, axis=1) # Shape: (batch_size, 1, input_shape...)\n\n gradients = self._apply_preprocessing_gradient(x, gradients)\n return gradients\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n predictions = self._forward_pass(\n self._model, x_preprocessed, training=training_mode, batch_size=batch_size\n ) # Fast, compiled call\n\n # Apply postprocessing\n predictions_post = self._apply_postprocessing(preds=predictions.numpy(), fit=False)\n\n return predictions_post\n\n def fit(\n self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, verbose: bool = False, **kwargs\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs or the number of steps per epoch as part of this argument will result in as error.\n \"\"\"\n y_ndim = y.ndim\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Adjust the shape of y for loss functions that do not take labels in one-hot encoding\n loss_name = getattr(self._model.loss, \"__name__\", None)\n if loss_name in [\"sparse_categorical_crossentropy\", \"SparseCategoricalCrossentropy\"] or y_ndim == 1:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n self._model.fit(\n x=x_preprocessed, y=y_preprocessed, batch_size=batch_size, epochs=nb_epochs, verbose=int(verbose), **kwargs\n )\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, verbose: bool = False, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch. If the generator can be used for native\n training in Keras, it will.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs as part of this argument will result in as error.\n \"\"\"\n from art.data_generators import KerasDataGenerator\n\n # Try to use the generator as a Keras native generator, otherwise use it through the `DataGenerator` interface\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n\n if isinstance(generator, KerasDataGenerator) and (\n self.preprocessing is None\n or (\n isinstance(self.preprocessing, StandardisationMeanStd)\n and (\n self.preprocessing.mean,\n self.preprocessing.std,\n )\n == (0, 1)\n )\n ):\n try:\n self._model.fit(generator.iterator, epochs=nb_epochs, verbose=int(verbose), **kwargs)\n except ValueError: # pragma: no cover\n logger.info(\"Unable to use data generator as Keras generator. Now treating as framework-independent.\")\n super().fit_generator(generator, nb_epochs=nb_epochs, verbose=verbose, **kwargs)\n else: # pragma: no cover\n super().fit_generator(generator, nb_epochs=nb_epochs, verbose=verbose, **kwargs)\n\n def get_activations(\n self, x: np.ndarray, layer: int | str, batch_size: int = 128, framework: bool = False\n ) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations.\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n import tensorflow as tf\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x=x, y=None, fit=False)\n\n layer_name: str\n\n x_tensor = tf.convert_to_tensor(x_preprocessed)\n if isinstance(layer, int):\n layer_index: int = layer\n layer_name = self._model.layers[layer_index].name\n else:\n layer_name = layer\n layer_instance = self._model.get_layer(name=layer_name)\n submodel = tf.keras.Model(inputs=self._input, outputs=layer_instance.output)\n return submodel.predict(x_tensor)\n\n def custom_loss_gradient(self, nn_function, tensors, input_values, name=\"default\"):\n \"\"\"\n Returns the gradient of the nn_function with respect to model input\n\n :param nn_function: an intermediate tensor representation of the function to differentiate\n :type nn_function: a Keras tensor\n :param tensors: the tensors or variables to differentiate with respect to\n :type tensors: `list`\n :param input_values: the inputs to evaluate the gradient\n :type input_values: `list`\n :param name: The name of the function. Functions of the same name are cached\n :type name: `str`\n :return: the gradient of the function w.r.t vars\n :rtype: `np.ndarray`\n \"\"\"\n with tf.GradientTape() as tape:\n tape.watch(tensors)\n outputs = nn_function(*tensors)\n grads = tape.gradient(outputs, tensors)\n return [g.numpy() for g in grads]\n\n def clone_for_refitting(\n self,\n ) -> \"KerasClassifier\":\n \"\"\"\n Create a copy of the classifier that can be refit from scratch. Will inherit same architecture, optimizer and\n initialization as cloned model, but without weights.\n\n :return: new classifier\n \"\"\"\n import tensorflow as tf\n from tensorflow.keras.metrics import Metric\n\n # Clone model architecture (but not weights)\n cloned_model = tf.keras.models.clone_model(self._model)\n\n filtered_metric_names = [\"accuracy\"]\n\n # Rebuild the optimizer from config, if available\n optimizer_config = None\n if hasattr(self._model, \"optimizer\") and self._model.optimizer:\n optimizer_config = self._model.optimizer.get_config()\n optimizer_class = self._model.optimizer.__class__\n\n # Compile cloned model with a fresh optimizer instance\n if optimizer_config:\n new_optimizer = optimizer_class.from_config(optimizer_config)\n cloned_model.compile(\n optimizer=new_optimizer,\n loss=tf.keras.losses.get(self._model.loss),\n metrics=filtered_metric_names,\n run_eagerly=getattr(self._model, \"run_eagerly\", False), # Copy run_eagerly if it was set\n )\n else:\n # If no optimizer, compile without one\n cloned_model.compile(\n loss=tf.keras.losses.get(self._model.loss),\n metrics=filtered_metric_names,\n )\n\n # Return a new KerasClassifier instance with the cloned model\n return KerasClassifier(\n model=cloned_model,\n use_logits=self._use_logits,\n channels_first=self.channels_first,\n clip_values=self.clip_values,\n # Add other attributes as needed (e.g., preprocessing_defences)\n )\n\n def _get_layers(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n \"\"\"\n from tensorflow.keras.layers import InputLayer\n\n layer_names = [layer.name for layer in self._model.layers[:-1] if not isinstance(layer, InputLayer)]\n logger.info(\"Inferred %i hidden layers on Keras classifier.\", len(layer_names))\n\n return layer_names\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. For Keras, .h5 format is used.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n self._model.save(str(full_path))\n logger.info(\"Model saved in path: %s.\", full_path)\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(model={self._model}, use_logits={self._use_logits}, \"\n f\"channels_first={self.channels_first}, clip_values={self.clip_values!r}, \"\n f\"preprocessing_defences={self.preprocessing_defences}, \"\n f\"postprocessing_defences={self.postprocessing_defences}, preprocessing={self.preprocessing}, \"\n f\"input_layer={self._input_layer}, output_layer={self._output_layer})\"\n )\n\n return repr_\n\n\ndef generator_fit(\n x: np.ndarray, y: np.ndarray, batch_size: int = 128\n) -> Iterator[tuple[np.ndarray, np.ndarray]]: # pragma: no cover\n \"\"\"\n Minimal data generator for randomly batching large datasets.\n\n :param x: The data sample to batch.\n :param y: The labels for `x`. The first dimension has to match the first dimension of `x`.\n :param batch_size: The size of the batches to produce.\n :return: A batch of size `batch_size` of random samples from `(x, y)`.\n \"\"\"\n while True:\n indices = np.random.randint(x.shape[0], size=batch_size)\n yield x[indices], y[indices]\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/lightgbm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `LightGBMClassifier` for LightGBM models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom copy import deepcopy\nimport logging\nimport os\nimport pickle\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierDecisionTree\nfrom art import config\n\nif TYPE_CHECKING:\n\n import lightgbm\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n from art.metrics.verification_decisions_trees import LeafNode\n\nlogger = logging.getLogger(__name__)\n\n\nclass LightGBMClassifier(ClassifierDecisionTree):\n \"\"\"\n Class for importing LightGBM models.\n \"\"\"\n\n def __init__(\n self,\n model: \"lightgbm.Booster\" | None = None, # type: ignore\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a LightGBM model.\n\n :param model: LightGBM model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n from lightgbm import Booster # type: ignore\n\n if not isinstance(model, Booster): # pragma: no cover\n raise TypeError(\"Model must be of type lightgbm.Booster\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n self._input_shape = (self._model.num_feature(),)\n self.nb_classes = self._get_nb_classes()\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit` function in `lightgbm.Booster` and will be passed to this function as such.\n :raises `NotImplementedException`: This method is not supported for LightGBM classifiers.\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Perform prediction\n predictions = self._model.predict(x_preprocessed)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=predictions, fit=False)\n\n return predictions\n\n def _get_nb_classes(self) -> int:\n \"\"\"\n Return the number of output classes.\n\n :return: Number of classes in the data.\n \"\"\"\n\n return self._model._Booster__num_class\n\n def save(self, filename: str, path: str | None = None) -> None: # pragma: no cover\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n with open(full_path + \".pickle\", \"wb\") as file_pickle:\n pickle.dump(self._model, file=file_pickle)\n\n def get_trees(self) -> list:\n \"\"\"\n Get the decision trees.\n\n :return: A list of decision trees.\n \"\"\"\n from art.metrics.verification_decisions_trees import Box, Tree\n\n booster_dump = self._model.dump_model()[\"tree_info\"]\n trees = []\n\n for i_tree, tree_dump in enumerate(booster_dump):\n box = Box()\n\n if self._model._Booster__num_class == 2:\n class_label = -1\n else:\n class_label = i_tree % self._model._Booster__num_class\n\n trees.append(\n Tree(\n class_id=class_label,\n leaf_nodes=self._get_leaf_nodes(tree_dump[\"tree_structure\"], i_tree, class_label, box),\n )\n )\n\n return trees\n\n def _get_leaf_nodes(self, node, i_tree, class_label, box) -> list[\"LeafNode\"]:\n from art.metrics.verification_decisions_trees import Box, Interval, LeafNode\n\n leaf_nodes: list[LeafNode] = []\n\n if \"split_index\" in node:\n node_left = node[\"left_child\"]\n node_right = node[\"right_child\"]\n\n box_left = deepcopy(box)\n box_right = deepcopy(box)\n\n feature = node[\"split_feature\"]\n box_split_left = Box(intervals={feature: Interval(-np.inf, node[\"threshold\"])})\n box_split_right = Box(intervals={feature: Interval(node[\"threshold\"], np.inf)})\n\n if box.intervals:\n box_left.intersect_with_box(box_split_left)\n box_right.intersect_with_box(box_split_right)\n else:\n box_left = box_split_left\n box_right = box_split_right\n\n leaf_nodes += self._get_leaf_nodes(node_left, i_tree, class_label, box_left)\n leaf_nodes += self._get_leaf_nodes(node_right, i_tree, class_label, box_right)\n\n if \"leaf_index\" in node:\n leaf_nodes.append(\n LeafNode(\n tree_id=i_tree,\n class_label=class_label,\n node_id=node[\"leaf_index\"],\n box=box,\n value=node[\"leaf_value\"],\n )\n )\n\n return leaf_nodes\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `PyTorchClassifier` for PyTorch models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport copy\nimport logging\nimport os\nimport time\nfrom typing import Any, TYPE_CHECKING\nfrom tqdm.auto import tqdm\n\nimport numpy as np\nimport six\n\nfrom art import config\nfrom art.estimators.classification.classifier import (\n ClassGradientsMixin,\n ClassifierMixin,\n)\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchClassifier(ClassGradientsMixin, ClassifierMixin, PyTorchEstimator):\n \"\"\"\n This class implements a classifier with the PyTorch framework.\n \"\"\"\n\n estimator_params = (\n PyTorchEstimator.estimator_params\n + ClassifierMixin.estimator_params\n + [\n \"loss\",\n \"input_shape\",\n \"optimizer\",\n \"use_amp\",\n \"opt_level\",\n \"loss_scale\",\n ]\n )\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n nb_classes: int,\n optimizer: \"torch.optim.Optimizer\" | None = None, # type: ignore\n use_amp: bool = False,\n opt_level: str = \"O1\",\n loss_scale: float | str | None = \"dynamic\",\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n ) -> None:\n \"\"\"\n Initialization specifically for the PyTorch-based implementation.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param optimizer: The optimizer used to train the classifier.\n :param use_amp: Whether to use the automatic mixed precision tool to enable mixed precision training or\n gradient computation, e.g. with loss gradient computation. When set to True, this option is\n only triggered if there are GPUs available.\n :param opt_level: Specify a pure or mixed precision optimization level. Used when use_amp is True. Accepted\n values are `O0`, `O1`, `O2`, and `O3`.\n :param loss_scale: Loss scaling. Used when use_amp is True. If passed as a string, must be a string\n representing a number, e.g., \u201c1.0\u201d, or the string \u201cdynamic\u201d.\n :param nb_classes: The number of classes of the model.\n :param optimizer: The optimizer used to train the classifier.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n import torch\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n self.nb_classes = nb_classes\n self._input_shape = input_shape\n self._model = self._make_model_wrapper(model)\n self._loss = loss\n self._optimizer = optimizer\n self._use_amp = use_amp\n self._learning_phase: bool | None = None\n self._opt_level = opt_level\n self._loss_scale = loss_scale\n\n # Check if model is RNN-like to decide if freezing batch-norm and dropout layers might be required for loss and\n # class gradient calculation\n self.is_rnn = any((isinstance(m, torch.nn.modules.RNNBase) for m in self._model.modules()))\n\n # Get the internal layers\n self._layer_names: list[str] = self._model.get_layers # type: ignore\n\n self._model.to(self._device)\n\n # Index of layer at which the class gradients should be calculated\n self._layer_idx_gradients = -1\n\n if isinstance(self._loss, torch.nn.CrossEntropyLoss):\n self._reduce_labels = True\n self._int_labels = True\n self._probability_labels = True\n elif isinstance(self._loss, (torch.nn.NLLLoss, torch.nn.MultiMarginLoss)):\n self._reduce_labels = True\n self._int_labels = True\n self._probability_labels = False\n elif isinstance(self._loss, (torch.nn.BCELoss, torch.nn.BCEWithLogitsLoss)):\n self._reduce_labels = True\n self._int_labels = False\n self._probability_labels = False\n else:\n self._reduce_labels = False\n self._int_labels = False\n self._probability_labels = False\n\n # Setup for AMP use\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n if self._optimizer is None:\n logger.warning(\n \"An optimizer is needed to use the automatic mixed precision tool, but none for provided. \"\n \"A default optimizer is used.\"\n )\n\n # Create the optimizers\n parameters = self._model.parameters()\n self._optimizer = torch.optim.SGD(parameters, lr=0.01)\n\n if self.device.type == \"cpu\":\n enabled = False\n else:\n enabled = True\n\n self._model, self._optimizer = amp.initialize(\n models=self._model,\n optimizers=self._optimizer,\n enabled=enabled,\n opt_level=opt_level,\n loss_scale=loss_scale,\n )\n\n @property\n def device(self) -> \"torch.device\":\n \"\"\"\n Get current used device.\n\n :return: Current used device.\n \"\"\"\n return self._device\n\n @property\n def model(self) -> \"torch.nn.Module\":\n return self._model._model\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def loss(self) -> \"torch.nn.modules.loss._Loss\":\n \"\"\"\n Return the loss function.\n\n :return: The loss function.\n \"\"\"\n return self._loss # type: ignore\n\n @property\n def optimizer(self) -> \"torch.optim.Optimizer\":\n \"\"\"\n Return the optimizer.\n\n :return: The optimizer.\n \"\"\"\n return self._optimizer # type: ignore\n\n @property\n def use_amp(self) -> bool:\n \"\"\"\n Return a boolean indicating whether to use the automatic mixed precision tool.\n\n :return: Whether to use the automatic mixed precision tool.\n \"\"\"\n return self._use_amp # type: ignore\n\n @property\n def opt_level(self) -> str:\n \"\"\"\n Return a string specifying a pure or mixed precision optimization level.\n\n :return: A string specifying a pure or mixed precision optimization level. Possible\n values are `O0`, `O1`, `O2`, and `O3`.\n \"\"\"\n return self._opt_level # type: ignore\n\n @property\n def loss_scale(self) -> float | str:\n \"\"\"\n Return the loss scaling value.\n\n :return: Loss scaling. Possible values for string: a string representing a number, e.g., \u201c1.0\u201d,\n or the string \u201cdynamic\u201d.\n \"\"\"\n return self._loss_scale # type: ignore\n\n def reduce_labels(self, y: np.ndarray | \"torch.Tensor\") -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Reduce labels from one-hot encoded to index labels.\n \"\"\"\n\n import torch\n\n # Check if the loss function supports probability labels and probability labels are provided\n if self._probability_labels and len(y.shape) == 2:\n if isinstance(y, torch.Tensor):\n is_one_hot = torch.equal(y.float().floor(), y.float().ceil())\n else:\n is_one_hot = np.array_equal(np.floor(y), np.ceil(y))\n if not is_one_hot: # probability labels\n return y\n\n # Check if the loss function requires as input index labels instead of one-hot-encoded labels\n # Checking for exactly 2 classes to support binary classification\n if self.nb_classes > 2 or (self.nb_classes == 2 and len(y.shape) == 2 and y.shape[1] == 2):\n if self._reduce_labels and self._int_labels:\n if isinstance(y, torch.Tensor):\n return torch.argmax(y, dim=1)\n return np.argmax(y, axis=1)\n if self._reduce_labels: # float labels\n if isinstance(y, torch.Tensor):\n return torch.argmax(y, dim=1).float()\n y_index = np.argmax(y, axis=1).astype(np.float32)\n y_index = np.expand_dims(y_index, axis=1)\n return y_index\n return y\n\n if isinstance(y, torch.Tensor):\n return y.float()\n return y.astype(np.float32)\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n dataset = TensorDataset(x_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=False)\n\n results_list = []\n for (x_batch,) in dataloader:\n # Move inputs to device\n x_batch = x_batch.to(self._device)\n\n # Run prediction\n with torch.no_grad():\n model_outputs = self._model(x_batch)\n output = model_outputs[-1]\n output = output.detach().cpu().numpy().astype(np.float32)\n if len(output.shape) == 1:\n output = np.expand_dims(output, axis=1).astype(np.float32)\n\n results_list.append(output)\n\n results = np.vstack(results_list)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=results, fit=False)\n\n return predictions\n\n def _predict_framework(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :return: Tensor of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y=y, fit=False, no_grad=False)\n\n # Put the model in the eval mode\n self._model.eval()\n\n model_outputs = self._model(x_preprocessed)\n output = model_outputs[-1]\n\n return output, y_preprocessed\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param verbose: Display training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n y_tensor = torch.from_numpy(y_preprocessed)\n dataset = TensorDataset(x_tensor, y_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)\n\n # Start training\n for _ in tqdm(range(nb_epochs), disable=not verbose, desc=\"Epochs\"):\n for x_batch, y_batch in dataloader:\n # Move inputs to device\n x_batch = x_batch.to(self._device)\n y_batch = y_batch.to(self._device)\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Perform prediction\n try:\n model_outputs = self._model(x_batch)\n except ValueError as err:\n if \"Expected more than 1 value per channel when training\" in str(err):\n logger.exception(\n \"Try dropping the last incomplete batch by setting drop_last=True in \"\n \"method PyTorchClassifier.fit.\"\n )\n raise err\n\n # Form the loss function\n loss = self._loss(model_outputs[-1], y_batch)\n\n # Do training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n self._optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, verbose: bool = False, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display the training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from art.data_generators import PyTorchDataGenerator\n\n # Put the model in the training mode\n self._model.train()\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n # Train directly in PyTorch\n from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n if isinstance(generator, PyTorchDataGenerator) and (\n self.preprocessing is None\n or (\n isinstance(self.preprocessing, StandardisationMeanStdPyTorch)\n and (\n self.preprocessing.mean,\n self.preprocessing.std,\n )\n == (0, 1)\n )\n ):\n for _ in tqdm(range(nb_epochs), disable=not verbose, desc=\"Epochs\"):\n for i_batch, o_batch in generator.iterator:\n if isinstance(i_batch, np.ndarray):\n i_batch = torch.from_numpy(i_batch).to(self._device)\n else:\n i_batch = i_batch.to(self._device)\n\n if isinstance(o_batch, np.ndarray):\n o_batch = torch.argmax(torch.from_numpy(o_batch).to(self._device), dim=1)\n else:\n o_batch = torch.argmax(o_batch.to(self._device), dim=1)\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Perform prediction\n model_outputs = self._model(i_batch)\n\n # Form the loss function\n loss = self._loss(model_outputs[-1], o_batch)\n\n # Do training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self._optimizer.step()\n\n else:\n # Fit a generic data generator through the API\n super().fit_generator(generator, nb_epochs=nb_epochs)\n\n def clone_for_refitting(self) -> \"PyTorchClassifier\":\n \"\"\"\n Create a copy of the classifier that can be refit from scratch. Will inherit same architecture, same type of\n optimizer and initialization as the original classifier, but without weights.\n\n :return: new estimator\n \"\"\"\n model = copy.deepcopy(self.model)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none is provided.\")\n\n # create a new optimizer that binds to the cloned model's parameters and uses original optimizer's defaults\n new_optimizer = type(self._optimizer)(model.parameters(), **self._optimizer.defaults) # type: ignore\n\n clone = type(self)(model, self._loss, self.input_shape, self.nb_classes, optimizer=new_optimizer)\n\n # reset weights\n clone.reset()\n params = self.get_params()\n del params[\"model\"]\n del params[\"optimizer\"]\n clone.set_params(**params)\n return clone\n\n def reset(self) -> None:\n \"\"\"\n Resets the weights of the classifier so that it can be refit from scratch.\n\n \"\"\"\n\n def weight_reset(module):\n reset_parameters = getattr(module, \"reset_parameters\", None)\n if reset_parameters and callable(reset_parameters):\n module.reset_parameters()\n\n self.model.apply(weight_reset)\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n Note on RNN-like models: Backpropagation through RNN modules in eval mode raises\n RuntimeError due to cudnn issues and require training mode, i.e. RuntimeError: cudnn RNN\n backward can only be called in training mode. Therefore, if the model is an RNN type we\n always use training mode but freeze batch-norm and dropout layers if\n `training_mode=False.`\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n import torch\n\n self._model.train(mode=training_mode)\n\n # Backpropagation through RNN modules in eval mode raises RuntimeError due to cudnn issues and require training\n # mode, i.e. RuntimeError: cudnn RNN backward can only be called in training mode. Therefore, if the model is\n # an RNN type we always use training mode but freeze batch-norm and dropout layers if training_mode=False.\n if self.is_rnn:\n self._model.train(mode=True)\n if not training_mode:\n logger.debug( # pragma: no cover\n \"Freezing batch-norm and dropout layers for gradient calculation in train mode with eval parameters\"\n \"of batch-norm and dropout.\"\n )\n self.set_batchnorm(train=False)\n self.set_dropout(train=False)\n\n if isinstance(label, list):\n label = np.array(label)\n if not (\n (label is None)\n or (isinstance(label, (int, np.integer)) and label in range(self.nb_classes))\n or (\n isinstance(label, np.ndarray)\n and len(label.shape) == 1\n and (label < self.nb_classes).all()\n and label.shape[0] == x.shape[0]\n )\n ):\n raise ValueError(f\"Label {label} is out of range.\") # pragma: no cover\n\n # Apply preprocessing\n if self.all_framework_preprocessing:\n x_grad = torch.from_numpy(x).to(self._device)\n if self._layer_idx_gradients < 0:\n x_grad.requires_grad = True\n x_input, _ = self._apply_preprocessing(x_grad, y=None, fit=False, no_grad=False)\n else:\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False, no_grad=True)\n x_grad = torch.from_numpy(x_preprocessed).to(self._device)\n if self._layer_idx_gradients < 0:\n x_grad.requires_grad = True\n x_input = x_grad\n\n # Run prediction\n model_outputs = self._model(x_input)\n\n # Set where to get gradient\n if self._layer_idx_gradients >= 0:\n input_grad = model_outputs[self._layer_idx_gradients]\n else:\n input_grad = x_grad\n\n # Set where to get gradient from\n preds = model_outputs[-1]\n\n # Compute the gradient\n grads_list = []\n\n def save_grad():\n def hook(grad):\n grads_list.append(grad.cpu().numpy().copy())\n grad.data.zero_()\n\n return hook\n\n input_grad.register_hook(save_grad())\n\n self._model.zero_grad()\n if label is None:\n if len(preds.shape) == 1 or preds.shape[1] == 1:\n num_outputs = 1\n else:\n num_outputs = self.nb_classes\n\n for i in range(num_outputs):\n torch.autograd.backward(\n preds[:, i],\n torch.tensor([1.0] * len(preds[:, 0])).to(self._device),\n retain_graph=True,\n )\n\n grads = np.swapaxes(np.array(grads_list), 0, 1)\n\n elif isinstance(label, (int, np.integer)):\n torch.autograd.backward(\n preds[:, label],\n torch.tensor([1.0] * len(preds[:, 0])).to(self._device),\n retain_graph=True,\n )\n grads = np.swapaxes(np.array(grads_list), 0, 1)\n else:\n unique_label = list(np.unique(label))\n for i in unique_label:\n torch.autograd.backward(\n preds[:, i],\n torch.tensor([1.0] * len(preds[:, 0])).to(self._device),\n retain_graph=True,\n )\n\n grads = np.swapaxes(np.array(grads_list), 0, 1)\n lst = [unique_label.index(i) for i in label]\n grads = grads[np.arange(len(grads)), lst]\n\n grads = grads[None, ...]\n grads = np.swapaxes(np.array(grads), 0, 1)\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n return grads\n\n def compute_loss( # type: ignore\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n reduction: str = \"none\",\n **kwargs,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the loss.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Array of losses of the same shape as `x`.\n \"\"\"\n import torch\n\n self._model.eval()\n\n y = check_and_transform_label_format(y, self.nb_classes) # type: ignore\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n if isinstance(x, torch.Tensor):\n inputs_t = x_preprocessed\n labels_t = y_preprocessed\n else:\n # Convert the inputs to Tensors\n inputs_t = torch.from_numpy(x_preprocessed).to(self._device)\n # Convert the labels to Tensors\n labels_t = torch.from_numpy(y_preprocessed).to(self._device)\n\n # Compute the loss and return\n model_outputs = self._model(inputs_t)\n prev_reduction = self._loss.reduction\n\n # Return individual loss values\n self._loss.reduction = reduction\n loss = self._loss(model_outputs[-1], labels_t)\n self._loss.reduction = prev_reduction\n\n if isinstance(x, torch.Tensor):\n return loss\n\n return loss.detach().cpu().numpy()\n\n def compute_losses(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n reduction: str = \"none\",\n ) -> dict[str, np.ndarray | \"torch.Tensor\"]:\n \"\"\"\n Compute all loss components.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Dictionary of loss components.\n \"\"\"\n return {\"total\": self.compute_loss(x=x, y=y, reduction=reduction)}\n\n def loss_gradient(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n Note on RNN-like models: Backpropagation through RNN modules in eval mode raises\n RuntimeError due to cudnn issues and require training mode, i.e. RuntimeError: cudnn RNN\n backward can only be called in training mode. Therefore, if the model is an RNN type we\n always use training mode but freeze batch-norm and dropout layers if\n `training_mode=False.`\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import torch\n\n self._model.train(mode=training_mode)\n\n # Backpropagation through RNN modules in eval mode raises RuntimeError due to cudnn issues and require training\n # mode, i.e. RuntimeError: cudnn RNN backward can only be called in training mode. Therefore, if the model is\n # an RNN type we always use training mode but freeze batch-norm and dropout layers if training_mode=False.\n if self.is_rnn:\n self._model.train(mode=True)\n if not training_mode:\n logger.debug(\n \"Freezing batch-norm and dropout layers for gradient calculation in train mode with eval parameters\"\n \"of batch-norm and dropout.\"\n )\n self.set_batchnorm(train=False)\n self.set_dropout(train=False)\n\n # Apply preprocessing\n if self.all_framework_preprocessing:\n if isinstance(x, torch.Tensor):\n x_grad = x.clone().detach().requires_grad_(True)\n else:\n x_grad = torch.tensor(x).to(self._device)\n x_grad.requires_grad = True\n if isinstance(y, torch.Tensor):\n y_grad = y.clone().detach()\n else:\n y_grad = torch.tensor(y).to(self._device)\n inputs_t, y_preprocessed = self._apply_preprocessing(x_grad, y=y_grad, fit=False, no_grad=False)\n elif isinstance(x, np.ndarray):\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y=y, fit=False, no_grad=True)\n x_grad = torch.from_numpy(x_preprocessed).to(self._device)\n x_grad.requires_grad = True\n inputs_t = x_grad\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n # Check label shape\n y_preprocessed = self.reduce_labels(y_preprocessed)\n\n if isinstance(y_preprocessed, np.ndarray):\n labels_t = torch.from_numpy(y_preprocessed).to(self._device)\n else:\n labels_t = y_preprocessed\n\n # Compute the gradient and return\n model_outputs = self._model(inputs_t)\n loss = self._loss(model_outputs[-1], labels_t)\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n grads: torch.Tensor | np.ndarray\n\n if x_grad.grad is not None:\n if isinstance(x, torch.Tensor):\n grads = x_grad.grad\n else:\n grads = x_grad.grad.cpu().numpy().copy()\n else:\n raise ValueError(\"Gradient term in PyTorch model is `None`.\")\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n assert grads.shape == x.shape\n\n return grads\n\n def custom_loss_gradient(\n self,\n loss_fn,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n layer_name,\n training_mode: bool = False,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param loss_fn: Loss function w.r.t to which gradient needs to be calculated.\n :param x: Sample input with shape as expected by the model(base image).\n :param y: Sample input with shape as expected by the model(target image).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.`\n :param layer_name: Name of the layer from which activation needs to be extracted/activation layer.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import torch\n\n self._model.train(mode=training_mode)\n self._model.eval()\n if self.all_framework_preprocessing:\n if isinstance(x, torch.Tensor):\n x_grad = x.clone().detach().requires_grad_(True)\n else:\n x_grad = torch.tensor(x).to(self._device)\n x_grad.requires_grad = True\n if isinstance(y, torch.Tensor):\n y_grad = y.clone().detach()\n else:\n y_grad = torch.tensor(y).to(self._device)\n inputs_t, _ = self._apply_preprocessing(x_grad, y=None, fit=False, no_grad=False)\n targets_t, _ = self._apply_preprocessing(y_grad, y=None, fit=False, no_grad=False)\n if isinstance(x, np.ndarray):\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False, no_grad=True)\n y_preprocessed, _ = self._apply_preprocessing(y, y=None, fit=False, no_grad=True)\n x_grad = torch.from_numpy(x_preprocessed).to(self._device)\n y_grad = torch.from_numpy(y_preprocessed).to(self._device)\n x_grad.requires_grad = True\n y_grad.requires_grad = False\n inputs_t = x_grad\n targets_t = y_grad\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n # Compute the gradient and return\n model_outputs1 = self.get_activations(inputs_t, layer_name, 1, framework=True)\n model_outputs2 = self.get_activations(targets_t, layer_name, 1, framework=True)\n diff = model_outputs1 - model_outputs2\n loss = loss_fn(diff, p=2)\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n if isinstance(x, torch.Tensor):\n grads = x_grad.grad\n else:\n grads = x_grad.grad.cpu().numpy().copy() # type: ignore\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n assert grads.shape == x.shape\n\n return grads\n\n def get_activations( # type: ignore\n self,\n x: np.ndarray | \"torch.Tensor\",\n layer: int | str | None = None,\n batch_size: int = 128,\n framework: bool = False,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n import torch\n\n self._model.eval()\n\n # Apply defences\n if framework:\n no_grad = False\n else:\n no_grad = True\n x_preprocessed, _ = self._apply_preprocessing(x=x, y=None, fit=False, no_grad=no_grad)\n\n # Get index of the extracted layer\n if isinstance(layer, six.string_types):\n if layer not in self._layer_names: # pragma: no cover\n raise ValueError(f\"Layer name {layer} not supported\")\n layer_index = self._layer_names.index(layer)\n\n elif isinstance(layer, int):\n layer_index = layer\n\n else: # pragma: no cover\n raise TypeError(\"Layer must be of type str or int\")\n\n def get_feature(name):\n # the hook signature\n def hook(model, input, output): # pylint: disable=redefined-builtin,unused-argument\n self._features[name] = output\n\n return hook\n\n if not hasattr(self, \"_features\"):\n self._features: dict[str, torch.Tensor] = {}\n # register forward hooks on the layers of choice\n\n if layer not in self._features:\n interim_layer = dict([*self._model._model.named_modules()])[self._layer_names[layer_index]]\n interim_layer.register_forward_hook(get_feature(self._layer_names[layer_index]))\n\n if framework:\n if isinstance(x_preprocessed, torch.Tensor):\n self._model(x_preprocessed)\n return self._features[self._layer_names[layer_index]]\n input_tensor = torch.from_numpy(x_preprocessed)\n self._model(input_tensor.to(self._device))\n return self._features[self._layer_names[layer_index]]\n\n # Run prediction with batch processing\n results = []\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Run prediction for the current batch\n self._model(torch.from_numpy(x_preprocessed[begin:end]).to(self._device))\n layer_output = self._features[self._layer_names[layer_index]]\n results.append(layer_output.detach().cpu().numpy())\n\n results_array = np.concatenate(results)\n\n return results_array\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n import torch\n\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # disable pylint because access to _modules required\n torch.save(self._model._model.state_dict(), full_path + \".model\")\n if self._optimizer is not None:\n torch.save(self._optimizer.state_dict(), full_path + \".optimizer\") # type: ignore\n logger.info(\"Optimizer state dict saved in path: %s.\", full_path + \".optimizer\")\n logger.info(\"Model state dict saved in path: %s.\", full_path + \".model\")\n\n def __getstate__(self) -> dict[str, Any]:\n \"\"\"\n Use to ensure `PyTorchClassifier` can be pickled.\n\n :return: State dictionary with instance parameters.\n \"\"\"\n\n # disable pylint because access to _model required\n state = self.__dict__.copy()\n state[\"inner_model\"] = copy.copy(state[\"_model\"]._model)\n\n # Remove the unpicklable entries\n del state[\"_model_wrapper\"]\n del state[\"_device\"]\n del state[\"_model\"]\n\n model_name = str(time.time())\n state[\"model_name\"] = model_name\n self.save(model_name)\n\n return state\n\n def __setstate__(self, state: dict[str, Any]) -> None:\n \"\"\"\n Use to ensure `PyTorchClassifier` can be unpickled.\n\n :param state: State dictionary with instance parameters to restore.\n \"\"\"\n import torch\n\n # Recover model\n self.__dict__.update(state)\n full_path = os.path.join(config.ART_DATA_PATH, state[\"model_name\"])\n model = state[\"inner_model\"]\n model.load_state_dict(torch.load(str(full_path) + \".model\"))\n model.eval()\n self._model = self._make_model_wrapper(model)\n\n # Recover device\n self._device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self._model.to(self._device)\n\n # Recover optimizer\n if os.path.isfile(str(full_path) + \".optimizer\"):\n self._optimizer.load_state_dict(torch.load(str(full_path) + \".optimizer\")) # type: ignore\n\n self.__dict__.pop(\"model_name\", None)\n self.__dict__.pop(\"inner_model\", None)\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(model={self._model}, loss={self._loss}, \"\n f\"optimizer={self._optimizer}, input_shape={self._input_shape}, nb_classes={self.nb_classes}, \"\n f\"channels_first={self.channels_first}, clip_values={self.clip_values!r}, \"\n f\"preprocessing_defences={self.preprocessing_defences}, \"\n f\"postprocessing_defences={self.postprocessing_defences}, preprocessing={self.preprocessing})\"\n )\n\n return repr_\n\n def _make_model_wrapper(self, model: \"torch.nn.Module\") -> \"torch.nn.Module\":\n # Try to import PyTorch and create an internal class that acts like a model wrapper extending torch.nn.Module\n try:\n import torch\n\n # Define model wrapping class only if not defined before\n if not hasattr(self, \"_model_wrapper\"):\n\n class ModelWrapper(torch.nn.Module):\n \"\"\"\n This is a wrapper for the input model.\n \"\"\"\n\n import torch\n\n def __init__(self, model: torch.nn.Module):\n \"\"\"\n Initialization by storing the input model.\n\n :param model: PyTorch model. The forward function of the model must return the logit output.\n \"\"\"\n super().__init__()\n self._model = model\n\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n This is where we get outputs from the input model.\n\n :param x: Input data.\n :type x: `torch.Tensor`\n :return: a list of output layers, where the last 2 layers are logit and final outputs.\n :rtype: `list`\n \"\"\"\n\n # disable pylint because access to _model required\n\n result = []\n if isinstance(self._model, torch.nn.Sequential):\n for _, module_ in self._model._modules.items():\n x = module_(x)\n result.append(x)\n\n elif isinstance(self._model, torch.nn.Module):\n x = self._model(x)\n result.append(x)\n\n else: # pragma: no cover\n raise TypeError(\"The input model must inherit from `nn.Module`.\")\n\n return result\n\n @property\n def get_layers(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n\n .. warning:: `get_layers` tries to infer the internal structure of the model.\n This feature comes with no guarantees on the correctness of the result.\n The intended order of the layers tries to match their order in the model, but this\n is not guaranteed either. In addition, the function can only infer the internal\n layers if the input model is of type `nn.Sequential`, otherwise, it will only\n return the logit layer.\n \"\"\"\n import torch\n\n result = []\n if isinstance(self._model, torch.nn.Module):\n for name, _ in self._model._modules.items():\n result.append(name)\n\n else: # pragma: no cover\n raise TypeError(\"The input model must inherit from `nn.Module`.\")\n logger.info(\n \"Inferred %i hidden layers on PyTorch classifier.\",\n len(result),\n )\n\n return result\n\n # Set newly created class as private attribute\n self._model_wrapper = ModelWrapper\n\n # Use model wrapping class to wrap the PyTorch model received as argument\n return self._model_wrapper(model)\n\n except ImportError: # pragma: no cover\n raise ImportError(\"Could not find PyTorch (`torch`) installation.\") from ImportError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/query_efficient_bb.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nProvides black-box gradient estimation using NES.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom scipy.stats import entropy\n\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin, ClassifierLossGradients\nfrom art.utils import clip_and_round\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass QueryEfficientGradientEstimationClassifier(ClassifierLossGradients, ClassifierMixin, BaseEstimator):\n \"\"\"\n Implementation of Query-Efficient Black-box Adversarial Examples. The attack approximates the gradient by\n maximizing the loss function over samples drawn from random Gaussian noise around the input.\n\n | Paper link: https://arxiv.org/abs/1712.07113\n \"\"\"\n\n estimator_params = [\"num_basis\", \"sigma\", \"round_samples\"]\n\n def __init__(\n self,\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n num_basis: int,\n sigma: float,\n round_samples: float = 0.0,\n ) -> None:\n \"\"\"\n :param classifier: An instance of a classification estimator whose loss_gradient is being approximated.\n :param num_basis: The number of samples to draw to approximate the gradient.\n :param sigma: Scaling on the Gaussian noise N(0,1).\n :param round_samples: The resolution of the input domain to round the data to, e.g., 1.0, or 1/255. Set to 0 to\n disable.\n \"\"\"\n super().__init__(model=classifier.model, clip_values=classifier.clip_values)\n self._classifier = classifier\n self.num_basis = num_basis\n self.sigma = sigma\n self.round_samples = round_samples\n self._nb_classes = self._classifier.nb_classes\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._classifier.input_shape # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction of the classifier for input `x`. Rounds results first.\n\n :param x: Features in array of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param batch_size: Size of batches.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n return self._classifier.predict(clip_and_round(x, self.clip_values, self.round_samples), batch_size=batch_size)\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the training data `(x, y)`.\n\n :param x: Features in array of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels in classification) in array of shape (nb_samples, nb_classes) in\n one-hot encoding format.\n :param kwargs: Dictionary of framework-specific arguments.\n \"\"\"\n raise NotImplementedError\n\n def _generate_samples(self, x: np.ndarray, epsilon_map: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generate samples around the current image.\n\n :param x: Sample input with shape as expected by the model.\n :param epsilon_map: Samples drawn from search space.\n :return: Two arrays of new input samples to approximate gradient.\n \"\"\"\n minus = clip_and_round(\n np.repeat(x, self.num_basis, axis=0) - epsilon_map,\n self.clip_values,\n self.round_samples,\n )\n plus = clip_and_round(\n np.repeat(x, self.num_basis, axis=0) + epsilon_map,\n self.clip_values,\n self.round_samples,\n )\n return minus, plus\n\n def class_gradient(self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Input with shape as expected by the classifier's model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n raise NotImplementedError\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Correct labels, one-vs-rest encoding.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n epsilon_map = self.sigma * np.random.normal(size=([self.num_basis] + list(self.input_shape)))\n grads = []\n for i in range(len(x)):\n minus, plus = self._generate_samples(x[i : i + 1], epsilon_map)\n\n # Vectorized; small tests weren't faster\n # ent_vec = np.vectorize(lambda p: entropy(y[i], p), signature='(n)->()')\n # new_y_minus = ent_vec(self.predict(minus))\n # new_y_plus = ent_vec(self.predict(plus))\n # Vanilla\n new_y_minus = np.array([entropy(y[i], p) for p in self.predict(minus)])\n new_y_plus = np.array([entropy(y[i], p) for p in self.predict(plus)])\n query_efficient_grad = 2 * np.mean(\n np.multiply(\n epsilon_map.reshape(self.num_basis, -1),\n (new_y_plus - new_y_minus).reshape(self.num_basis, -1) / (2 * self.sigma),\n ).reshape([-1] + list(self.input_shape)),\n axis=0,\n )\n grads.append(query_efficient_grad)\n grads_array = self._apply_preprocessing_gradient(x, np.array(grads))\n return grads_array\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations.\n :param batch_size: Size of batches.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file specific to the backend framework.\n\n :param filename: Name of the file where to save the model.\n :param path: Path of the directory where to save the model. If no path is specified, the model will be stored in\n the default data location of ART at `ART_DATA_PATH`.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/scikitlearn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifiers for scikit-learn models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nfrom copy import deepcopy\nimport importlib\nimport logging\nimport os\nimport pickle\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.estimator import DecisionTreeMixin, LossGradientsMixin\nfrom art.estimators.classification.classifier import (\n ClassGradientsMixin,\n ClassifierMixin,\n)\nfrom art.estimators.regression.scikitlearn import ScikitlearnDecisionTreeRegressor\nfrom art.estimators.scikitlearn import ScikitlearnEstimator\nfrom art.utils import to_categorical\nfrom art import config\n\nif TYPE_CHECKING:\n\n import sklearn\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n from art.metrics.verification_decisions_trees import LeafNode, Tree\n\nlogger = logging.getLogger(__name__)\n\n\n# pylint: disable=invalid-name\ndef SklearnClassifier(\n model: \"sklearn.base.BaseEstimator\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n use_logits: bool = False,\n) -> \"ScikitlearnClassifier\":\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Classifier model. This is a convenience function that\n instantiates the correct class for the given scikit-learn model.\n\n :param model: scikit-learn Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n if model.__class__.__module__.split(\".\")[0] != \"sklearn\": # pragma: no cover\n raise TypeError(f\"Model is not an sklearn model. Received '{model.__class__}'\")\n\n sklearn_name = model.__class__.__name__\n module = importlib.import_module(\"art.estimators.classification.scikitlearn\")\n if hasattr(module, f\"Scikitlearn{sklearn_name}\"):\n return getattr(module, f\"Scikitlearn{sklearn_name}\")(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n # This basic class at least generically handles `fit`, `predict` and `save`\n return ScikitlearnClassifier(\n model,\n clip_values,\n preprocessing_defences,\n postprocessing_defences,\n preprocessing,\n use_logits,\n )\n\n\nclass ScikitlearnClassifier(ClassifierMixin, ScikitlearnEstimator):\n \"\"\"\n Class for scikit-learn classifier models.\n \"\"\"\n\n estimator_params = ClassifierMixin.estimator_params + ScikitlearnEstimator.estimator_params + [\"use_logits\"]\n\n def __init__(\n self,\n model: \"sklearn.base.BaseEstimator\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n use_logits: bool = False,\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn classifier model.\n\n :param model: scikit-learn classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param use_logits: Determines whether predict() returns logits instead of probabilities if available. Some\n adversarial attacks (DeepFool) may perform better if logits are used.\n \"\"\"\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._input_shape = self._get_input_shape(model)\n nb_classes = self._get_nb_classes()\n if nb_classes is not None:\n self.nb_classes = nb_classes\n self._use_logits = use_logits\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def use_logits(self) -> bool:\n \"\"\"\n Return the Boolean for using logits.\n\n :return: Boolean for using logits.\n \"\"\"\n return self._use_logits # type: ignore\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit` function in `sklearn` classifier and will be passed to this function as such.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n self.model.fit(x_preprocessed, y_preprocessed, **kwargs)\n self._input_shape = self._get_input_shape(self.model)\n self.nb_classes = self._get_nb_classes()\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n :raises `ValueError`: If the classifier does not have methods `predict` or `predict_proba`.\n \"\"\"\n # Apply defences\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n if self._use_logits:\n if callable(getattr(self.model, \"predict_log_proba\", None)):\n y_pred = self.model.predict_log_proba(x_preprocessed)\n else: # pragma: no cover\n raise ValueError(\n \"Argument `use_logits` was True but classifier model does not have callable\" \"`predict_log_proba`.\"\n )\n elif callable(getattr(self.model, \"predict_proba\", None)):\n y_pred = self.model.predict_proba(x_preprocessed)\n elif callable(getattr(self.model, \"predict\", None)):\n y_pred = to_categorical(\n self.model.predict(x_preprocessed),\n nb_classes=self._get_nb_classes(),\n )\n else: # pragma: no cover\n raise ValueError(\"The provided model does not have methods `predict_proba` or `predict`.\")\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=y_pred, fit=False)\n\n return predictions\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder): # pragma: no cover\n os.makedirs(folder)\n\n with open(full_path + \".pickle\", \"wb\") as file_pickle:\n pickle.dump(self.model, file=file_pickle)\n\n def clone_for_refitting(self) -> \"ScikitlearnClassifier\":\n \"\"\"\n Create a copy of the classifier that can be refit from scratch.\n\n :return: new estimator\n \"\"\"\n import sklearn\n\n clone = type(self)(sklearn.base.clone(self.model))\n params = self.get_params()\n del params[\"model\"]\n clone.set_params(**params)\n return clone\n\n def reset(self) -> None:\n \"\"\"\n Resets the weights of the classifier so that it can be refit from scratch.\n\n \"\"\"\n # No need to do anything since scikitlearn models start from scratch each time fit() is called\n pass\n\n def _get_nb_classes(self) -> int:\n if hasattr(self.model, \"n_classes_\"):\n _nb_classes = self.model.n_classes_\n elif hasattr(self.model, \"classes_\"):\n _nb_classes = self.model.classes_.shape[0]\n else:\n logger.warning(\"Number of classes not recognised. The model might not have been fitted.\")\n _nb_classes = None\n return _nb_classes\n\n\nclass ScikitlearnDecisionTreeClassifier(ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn Decision Tree Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.tree.DecisionTreeClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Decision Tree Classifier model.\n\n :param model: scikit-learn Decision Tree Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n import sklearn\n\n if not isinstance(model, sklearn.tree.DecisionTreeClassifier) and model is not None:\n raise TypeError(\"Model must be of type sklearn.tree.DecisionTreeClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n def get_classes_at_node(self, node_id: int) -> np.ndarray:\n \"\"\"\n Returns the classification for a given node.\n\n :return: Major class in node.\n \"\"\"\n return np.argmax(self.model.tree_.value[node_id]) # type: ignore\n\n def get_threshold_at_node(self, node_id: int) -> float:\n \"\"\"\n Returns the threshold of given id for a node.\n\n :return: Threshold value of feature split in this node.\n \"\"\"\n return self.model.tree_.threshold[node_id]\n\n def get_feature_at_node(self, node_id: int) -> int:\n \"\"\"\n Returns the feature of given id for a node.\n\n :return: Feature index of feature split in this node.\n \"\"\"\n return self.model.tree_.feature[node_id]\n\n def get_samples_at_node(self, node_id: int) -> int:\n \"\"\"\n Returns the number of training samples mapped to a node.\n\n :return: Number of samples mapped this node.\n \"\"\"\n return self.model.tree_.n_node_samples[node_id]\n\n def get_left_child(self, node_id: int) -> int:\n \"\"\"\n Returns the id of the left child node of node_id.\n\n :return: The indices of the left child in the tree.\n \"\"\"\n return self.model.tree_.children_left[node_id]\n\n def get_right_child(self, node_id: int) -> int:\n \"\"\"\n Returns the id of the right child node of node_id.\n\n :return: The indices of the right child in the tree.\n \"\"\"\n return self.model.tree_.children_right[node_id]\n\n def get_decision_path(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the path through nodes in the tree when classifying x. Last one is leaf, first one root node.\n\n :return: The indices of the nodes in the array structure of the tree.\n \"\"\"\n if len(np.shape(x)) == 1:\n return self.model.decision_path(x.reshape(1, -1)).indices\n\n return self.model.decision_path(x).indices\n\n def get_values_at_node(self, node_id: int) -> np.ndarray:\n \"\"\"\n Returns the feature of given id for a node.\n\n :return: Normalized values at node node_id.\n \"\"\"\n return self.model.tree_.value[node_id] / np.linalg.norm(self.model.tree_.value[node_id])\n\n def _get_leaf_nodes(self, node_id, i_tree, class_label, box) -> list[\"LeafNode\"]:\n from art.metrics.verification_decisions_trees import LeafNode, Box, Interval\n\n leaf_nodes = []\n\n if self.get_left_child(node_id) != self.get_right_child(node_id):\n\n node_left = self.get_left_child(node_id)\n node_right = self.get_right_child(node_id)\n\n box_left = deepcopy(box)\n box_right = deepcopy(box)\n\n feature = self.get_feature_at_node(node_id)\n box_split_left = Box(intervals={feature: Interval(-np.inf, self.get_threshold_at_node(node_id))})\n box_split_right = Box(intervals={feature: Interval(self.get_threshold_at_node(node_id), np.inf)})\n\n if box.intervals:\n box_left.intersect_with_box(box_split_left)\n box_right.intersect_with_box(box_split_right)\n else:\n box_left = box_split_left\n box_right = box_split_right\n\n leaf_nodes += self._get_leaf_nodes(node_left, i_tree, class_label, box_left)\n leaf_nodes += self._get_leaf_nodes(node_right, i_tree, class_label, box_right)\n\n else:\n leaf_nodes.append(\n LeafNode(\n tree_id=i_tree,\n class_label=class_label,\n node_id=node_id,\n box=box,\n value=self.get_values_at_node(node_id)[0, class_label],\n )\n )\n\n return leaf_nodes\n\n\nclass ScikitlearnExtraTreeClassifier(ScikitlearnDecisionTreeClassifier):\n \"\"\"\n Class for scikit-learn Extra TreeClassifier Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.tree.ExtraTreeClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Extra TreeClassifier Classifier model.\n\n :param model: scikit-learn Extra TreeClassifier Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n import sklearn\n\n if not isinstance(model, sklearn.tree.ExtraTreeClassifier):\n raise TypeError(\"Model must be of type sklearn.tree.ExtraTreeClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n\nclass ScikitlearnAdaBoostClassifier(ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn AdaBoost Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.ensemble.AdaBoostClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn AdaBoost Classifier model.\n\n :param model: scikit-learn AdaBoost Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n import sklearn\n\n if not isinstance(model, sklearn.ensemble.AdaBoostClassifier):\n raise TypeError(\"Model must be of type sklearn.ensemble.AdaBoostClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n\nclass ScikitlearnBaggingClassifier(ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn Bagging Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.ensemble.BaggingClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Bagging Classifier model.\n\n :param model: scikit-learn Bagging Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.ensemble.BaggingClassifier):\n raise TypeError(\"Model must be of type sklearn.ensemble.BaggingClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n\nclass ScikitlearnExtraTreesClassifier(ScikitlearnClassifier, DecisionTreeMixin):\n \"\"\"\n Class for scikit-learn Extra Trees Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.ensemble.ExtraTreesClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ):\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Extra Trees Classifier model.\n\n :param model: scikit-learn Extra Trees Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.ensemble.ExtraTreesClassifier):\n raise TypeError(\"Model must be of type sklearn.ensemble.ExtraTreesClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n def get_trees(self) -> list[\"Tree\"]:\n \"\"\"\n Get the decision trees.\n\n :return: A list of decision trees.\n \"\"\"\n from art.metrics.verification_decisions_trees import Box, Tree\n\n trees = []\n\n for i_tree, decision_tree_model in enumerate(self.model.estimators_):\n box = Box()\n\n # if num_classes == 2:\n # class_label = -1\n # else:\n # class_label = i_tree % num_classes\n\n extra_tree_classifier = ScikitlearnExtraTreeClassifier(model=decision_tree_model)\n\n for i_class in range(self.model.n_classes_):\n class_label = i_class\n\n trees.append(\n Tree(\n class_id=class_label,\n leaf_nodes=extra_tree_classifier._get_leaf_nodes(0, i_tree, class_label, box),\n )\n )\n\n return trees\n\n\nclass ScikitlearnGradientBoostingClassifier(ScikitlearnClassifier, DecisionTreeMixin):\n \"\"\"\n Class for scikit-learn Gradient Boosting Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.ensemble.GradientBoostingClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Gradient Boosting Classifier model.\n\n :param model: scikit-learn Gradient Boosting Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.ensemble.GradientBoostingClassifier):\n raise TypeError(\"Model must be of type sklearn.ensemble.GradientBoostingClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n def get_trees(self) -> list[\"Tree\"]:\n \"\"\"\n Get the decision trees.\n\n :return: A list of decision trees.\n \"\"\"\n from art.metrics.verification_decisions_trees import Box, Tree\n\n trees = []\n num_trees, num_classes = self.model.estimators_.shape\n\n for i_tree in range(num_trees):\n box = Box()\n\n for i_class in range(num_classes):\n decision_tree_classifier = ScikitlearnDecisionTreeRegressor(\n model=self.model.estimators_[i_tree, i_class]\n )\n\n if num_classes == 2:\n class_label = None\n else:\n class_label = i_class\n\n trees.append(\n Tree(\n class_id=class_label,\n leaf_nodes=decision_tree_classifier._get_leaf_nodes(0, i_tree, class_label, box),\n )\n )\n\n return trees\n\n\nclass ScikitlearnRandomForestClassifier(ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn Random Forest Classifier models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.ensemble.RandomForestClassifier\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Random Forest Classifier model.\n\n :param model: scikit-learn Random Forest Classifier model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.ensemble.RandomForestClassifier):\n raise TypeError(\"Model must be of type sklearn.ensemble.RandomForestClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n def get_trees(self) -> list[\"Tree\"]:\n \"\"\"\n Get the decision trees.\n\n :return: A list of decision trees.\n \"\"\"\n from art.metrics.verification_decisions_trees import Box, Tree\n\n trees = []\n\n for i_tree, decision_tree_model in enumerate(self.model.estimators_):\n box = Box()\n\n # if num_classes == 2:\n # class_label = -1\n # else:\n # class_label = i_tree % num_classes\n\n decision_tree_classifier = ScikitlearnDecisionTreeClassifier(model=decision_tree_model)\n\n for i_class in range(self.model.n_classes_):\n class_label = i_class\n\n trees.append(\n Tree(\n class_id=class_label,\n leaf_nodes=decision_tree_classifier._get_leaf_nodes(0, i_tree, class_label, box),\n )\n )\n\n return trees\n\n\nclass ScikitlearnLogisticRegression(ClassGradientsMixin, LossGradientsMixin, ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn Logistic Regression models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.linear_model.LogisticRegression\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Logistic Regression model.\n\n :param model: scikit-learn LogisticRegression model\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.linear_model.LogisticRegression):\n raise TypeError(\"Model must be of type sklearn.linear_model.LogisticRegression).\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n def class_gradient(self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n | Paper link: http://cs229.stanford.edu/proj2016/report/ItkinaWu-AdversarialAttacksonImageRecognition-report.pdf\n | Typo in https://arxiv.org/abs/1605.07277 (equation 6)\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n :raises `ValueError`: If the model has not been fitted prior to calling this method or if the number of\n classes in the classifier is not known.\n :raises `TypeError`: If the requested label cannot be processed.\n \"\"\"\n if not hasattr(self.model, \"coef_\"): # pragma: no cover\n raise ValueError(\n \"\"\"Model has not been fitted. Run function `fit(x, y)` of classifier first or provide a\n fitted model.\"\"\"\n )\n if self.nb_classes is None: # pragma: no cover\n raise ValueError(\"Unknown number of classes in classifier.\")\n nb_samples = x.shape[0]\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n y_pred = self.model.predict_proba(X=x_preprocessed)\n weights = self.model.coef_\n\n if self.nb_classes > 2: # type: ignore\n w_weighted = np.matmul(y_pred, weights)\n\n def _f_class_gradient(i_class, i_sample):\n if self.nb_classes == 2:\n return (-1.0) ** (i_class + 1.0) * y_pred[i_sample, 0] * y_pred[i_sample, 1] * weights[0, :]\n\n return weights[i_class, :] - w_weighted[i_sample, :]\n\n if label is None:\n # Compute the gradients w.r.t. all classes\n class_gradients = []\n\n for i_class in range(self.nb_classes): # type: ignore\n class_gradient = np.zeros(x.shape)\n for i_sample in range(nb_samples):\n class_gradient[i_sample, :] += _f_class_gradient(i_class, i_sample)\n class_gradients.append(class_gradient)\n\n gradients = np.swapaxes(np.array(class_gradients), 0, 1)\n\n elif isinstance(label, int):\n # Compute the gradients only w.r.t. the provided label\n class_gradient = np.zeros(x.shape)\n for i_sample in range(nb_samples):\n class_gradient[i_sample, :] += _f_class_gradient(label, i_sample)\n\n gradients = np.swapaxes(np.array([class_gradient]), 0, 1)\n\n elif (\n (isinstance(label, list) and len(label) == nb_samples)\n or isinstance(label, np.ndarray)\n and label.shape == (nb_samples,)\n ):\n # For each sample, compute the gradients w.r.t. the indicated target class (possibly distinct)\n class_gradients = []\n unique_labels = list(np.unique(label))\n\n for unique_label in unique_labels:\n class_gradient = np.zeros(x.shape)\n for i_sample in range(nb_samples):\n # class_gradient[i_sample, :] += label[i_sample, unique_label] * (weights[unique_label, :]\n # - w_weighted[i_sample, :])\n class_gradient[i_sample, :] += _f_class_gradient(unique_label, i_sample)\n\n class_gradients.append(class_gradient)\n\n gradients = np.swapaxes(np.array(class_gradients), 0, 1)\n lst = [unique_labels.index(i) for i in label]\n gradients = np.expand_dims(gradients[np.arange(len(gradients)), lst], axis=1)\n\n else:\n raise TypeError(\"Unrecognized type for argument `label` with type \" + str(type(label)))\n\n gradients = self._apply_preprocessing_gradient(x, gradients)\n\n return gradients\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :return: Array of gradients of the same shape as `x`.\n :raises `ValueError`: If the model has not been fitted prior to calling this method.\n \"\"\"\n\n from sklearn.utils.class_weight import compute_class_weight\n\n if not hasattr(self.model, \"coef_\"): # pragma: no cover\n raise ValueError(\n \"\"\"Model has not been fitted. Run function `fit(x, y)` of classifier first or provide a\n fitted model.\"\"\"\n )\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n y_index = np.argmax(y_preprocessed, axis=1)\n if self.model.class_weight is None or self.model.class_weight == \"balanced\":\n class_weight = np.ones(self.nb_classes)\n else:\n class_weight = compute_class_weight(\n class_weight=self.model.class_weight,\n classes=self.model.classes_,\n y=y_index,\n )\n\n y_pred = self.predict(x=x_preprocessed)\n weights = self.model.coef_\n\n errors = class_weight * (y_pred - y)\n\n if weights.shape[0] == 1:\n weights = np.append(-weights, weights, axis=0)\n\n gradients = (errors @ weights) / self.model.classes_.size\n\n gradients = self._apply_preprocessing_gradient(x, gradients)\n\n return gradients\n\n @staticmethod\n def get_trainable_attribute_names() -> tuple[str, str]:\n \"\"\"\n Get the names of trainable attributes.\n\n :return: A tuple of trainable attributes.\n \"\"\"\n return \"intercept_\", \"coef_\"\n\n\nclass ScikitlearnGaussianNB(ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn Gaussian Naive Bayes models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.naive_bayes.GaussianNB\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn Gaussian Naive Bayes (GaussianNB) model.\n\n :param model: scikit-learn Gaussian Naive Bayes (GaussianNB) model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.naive_bayes.GaussianNB): # pragma: no cover\n raise TypeError(f\"Model must be of type sklearn.naive_bayes.GaussianNB. Found type {type(model)}\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n def get_trainable_attribute_names(self) -> tuple[str, str]:\n \"\"\"\n Get the names of trainable attributes.\n\n :return: A tuple of trainable attributes.\n \"\"\"\n # For scikit-learn <=0.24\n if hasattr(self.model, \"sigma_\"):\n return \"sigma_\", \"theta_\"\n\n return \"var_\", \"theta_\"\n\n\nclass ScikitlearnSVC(ClassGradientsMixin, LossGradientsMixin, ScikitlearnClassifier):\n \"\"\"\n Class for scikit-learn C-Support Vector Classification models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.svm.SVC\" | \"sklearn.svm.LinearSVC\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a scikit-learn C-Support Vector Classification model.\n\n :param model: scikit-learn C-Support Vector Classification model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.svm.SVC) and not isinstance(model, sklearn.svm.LinearSVC):\n raise TypeError(f\"Model must be of type sklearn.svm.SVC or sklearn.svm.LinearSVC. Found type {type(model)}\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._kernel = self._kernel_func()\n\n def class_gradient(self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n\n import sklearn\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n num_samples, _ = x_preprocessed.shape\n\n if isinstance(self.model, sklearn.svm.SVC):\n if self.model.fit_status_: # pragma: no cover\n raise AssertionError(\"Model has not been fitted correctly.\")\n\n support_indices = [0] + list(np.cumsum(self.model.n_support_))\n\n if self.nb_classes == 2:\n sign_multiplier = -1\n else:\n sign_multiplier = 1\n\n if label is None:\n gradients = np.zeros(\n (\n x_preprocessed.shape[0],\n self.nb_classes,\n x_preprocessed.shape[1],\n )\n )\n\n for i_label in range(self.nb_classes): # type: ignore\n for i_sample in range(num_samples):\n for not_label in range(self.nb_classes): # type: ignore\n if i_label != not_label:\n if not_label < i_label:\n label_multiplier = -1\n else:\n label_multiplier = 1\n\n for label_sv in range(\n support_indices[i_label],\n support_indices[i_label + 1],\n ):\n alpha_i_k_y_i = self.model.dual_coef_[\n not_label if not_label < i_label else not_label - 1,\n label_sv,\n ]\n grad_kernel = self._get_kernel_gradient_sv(label_sv, x_preprocessed[i_sample])\n gradients[i_sample, i_label] += label_multiplier * alpha_i_k_y_i * grad_kernel\n\n for not_label_sv in range(\n support_indices[not_label],\n support_indices[not_label + 1],\n ):\n alpha_i_k_y_i = self.model.dual_coef_[\n i_label if i_label < not_label else i_label - 1,\n not_label_sv,\n ]\n grad_kernel = self._get_kernel_gradient_sv(not_label_sv, x_preprocessed[i_sample])\n gradients[i_sample, i_label] += label_multiplier * alpha_i_k_y_i * grad_kernel\n\n elif isinstance(label, int):\n gradients = np.zeros((x_preprocessed.shape[0], 1, x_preprocessed.shape[1]))\n\n for i_sample in range(num_samples):\n for not_label in range(self.nb_classes): # type: ignore\n if label != not_label:\n if not_label < label:\n label_multiplier = -1\n else:\n label_multiplier = 1\n\n for label_sv in range(support_indices[label], support_indices[label + 1]):\n alpha_i_k_y_i = self.model.dual_coef_[\n not_label if not_label < label else not_label - 1,\n label_sv,\n ]\n grad_kernel = self._get_kernel_gradient_sv(label_sv, x_preprocessed[i_sample])\n gradients[i_sample, 0] += label_multiplier * alpha_i_k_y_i * grad_kernel\n\n for not_label_sv in range(\n support_indices[not_label],\n support_indices[not_label + 1],\n ):\n alpha_i_k_y_i = self.model.dual_coef_[\n label if label < not_label else label - 1,\n not_label_sv,\n ]\n grad_kernel = self._get_kernel_gradient_sv(not_label_sv, x_preprocessed[i_sample])\n gradients[i_sample, 0] += label_multiplier * alpha_i_k_y_i * grad_kernel\n\n elif (\n (isinstance(label, list) and len(label) == num_samples)\n or isinstance(label, np.ndarray)\n and label.shape == (num_samples,)\n ):\n gradients = np.zeros((x_preprocessed.shape[0], 1, x_preprocessed.shape[1]))\n\n for i_sample in range(num_samples):\n for not_label in range(self.nb_classes): # type: ignore\n if label[i_sample] != not_label:\n if not_label < label[i_sample]:\n label_multiplier = -1\n else:\n label_multiplier = 1\n\n for label_sv in range(\n support_indices[label[i_sample]],\n support_indices[label[i_sample] + 1],\n ):\n alpha_i_k_y_i = self.model.dual_coef_[\n not_label if not_label < label[i_sample] else not_label - 1,\n label_sv,\n ]\n grad_kernel = self._get_kernel_gradient_sv(label_sv, x_preprocessed[i_sample])\n gradients[i_sample, 0] += label_multiplier * alpha_i_k_y_i * grad_kernel\n\n for not_label_sv in range(\n support_indices[not_label],\n support_indices[not_label + 1],\n ):\n alpha_i_k_y_i = self.model.dual_coef_[\n label[i_sample] if label[i_sample] < not_label else label[i_sample] - 1,\n not_label_sv,\n ]\n grad_kernel = self._get_kernel_gradient_sv(not_label_sv, x_preprocessed[i_sample])\n gradients[i_sample, 0] += label_multiplier * alpha_i_k_y_i * grad_kernel\n\n else:\n raise TypeError(\"Unrecognized type for argument `label` with type \" + str(type(label)))\n\n gradients = self._apply_preprocessing_gradient(x, gradients * sign_multiplier)\n\n elif isinstance(self.model, sklearn.svm.LinearSVC):\n if label is None:\n gradients = np.zeros(\n (\n x_preprocessed.shape[0],\n self.nb_classes,\n x_preprocessed.shape[1],\n )\n )\n\n for i in range(self.nb_classes): # type: ignore\n for i_sample in range(num_samples):\n if self.nb_classes == 2:\n gradients[i_sample, i] = self.model.coef_[0] * (2 * i - 1)\n else:\n gradients[i_sample, i] = self.model.coef_[i]\n\n elif isinstance(label, int):\n gradients = np.zeros((x_preprocessed.shape[0], 1, x_preprocessed.shape[1]))\n\n for i_sample in range(num_samples):\n if self.nb_classes == 2:\n gradients[i_sample, 0] = self.model.coef_[0] * (2 * label - 1)\n else:\n gradients[i_sample, 0] = self.model.coef_[label]\n\n elif (\n (isinstance(label, list) and len(label) == num_samples)\n or isinstance(label, np.ndarray)\n and label.shape == (num_samples,)\n ):\n gradients = np.zeros((x_preprocessed.shape[0], 1, x_preprocessed.shape[1]))\n\n for i_sample in range(num_samples):\n if self.nb_classes == 2:\n gradients[i_sample, 0] = self.model.coef_[0] * (2 * label[i_sample] - 1)\n else:\n gradients[i_sample, 0] = self.model.coef_[label[i_sample]]\n\n else:\n raise TypeError(\"Unrecognized type for argument `label` with type \" + str(type(label)))\n\n gradients = self._apply_preprocessing_gradient(x, gradients)\n\n else:\n raise ValueError(\"Type of `self.model` not supported for class-gradients.\")\n\n return gradients\n\n def _kernel_grad(self, sv: np.ndarray, x_sample: np.ndarray) -> np.ndarray:\n \"\"\"\n Applies the kernel gradient to a support vector.\n\n :param sv: A support vector.\n :param x_sample: The sample the gradient is taken with respect to.\n :return: the kernel gradient.\n \"\"\"\n\n if self.model.kernel == \"linear\":\n grad = sv\n elif self.model.kernel == \"poly\":\n grad = (\n self.model.degree\n * (self.model._gamma * np.sum(x_sample * sv) + self.model.coef0) ** (self.model.degree - 1)\n * sv\n )\n elif self.model.kernel == \"rbf\":\n grad = (\n 2\n * self.model._gamma\n * (-1)\n * np.exp(-self.model._gamma * np.linalg.norm(x_sample - sv, ord=2) ** 2)\n * (x_sample - sv)\n )\n elif self.model.kernel == \"sigmoid\":\n raise NotImplementedError\n else:\n raise NotImplementedError(f\"Loss gradients for kernel '{self.model.kernel}' are not implemented.\")\n return grad\n\n def _get_kernel_gradient_sv(self, i_sv: int, x_sample: np.ndarray) -> np.ndarray:\n \"\"\"\n Applies the kernel gradient to all of a model's support vectors.\n\n :param i_sv: A support vector index.\n :param x_sample: A sample vector.\n :return: The kernelized product of the vectors.\n \"\"\"\n x_i = self.model.support_vectors_[i_sv, :]\n return self._kernel_grad(x_i, x_sample)\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n Following equation (1) with lambda=0.\n\n | Paper link: https://pralab.diee.unica.it/sites/default/files/biggio14-svm-chapter.pdf\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n\n import sklearn\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n num_samples, _ = x_preprocessed.shape\n gradients = np.zeros_like(x_preprocessed)\n y_index = np.argmax(y_preprocessed, axis=1)\n\n if isinstance(self.model, sklearn.svm.SVC):\n\n if self.model.fit_status_:\n raise AssertionError(\"Model has not been fitted correctly.\")\n\n if y_preprocessed.shape[1] == 2:\n sign_multiplier = 1\n else:\n sign_multiplier = -1\n\n i_not_label_i = None\n label_multiplier = None\n support_indices = [0] + list(np.cumsum(self.model.n_support_))\n\n for i_sample in range(num_samples):\n i_label = y_index[i_sample]\n\n for i_not_label in range(self.nb_classes): # type: ignore\n if i_label != i_not_label:\n if i_not_label < i_label:\n i_not_label_i = i_not_label\n label_multiplier = -1\n elif i_not_label > i_label:\n i_not_label_i = i_not_label - 1\n label_multiplier = 1\n\n for i_label_sv in range(support_indices[i_label], support_indices[i_label + 1]):\n alpha_i_k_y_i = self.model.dual_coef_[i_not_label_i, i_label_sv] * label_multiplier\n grad_kernel = self._get_kernel_gradient_sv(i_label_sv, x_preprocessed[i_sample])\n gradients[i_sample, :] += sign_multiplier * alpha_i_k_y_i * grad_kernel\n\n for i_not_label_sv in range(\n support_indices[i_not_label],\n support_indices[i_not_label + 1],\n ):\n alpha_i_k_y_i = self.model.dual_coef_[i_not_label_i, i_not_label_sv] * label_multiplier\n grad_kernel = self._get_kernel_gradient_sv(i_not_label_sv, x_preprocessed[i_sample])\n gradients[i_sample, :] += sign_multiplier * alpha_i_k_y_i * grad_kernel\n\n elif isinstance(self.model, sklearn.svm.LinearSVC):\n for i_sample in range(num_samples):\n i_label = y_index[i_sample]\n if self.nb_classes == 2:\n i_label_i = 0\n if i_label == 0:\n label_multiplier = 1\n elif i_label == 1:\n label_multiplier = -1\n else:\n raise ValueError(\"Label index not recognized because it is not 0 or 1.\")\n else:\n i_label_i = i_label\n label_multiplier = -1\n\n gradients[i_sample] = label_multiplier * self.model.coef_[i_label_i]\n else:\n raise TypeError(\"Model not recognized.\")\n\n gradients = self._apply_preprocessing_gradient(x, gradients)\n return gradients\n\n def _kernel_func(self) -> Callable:\n \"\"\"\n Return the function for the kernel of this SVM.\n\n :return: A callable kernel function.\n \"\"\"\n\n import sklearn\n from sklearn.metrics.pairwise import (\n polynomial_kernel,\n linear_kernel,\n rbf_kernel,\n )\n\n if isinstance(self.model, sklearn.svm.LinearSVC):\n kernel = \"linear\"\n elif isinstance(self.model, sklearn.svm.SVC):\n kernel = self.model.kernel\n else:\n raise NotImplementedError(\"SVM model not yet supported.\")\n\n if kernel == \"linear\":\n kernel_func = linear_kernel\n elif kernel == \"poly\":\n kernel_func = polynomial_kernel\n elif kernel == \"rbf\":\n kernel_func = rbf_kernel\n elif callable(kernel):\n kernel_func = kernel\n else:\n raise NotImplementedError(f\"Kernel '{kernel}' not yet supported.\")\n\n return kernel_func\n\n def q_submatrix(self, rows: np.ndarray, cols: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the q submatrix of this SVM indexed by the arrays at rows and columns.\n\n :param rows: The row vectors.\n :param cols: The column vectors.\n :return: A submatrix of Q.\n \"\"\"\n submatrix_shape = (rows.shape[0], cols.shape[0])\n y_row = self.model.predict(rows)\n y_col = self.model.predict(cols)\n y_row[y_row == 0] = -1\n y_col[y_col == 0] = -1\n q_rc = np.zeros(submatrix_shape)\n for row in range(q_rc.shape[0]):\n for col in range(q_rc.shape[1]):\n q_rc[row][col] = self._kernel([rows[row]], [cols[col]])[0][0] * y_row[row] * y_col[col]\n\n return q_rc\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n\n import sklearn\n\n # Apply defences\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n if isinstance(self.model, sklearn.svm.SVC) and self.model.probability:\n y_pred = self.model.predict_proba(X=x_preprocessed)\n else:\n y_pred_label = self.model.predict(X=x_preprocessed)\n targets = np.array(y_pred_label).reshape(-1)\n one_hot_targets = np.eye(self.nb_classes)[targets]\n y_pred = one_hot_targets\n\n return y_pred\n\n\nScikitlearnLinearSVC = ScikitlearnSVC\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `TensorFlowClassifier` for TensorFlow models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nfrom typing import TYPE_CHECKING\nfrom tqdm.auto import tqdm\n\nimport numpy as np\nimport six\n\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin, ClassifierMixin\n\nif TYPE_CHECKING:\n\n import tensorflow.compat.v1 as tf\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2Classifier(ClassGradientsMixin, ClassifierMixin, TensorFlowV2Estimator):\n \"\"\"\n This class implements a classifier with the TensorFlow v2 framework.\n \"\"\"\n\n estimator_params = (\n TensorFlowV2Estimator.estimator_params\n + ClassifierMixin.estimator_params\n + [\n \"input_shape\",\n \"loss_object\",\n \"optimizer\",\n \"train_step\",\n ]\n )\n\n def __init__(\n self,\n model: Callable,\n nb_classes: int,\n input_shape: tuple[int, ...],\n loss_object: \"tf.keras.losses.Loss\" | None = None,\n optimizer: \"tf.keras.optimizers.Optimizer\" | None = None,\n train_step: Callable | None = None,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Initialization specific to TensorFlow v2 models.\n\n :param model: a python functions or callable class defining the model and providing it prediction as output.\n :param nb_classes: the number of classes in the classification task.\n :param input_shape: shape of one input for the classifier, e.g. for MNIST input_shape=(28, 28, 1).\n :param loss_object: The loss function for which to compute gradients. This parameter is applied for training\n the model and computing gradients of the loss w.r.t. the input.\n :param optimizer: The optimizer used to train the classifier.\n :param train_step: A function that applies a gradient update to the trainable variables with signature\n `train_step(model, images, labels)`. This will override the default training loop that uses the\n provided `loss_object` and `optimizer` parameters. It is recommended to use the `@tf.function`\n decorator, if possible, for efficient training.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n import tensorflow as tf\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n self.nb_classes = nb_classes\n self._input_shape = input_shape\n self._loss_object = loss_object\n self._optimizer = optimizer\n self._train_step = train_step\n\n # Check if the loss function requires as input index labels instead of one-hot-encoded labels\n if isinstance(self._loss_object, tf.keras.losses.SparseCategoricalCrossentropy):\n self._reduce_labels = True\n else:\n self._reduce_labels = False\n\n @tf.function(reduce_retracing=True) # Compile this for speed\n def _forward_pass(model, x, training):\n return model(x, training=training)\n\n self._forward_pass = _forward_pass\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def loss_object(self) -> \"tf.keras.losses.Loss\":\n \"\"\"\n Return the loss function.\n\n :return: The loss function.\n \"\"\"\n return self._loss_object # type: ignore\n\n @property\n def optimizer(self) -> \"tf.keras.optimizers.Optimizer\":\n \"\"\"\n Return the optimizer.\n\n :return: The optimizer.\n \"\"\"\n return self._optimizer # type: ignore\n\n @property\n def train_step(self) -> Callable:\n \"\"\"\n Return the function that applies a gradient update to the trainable variables.\n\n :return: The function that applies a gradient update to the trainable variables.\n \"\"\"\n return self._train_step # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n predictions = self._forward_pass(self._model, x_preprocessed, training=training_mode) # Fast, compiled call\n\n # Apply postprocessing\n predictions_post = self._apply_postprocessing(preds=predictions.numpy(), fit=False)\n\n return predictions_post\n\n def _predict_framework(self, x: \"tf.Tensor\", training_mode: bool = False) -> \"tf.Tensor\":\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n return self._model(x_preprocessed, training=training_mode)\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n verbose: bool = False,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels, one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter currently supports\n \"scheduler\" which is an optional function that will be called at the end of every\n epoch to adjust the learning rate.\n \"\"\"\n import tensorflow as tf\n from art.utils import check_and_transform_label_format\n\n if self._train_step is None: # pragma: no cover\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\n \"A loss function `loss_object` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\n \"An optimizer `optimizer` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n\n @tf.function\n def train_step(model, images, labels):\n with tf.GradientTape() as tape:\n predictions = model(images, training=True)\n loss = self.loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n if hasattr(self.optimizer, \"_check_variables_are_known\"):\n self.optimizer._check_variables_are_known = lambda *args, **kwargs: None\n self.optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n else:\n train_step = self._train_step\n\n scheduler = kwargs.get(\"scheduler\")\n\n y = check_and_transform_label_format(y, nb_classes=self.nb_classes)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Check label shape\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n train_ds = tf.data.Dataset.from_tensor_slices((x_preprocessed, y_preprocessed)).shuffle(10000).batch(batch_size)\n\n for epoch in tqdm(range(nb_epochs), disable=not verbose, desc=\"Epochs\"):\n for images, labels in train_ds:\n train_step(self.model, images, labels)\n\n if scheduler is not None:\n scheduler(epoch)\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, verbose: bool = False, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch. If the generator can be used for native\n training in TensorFlow, it will.\n :param nb_epochs: Number of epochs to use for training.\n :param verbose: Display training progress bar.\n :param kwargs: Dictionary of framework-specific arguments. This parameter currently supports\n \"scheduler\" which is an optional function that will be called at the end of every\n epoch to adjust the learning rate.\n \"\"\"\n import tensorflow as tf\n from art.data_generators import TensorFlowV2DataGenerator\n\n if self._train_step is None: # pragma: no cover\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\n \"A loss function `loss_object` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\n \"An optimizer `optimizer` or training function `train_step` is required for fitting the \"\n \"model, but it has not been defined.\"\n )\n\n @tf.function\n def train_step(model, images, labels):\n with tf.GradientTape() as tape:\n predictions = model(images, training=True)\n loss = self.loss_object(labels, predictions)\n gradients = tape.gradient(loss, model.trainable_variables)\n self.optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n else:\n train_step = self._train_step\n\n scheduler = kwargs.get(\"scheduler\")\n\n # Train directly in TensorFlow\n from art.preprocessing.standardisation_mean_std.tensorflow import StandardisationMeanStdTensorFlow\n\n if isinstance(generator, TensorFlowV2DataGenerator) and (\n self.preprocessing is None\n or (\n isinstance(self.preprocessing, StandardisationMeanStdTensorFlow)\n and (\n self.preprocessing.mean,\n self.preprocessing.std,\n )\n == (0, 1)\n )\n ):\n for epoch in tqdm(range(nb_epochs), disable=not verbose, desc=\"Epochs\"):\n for i_batch, o_batch in generator.iterator:\n if self._reduce_labels:\n o_batch = tf.math.argmax(o_batch, axis=1)\n train_step(self._model, i_batch, o_batch)\n\n if scheduler is not None:\n scheduler(epoch)\n else:\n # Fit a generic data generator through the API\n super().fit_generator(generator, nb_epochs=nb_epochs)\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n import tensorflow as tf\n\n x = tf.convert_to_tensor(x)\n\n with tf.GradientTape(persistent=True) as tape:\n # Apply preprocessing\n if self.all_framework_preprocessing:\n x_grad = tf.convert_to_tensor(x)\n tape.watch(x_grad)\n x_input, _ = self._apply_preprocessing(x_grad, y=None, fit=False)\n else:\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n x_grad = tf.convert_to_tensor(x_preprocessed)\n tape.watch(x_grad)\n x_input = x_grad\n\n tape.watch(x_input)\n\n # Compute the gradients\n if tf.executing_eagerly():\n if label is None:\n # Compute the gradients w.r.t. all classes\n class_gradients = []\n\n for i in range(self.nb_classes):\n predictions = self.model(x_input, training=training_mode)\n prediction = predictions[:, i]\n tape.watch(prediction)\n\n class_gradient = tape.gradient(prediction, x_input).numpy()\n class_gradients.append(class_gradient)\n # Break after 1 iteration for binary classification case\n if len(predictions.shape) == 1 or predictions.shape[1] == 1:\n break\n\n gradients = np.swapaxes(np.array(class_gradients), 0, 1)\n\n elif isinstance(label, int):\n # Compute the gradients only w.r.t. the provided label\n predictions = self.model(x_input, training=training_mode)\n prediction = predictions[:, label]\n tape.watch(prediction)\n\n class_gradient = tape.gradient(prediction, x_grad).numpy()\n gradients = np.expand_dims(class_gradient, axis=1)\n\n else:\n # For each sample, compute the gradients w.r.t. the indicated target class (possibly distinct)\n class_gradients = []\n unique_labels = list(np.unique(label))\n\n for unique_label in unique_labels:\n predictions = self.model(x_input, training=training_mode)\n prediction = predictions[:, unique_label]\n tape.watch(prediction)\n\n class_gradient = tape.gradient(prediction, x_grad).numpy()\n class_gradients.append(class_gradient)\n\n gradients = np.swapaxes(np.array(class_gradients), 0, 1)\n lst = [unique_labels.index(i) for i in label]\n gradients = np.expand_dims(gradients[np.arange(len(gradients)), lst], axis=1)\n\n if not self.all_framework_preprocessing:\n gradients = self._apply_preprocessing_gradient(x, gradients)\n\n else:\n raise NotImplementedError(\"Expecting eager execution.\")\n\n return gradients\n\n def compute_loss(\n self,\n x: np.ndarray | \"tf.Tensor\",\n y: np.ndarray | \"tf.Tensor\",\n reduction: str = \"none\",\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute the loss.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of losses of the same shape as `x`.\n \"\"\"\n import tensorflow as tf\n from art.utils import check_and_transform_label_format\n\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\"The loss function `loss_object` is required for computing losses, but it is not defined.\")\n prev_reduction = self._loss_object.reduction\n if reduction == \"none\":\n self._loss_object.reduction = tf.keras.losses.Reduction.NONE\n elif reduction == \"mean\":\n self._loss_object.reduction = tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE\n elif reduction == \"sum\":\n self._loss_object.reduction = tf.keras.losses.Reduction.SUM\n\n y = check_and_transform_label_format(y, self.nb_classes) # type: ignore\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n if tf.executing_eagerly():\n x_preprocessed_tf = tf.convert_to_tensor(x_preprocessed)\n predictions = self.model(x_preprocessed_tf, training=training_mode)\n if self._reduce_labels:\n loss = self._loss_object(np.argmax(y_preprocessed, axis=1), predictions)\n else:\n loss = self._loss_object(y_preprocessed, predictions)\n else:\n raise NotImplementedError(\"Expecting eager execution.\")\n\n self._loss_object.reduction = prev_reduction\n return loss.numpy()\n\n def compute_losses(\n self,\n x: np.ndarray | \"tf.Tensor\",\n y: np.ndarray | \"tf.Tensor\",\n reduction: str = \"none\",\n ) -> dict[str, np.ndarray | \"tf.Tensor\"]:\n \"\"\"\n Compute all loss components.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Dictionary of loss components.\n \"\"\"\n return {\"total\": self.compute_loss(x=x, y=y, reduction=reduction)}\n\n def loss_gradient(\n self,\n x: np.ndarray | \"tf.Tensor\",\n y: np.ndarray | \"tf.Tensor\",\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray | \"tf.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Correct labels, one-vs-rest encoding.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import tensorflow as tf\n\n if self._loss_object is None: # pragma: no cover\n raise TypeError(\n \"The loss function `loss_object` is required for computing loss gradients, but it has not been \"\n \"defined.\"\n )\n\n if tf.executing_eagerly():\n with tf.GradientTape() as tape:\n # Apply preprocessing\n if self.all_framework_preprocessing:\n x_grad = tf.convert_to_tensor(x)\n tape.watch(x_grad)\n x_input, y_input = self._apply_preprocessing(x_grad, y=y, fit=False)\n else:\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y=y, fit=False)\n x_grad = tf.convert_to_tensor(x_preprocessed)\n tape.watch(x_grad)\n x_input = x_grad\n y_input = y_preprocessed\n\n predictions = self.model(x_input, training=training_mode)\n\n if self._reduce_labels:\n loss = self._loss_object(np.argmax(y_input, axis=1), predictions)\n else:\n loss = self._loss_object(y_input, predictions)\n\n gradients = tape.gradient(loss, x_grad)\n\n if isinstance(x, np.ndarray):\n gradients = gradients.numpy()\n\n else:\n raise NotImplementedError(\"Expecting eager execution.\")\n\n # Apply preprocessing gradients\n if not self.all_framework_preprocessing:\n gradients = self._apply_preprocessing_gradient(x, gradients)\n\n return gradients\n\n def clone_for_refitting(\n self,\n ) -> \"TensorFlowV2Classifier\": # pragma: no cover\n \"\"\"\n Create a copy of the classifier that can be refit from scratch. Will inherit same architecture, optimizer and\n initialization as cloned model, but without weights.\n\n :return: new estimator\n \"\"\"\n import tensorflow as tf\n\n try:\n model = tf.keras.models.clone_model(self.model, input_tensors=self.model.input)\n except ValueError as error:\n raise ValueError(\"Cannot clone custom tensorflow models\") from error\n\n # Recreate optimizer from config (fresh instance for each clone)\n optimizer_config = self.model.optimizer.get_config()\n optimizer_class = type(self.model.optimizer)\n new_optimizer = optimizer_class.from_config(optimizer_config)\n\n # Compile the model with the new optimizer\n model.compile(\n optimizer=new_optimizer,\n loss=self.model.loss,\n metrics=self.model.metrics,\n run_eagerly=self.model.run_eagerly,\n )\n\n clone = type(self)(model, self.nb_classes, self.input_shape)\n params = self.get_params()\n del params[\"model\"]\n clone.set_params(**params)\n clone._train_step = self._train_step\n clone._reduce_labels = self._reduce_labels\n clone._loss_object = self._loss_object\n clone._optimizer = new_optimizer\n return clone\n\n def reset(self) -> None:\n \"\"\"\n Resets the weights of the classifier so that it can be refit from scratch.\n \"\"\"\n import tensorflow as tf\n\n for layer in self.model.layers:\n if isinstance(layer, (tf.keras.Model, tf.keras.models.Sequential)): # if there is a model as a layer\n raise NotImplementedError(\"Resetting of models with models as layers has not been tested.\")\n # self.reset(layer) # apply recursively\n # continue\n\n # find initializers\n if hasattr(layer, \"cell\"):\n init_container = layer.cell\n else:\n init_container = layer\n\n for key, initializer in init_container.__dict__.items():\n if \"initializer\" not in key: # not an initializer skip\n continue\n\n # find the corresponding variable, like the kernel or the bias\n if key == \"recurrent_initializer\": # special case check\n var = getattr(init_container, \"recurrent_kernel\", None)\n else:\n var = getattr(init_container, key.replace(\"_initializer\", \"\"), None)\n\n if var is not None:\n var.assign(initializer(var.shape, var.dtype))\n\n def _get_layers(self) -> list:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n \"\"\"\n raise NotImplementedError\n\n @property\n def layer_names(self) -> list[str] | None:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n\n .. warning:: `layer_names` tries to infer the internal structure of the model.\n This feature comes with no guarantees on the correctness of the result.\n The intended order of the layers tries to match their order in the model, but this is not\n guaranteed either.\n \"\"\"\n import tensorflow as tf\n\n if isinstance(self._model, (tf.keras.Model, tf.keras.models.Sequential)):\n return [layer.name for layer in self._model.layers if hasattr(layer, \"name\")]\n\n return None # type: ignore\n\n def get_activations( # type: ignore\n self, x: np.ndarray, layer: int | str, batch_size: int = 128, framework: bool = False\n ) -> np.ndarray | None:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations.\n :param batch_size: Batch size.\n :param framework: Return activation as tensor.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n import tensorflow as tf\n import tensorflow.keras.backend as k\n from art.config import ART_NUMPY_DTYPE\n\n if not isinstance(self._model, tf.keras.models.Sequential): # pragma: no cover\n raise ValueError(\"Method get_activations is not supported for non-Sequential models.\")\n\n i_layer = None\n if self.layer_names is None: # pragma: no cover\n raise ValueError(\"No layer names identified.\")\n\n if isinstance(layer, six.string_types):\n if layer not in self.layer_names: # pragma: no cover\n raise ValueError(f\"Layer name {layer} is not part of the graph.\")\n for i_name, name in enumerate(self.layer_names):\n if name == layer:\n i_layer = i_name\n break\n elif isinstance(layer, int):\n if layer < -len(self.layer_names) or layer >= len(self.layer_names): # pragma: no cover\n raise ValueError(\n f\"Layer index {layer} is outside of range (-{len(self.layer_names)} \"\n f\"to {len(self.layer_names) - 1}).\"\n )\n i_layer = layer\n else: # pragma: no cover\n raise TypeError(\"Layer must be of type `str` or `int`.\")\n\n activation_model = tf.keras.Model(self._model.layers[0].input, self._model.layers[i_layer].output)\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x=x, y=None, fit=False)\n\n if framework:\n if isinstance(x_preprocessed, tf.Tensor):\n return activation_model(x_preprocessed, training=False)\n return activation_model(tf.convert_to_tensor(x_preprocessed), training=False)\n\n # Determine shape of expected output and prepare array\n layer_instance = self._model.layers[i_layer]\n input_shape = k.int_shape(layer_instance.input) # Keras 3.x-safe way\n output_shape = layer_instance.compute_output_shape(input_shape)\n activations = np.zeros((x_preprocessed.shape[0],) + output_shape[1:], dtype=ART_NUMPY_DTYPE)\n\n # Get activations with batching\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = (\n batch_index * batch_size,\n min((batch_index + 1) * batch_size, x_preprocessed.shape[0]),\n )\n activations[begin:end] = activation_model([x_preprocessed[begin:end]], training=False).numpy()\n\n return activations\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. For TensorFlow, .ckpt is used.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(model={self._model}, nb_classes={self.nb_classes}, \"\n f\"input_shape={self._input_shape}, loss_object={self._loss_object}, optimizer={self.optimizer}, \"\n f\"train_step={self._train_step}, channels_first={self.channels_first}, clip_values={self.clip_values!r}, \"\n f\"preprocessing_defences={self.preprocessing_defences}, \"\n f\"postprocessing_defences={self.postprocessing_defences}, preprocessing={self.preprocessing})\"\n )\n\n return repr_\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/classification/xgboost.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `XGBoostClassifier` for XGBoost models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom copy import deepcopy\nimport json\nimport logging\nimport os\nimport pickle\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassifierDecisionTree\nfrom art.utils import to_categorical\nfrom art import config\n\nif TYPE_CHECKING:\n\n import xgboost\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n from art.metrics.verification_decisions_trees import LeafNode, Tree\n\nlogger = logging.getLogger(__name__)\n\n\nclass XGBoostClassifier(ClassifierDecisionTree):\n \"\"\"\n Class for importing XGBoost models.\n \"\"\"\n\n estimator_params = ClassifierDecisionTree.estimator_params + [\n \"nb_features\",\n ]\n\n def __init__(\n self,\n model: \"xgboost.Booster\" | \"xgboost.XGBClassifier\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n nb_features: int | None = None,\n nb_classes: int | None = None,\n ) -> None:\n \"\"\"\n Create a `Classifier` instance from a XGBoost model.\n\n :param model: XGBoost model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param nb_features: The number of features in the training data. Only used if it cannot be extracted from\n model.\n :param nb_classes: The number of classes in the training data. Only used if it cannot be extracted from model.\n \"\"\"\n from xgboost import Booster, XGBClassifier\n\n if not isinstance(model, Booster) and not isinstance(model, XGBClassifier):\n raise TypeError(\"Model must be of type xgboost.Booster or xgboost.XGBClassifier.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._input_shape = (nb_features,)\n _nb_classes = self._get_nb_classes(nb_classes)\n if _nb_classes is not None:\n self._nb_classes = _nb_classes\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def nb_features(self) -> int:\n \"\"\"\n Return the number of features.\n\n :return: The number of features.\n \"\"\"\n return self._input_shape[0] # type: ignore\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`. Only supported for models of type XGBClassifier.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes).\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit` function in `xgboost.XGBClassifier` and will be passed to this function as such.\n :raises `NotImplementedException`: This method is not supported for Booster objects.\n \"\"\"\n import xgboost\n\n if isinstance(self._model, xgboost.XGBClassifier):\n self._model.fit(x, y, **kwargs)\n _nb_classes = self._get_nb_classes(self._nb_classes)\n if _nb_classes is not None:\n self._nb_classes = _nb_classes\n else:\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n import xgboost\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n if isinstance(self._model, xgboost.Booster):\n train_data = xgboost.DMatrix(x_preprocessed, label=None)\n y_prediction = self._model.predict(train_data)\n if len(y_prediction.shape) == 1:\n y_prediction = to_categorical(labels=y_prediction, nb_classes=self.nb_classes)\n elif isinstance(self._model, xgboost.XGBClassifier):\n y_prediction = self._model.predict_proba(x_preprocessed)\n else:\n raise ValueError(\"Type of model not recognized.\")\n\n # Apply postprocessing\n y_prediction = self._apply_postprocessing(preds=y_prediction, fit=False)\n\n return y_prediction\n\n def clone_for_refitting(\n self,\n ) -> \"XGBoostClassifier\":\n \"\"\"\n Create a copy of the estimator that can be refit from scratch. Only supported for models of type XGBClassifier.\n\n :return: new estimator.\n :raises `NotImplementedError`: This method is not supported for Booster objects.\n \"\"\"\n import xgboost\n\n if isinstance(self._model, xgboost.XGBClassifier):\n params = self.get_params()\n del params[\"model\"]\n internal_params = self._model.get_params()\n new_classifier = xgboost.XGBClassifier()\n new_classifier.set_params(**internal_params)\n new_estimator = XGBoostClassifier(new_classifier)\n new_estimator.set_params(**params)\n return new_estimator\n\n raise NotImplementedError\n\n def _get_nb_classes(self, nb_classes: int | None) -> int | None:\n \"\"\"\n Return the number of output classes.\n\n :return: Number of classes in the data.\n \"\"\"\n from xgboost import Booster, XGBClassifier\n\n try:\n if isinstance(self._model, Booster):\n return int(len(self._model.get_dump(dump_format=\"json\")) / self._model.n_estimators) # type: ignore\n if isinstance(self._model, XGBClassifier):\n return self._model.n_classes_\n except AttributeError:\n # Attribute n_classes_ not found, will return default nb_classes value\n pass\n\n if nb_classes is not None:\n return nb_classes\n return None\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder): # pragma: no cover\n os.makedirs(folder)\n\n with open(full_path + \".pickle\", \"wb\") as file_pickle:\n pickle.dump(self._model, file=file_pickle)\n\n def get_trees(self) -> list[\"Tree\"]:\n \"\"\"\n Get the decision trees.\n\n :return: A list of decision trees.\n \"\"\"\n from art.metrics.verification_decisions_trees import Box, Tree\n\n booster_dump = self._model.get_booster().get_dump(dump_format=\"json\")\n trees = []\n\n for i_tree, tree_dump in enumerate(booster_dump):\n box = Box()\n\n if self._model.n_classes_ == 2:\n class_label = -1\n else:\n class_label = i_tree % self._model.n_classes_\n\n tree_json = json.loads(tree_dump)\n trees.append(\n Tree(\n class_id=class_label,\n leaf_nodes=self._get_leaf_nodes(tree_json, i_tree, class_label, box),\n )\n )\n\n return trees\n\n def _get_leaf_nodes(self, node, i_tree, class_label, box) -> list[\"LeafNode\"]:\n from art.metrics.verification_decisions_trees import LeafNode, Box, Interval\n\n leaf_nodes: list[LeafNode] = []\n\n if \"children\" in node:\n if node[\"children\"][0][\"nodeid\"] == node[\"yes\"] and node[\"children\"][1][\"nodeid\"] == node[\"no\"]:\n node_left = node[\"children\"][0]\n node_right = node[\"children\"][1]\n elif node[\"children\"][1][\"nodeid\"] == node[\"yes\"] and node[\"children\"][0][\"nodeid\"] == node[\"no\"]:\n node_left = node[\"children\"][1]\n node_right = node[\"children\"][0]\n else:\n raise ValueError\n\n box_left = deepcopy(box)\n box_right = deepcopy(box)\n\n feature = int(node[\"split\"][1:])\n box_split_left = Box(intervals={feature: Interval(-np.inf, node[\"split_condition\"])})\n box_split_right = Box(intervals={feature: Interval(node[\"split_condition\"], np.inf)})\n\n if box.intervals:\n box_left.intersect_with_box(box_split_left)\n box_right.intersect_with_box(box_split_right)\n else:\n box_left = box_split_left\n box_right = box_split_right\n\n leaf_nodes += self._get_leaf_nodes(node_left, i_tree, class_label, box_left)\n leaf_nodes += self._get_leaf_nodes(node_right, i_tree, class_label, box_right)\n\n if \"leaf\" in node:\n leaf_nodes.append(\n LeafNode(\n tree_id=i_tree,\n class_label=class_label,\n node_id=node[\"nodeid\"],\n box=box,\n value=node[\"leaf\"],\n )\n )\n\n return leaf_nodes\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/gan/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nGAN Estimator API.\n\"\"\"\n\nfrom art.estimators.gan.tensorflow import TensorFlowV2GAN\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/gan/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module creates GANs using the TensorFlow ML Framework\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, GENERATOR_TYPE\n import tensorflow as tf\n\n\nclass TensorFlowV2GAN(TensorFlowV2Estimator):\n \"\"\"\n This class implements a GAN with the TensorFlow v2 framework.\n \"\"\"\n\n def __init__(\n self,\n generator: \"GENERATOR_TYPE\",\n discriminator: \"CLASSIFIER_TYPE\",\n generator_loss=None,\n discriminator_loss=None,\n generator_optimizer_fct=None,\n discriminator_optimizer_fct=None,\n ):\n \"\"\"\n Initialization of a test TensorFlow v2 GAN\n\n :param generator: a TensorFlow2 generator\n :param discriminator: a TensorFlow v2 discriminator\n :param generator_loss: the loss function to use for the generator\n :param discriminator_loss: the loss function to use for the discriminator\n :param generator_optimizer_fct: the optimizer function to use for the generator\n :param discriminator_optimizer_fct: the optimizer function to use for the discriminator\n \"\"\"\n super().__init__(model=None, clip_values=None, channels_first=None)\n self._generator = generator\n self._discriminator_classifier = discriminator\n self._generator_loss = generator_loss\n self._generator_optimizer_fct = generator_optimizer_fct\n self._discriminator_loss = discriminator_loss\n self._discriminator_optimizer_fct = discriminator_optimizer_fct\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Generates a sample.\n\n :param x: An input seed.\n :param batch_size: The batch size for predictions.\n :return: The generated sample.\n \"\"\"\n return self.generator.predict(x, batch_size=batch_size, **kwargs)\n\n @property\n def input_shape(self) -> tuple[int, int]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return 1, 100\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Creates a generative model\n\n :param x: The secret backdoor trigger that will produce the target.\n :param y: The target to produce when using the trigger.\n :param batch_size: batch_size of images used to train generator.\n :param nb_epochs: total number of iterations for performing the attack.\n \"\"\"\n import tensorflow as tf\n\n z_trigger = x\n for _ in range(nb_epochs):\n train_imgs = kwargs.get(\"images\")\n train_set = (\n tf.data.Dataset.from_tensor_slices(train_imgs)\n .shuffle(train_imgs.shape[0]) # type: ignore\n .batch(batch_size)\n )\n\n for images_batch in train_set:\n # generating noise from a normal distribution\n noise = tf.random.normal([images_batch.shape[0], z_trigger.shape[1]])\n\n with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n generated_images = self.generator.model(noise, training=True)\n real_output = self.discriminator.model(images_batch, training=True) # type: ignore\n\n generated_output = self.discriminator.model(generated_images, training=True) # type: ignore\n\n gen_loss = self._generator_loss(generated_output)\n disc_loss = self._discriminator_loss(real_output, generated_output)\n\n gradients_of_generator = gen_tape.gradient(gen_loss, self.generator.model.variables)\n gradients_of_discriminator = disc_tape.gradient(\n disc_loss, self.discriminator.model.variables # type: ignore\n )\n\n self.generator_optimizer_fct.apply_gradients(\n zip(gradients_of_generator, self.estimator.model.trainable_variables) # type: ignore\n )\n self.discriminator_optimizer_fct.apply_gradients(\n zip(gradients_of_discriminator, self.discriminator.model.variables) # type: ignore\n )\n\n @property\n def generator(self) -> \"GENERATOR_TYPE\":\n \"\"\"\n :return: the generator\n \"\"\"\n return self._generator\n\n @property\n def discriminator(self) -> \"CLASSIFIER_TYPE\":\n \"\"\"\n :return: the discriminator\n \"\"\"\n return self._discriminator_classifier\n\n @property\n def generator_loss(self) -> \"tf.Tensor\":\n \"\"\"\n :return: the loss fct used for the generator\n \"\"\"\n return self._generator_loss\n\n @property\n def generator_optimizer_fct(self) -> \"tf.Tensor\":\n \"\"\"\n :return: the optimizer function for the generator\n \"\"\"\n return self._generator_optimizer_fct\n\n @property\n def discriminator_loss(self) -> \"tf.Tensor\":\n \"\"\"\n :return: the loss fct used for the discriminator\n \"\"\"\n return self._discriminator_loss\n\n @property\n def discriminator_optimizer_fct(self) -> \"tf.Tensor\":\n \"\"\"\n :return: the optimizer function for the discriminator\n \"\"\"\n return self._discriminator_optimizer_fct\n\n def loss_gradient(self, x, y, **kwargs):\n raise NotImplementedError\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/generation/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nGenerator API.\n\"\"\"\n\nfrom art.estimators.generation.generator import GeneratorMixin\n\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/generation/generator.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements mixin abstract base classes defining properties for all generators in ART.\n\"\"\"\nfrom __future__ import annotations\n\nimport abc\n\n\nclass GeneratorMixin(abc.ABC):\n \"\"\"\n Mixin abstract base class defining functionality for generators.\n \"\"\"\n\n @property\n @abc.abstractmethod\n def encoding_length(self) -> int:\n \"\"\"\n Returns the length of the encoding size output.\n\n :return: The length of the encoding size output.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/generation/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `TensorFlowGenerator` for TensorFlow models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\nfrom art.estimators.generation.generator import GeneratorMixin\n\nif TYPE_CHECKING:\n\n import tensorflow.compat.v1 as tf\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2Generator(GeneratorMixin, TensorFlowV2Estimator):\n \"\"\"\n This class implements a DGM with the TensorFlow framework.\n \"\"\"\n\n estimator_params = TensorFlowV2Estimator.estimator_params + [\n \"encoding_length\",\n ]\n\n def __init__(\n self,\n encoding_length: int,\n model: \"tf.Tensor\",\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ):\n \"\"\"\n Initialization specific to TensorFlow generator implementations.\n\n :param encoding_length: length of the input seed\n :param model: TensorFlow model, neural network or other.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range\n of all features. If arrays are provided, each value will be considered the bound for a\n feature, thus the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input\n will then be divided by the second one.\n \"\"\"\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._encoding_length = encoding_length\n\n @property\n def model(self) -> \"tf.Tensor\":\n \"\"\"\n :return: The generator tensor.\n \"\"\"\n return self._model\n\n @property\n def encoding_length(self) -> int:\n \"\"\"\n :return: The length of the encoding size output.\n \"\"\"\n return self._encoding_length\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform projections over a batch of encodings.\n\n :param x: Encodings.\n :param batch_size: Batch size.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of prediction projections of shape `(num_inputs, nb_classes)`.\n \"\"\"\n # Run prediction with batch processing\n results_list = []\n num_batch = int(np.ceil(len(x) / float(batch_size)))\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x.shape[0]),\n )\n\n # Run prediction\n results_list.append(self._model(x[begin:end], training=training_mode).numpy())\n\n results = np.vstack(results_list)\n\n return results\n\n def loss_gradient(self, x, y, **kwargs) -> np.ndarray:\n raise NotImplementedError\n\n def fit(self, x, y, batch_size=128, nb_epochs=10, **kwargs):\n \"\"\"\n Do nothing.\n \"\"\"\n raise NotImplementedError\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n \"\"\"\n Do nothing.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule containing estimators for object detection.\n\"\"\"\n\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\n\nfrom art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\nfrom art.estimators.object_detection.pytorch_faster_rcnn import PyTorchFasterRCNN\nfrom art.estimators.object_detection.pytorch_yolo import PyTorchYolo\nfrom art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\nfrom art.estimators.object_detection.pytorch_detection_transformer import PyTorchDetectionTransformer\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/detr.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Copyright 2020 - present, Facebook, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nUtility methods for DEtection TRansformer (DETR) in PyTorch.\n\n | Paper link: https://arxiv.org/abs/2005.12872\n\n Changes/differences to original code:\n - Line 209: add device\n - Line 243: remove reference to box_ops import\n - Line 327: remove check for distributed computing\n - Line 391: add device\n - Lines 456-7: remove copy_()\n - Line 459: returning original tensor list\n - Line 462: function name changed to distinguish that it now facilitates gradients\n\"\"\"\nfrom __future__ import annotations\n\nimport torch\n\n\nclass NestedTensor:\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/util/misc.py)\n \"\"\"\n\n def __init__(self, tensors, mask: \"torch.Tensor\" | None):\n self.tensors = tensors\n self.mask = mask\n\n def to_device(self, device: \"torch.device\"):\n \"\"\"\n Transfer to device\n \"\"\"\n cast_tensor = self.tensors.to(device)\n mask = self.mask\n if mask is not None:\n assert mask is not None\n cast_mask = mask.to(device)\n else:\n cast_mask = None\n return NestedTensor(cast_tensor, cast_mask)\n\n def decompose(self):\n \"\"\"\n Return tensors and masks\n \"\"\"\n return self.tensors, self.mask\n\n def __repr__(self):\n return str(self.tensors)\n\n\nclass HungarianMatcher(torch.nn.Module):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/models/matcher.py)\n \"\"\"\n\n def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1):\n \"\"\"Creates the matcher\n Params:\n cost_class: This is the relative weight of the classification error\n in the matching cost\n cost_bbox: This is the relative weight of the L1 error\n of the bounding box coordinates in the matching cost\n cost_giou: This is the relative weight of the giou loss of the\n bounding box in the matching cost\n \"\"\"\n super().__init__()\n self.cost_class = cost_class\n self.cost_bbox = cost_bbox\n self.cost_giou = cost_giou\n assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, \"all costs cant be 0\"\n\n def forward(self, outputs, targets):\n \"\"\"Performs the matching\n Params:\n outputs: This is a dict that contains at least these entries:\n \"pred_logits\": Tensor of dim [batch_size, num_queries, num_classes]\n with the classification logits\n \"pred_boxes\": Tensor of dim [batch_size, num_queries, 4]\n with the predicted box coordinates\n targets: This is a list of targets (len(targets) = batch_size),\n where each target is a dict containing:\n \"labels\": Tensor of dim [num_target_boxes] (where num_target_boxes\n is the number of ground-truth\n objects in the target) containing the class labels\n \"boxes\": Tensor of dim [num_target_boxes, 4] containing the target box coordinates\n Returns:\n A list of size batch_size, containing tuples of (index_i, index_j) where:\n - index_i is the indices of the selected predictions (in order)\n - index_j is the indices of the corresponding selected targets (in order)\n For each batch element, it holds:\n len(index_i) = len(index_j) = min(num_queries, num_target_boxes)\n \"\"\"\n from scipy.optimize import linear_sum_assignment\n\n batch_size, num_queries = outputs[\"pred_logits\"].shape[:2]\n\n # We flatten to compute the cost matrices in a batch\n out_prob = outputs[\"pred_logits\"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes]\n out_bbox = outputs[\"pred_boxes\"].flatten(0, 1) # [batch_size * num_queries, 4]\n\n # Also concat the target labels and boxes\n tgt_ids = torch.cat([v[\"labels\"] for v in targets])\n tgt_bbox = torch.cat([v[\"boxes\"] for v in targets])\n\n # Compute the classification cost. Contrary to the loss, we don't use the NLL,\n # but approximate it in 1 - proba[target class].\n # The 1 is a constant that doesn't change the matching, it can be omitted.\n cost_class = -out_prob[:, tgt_ids]\n\n # Compute the L1 cost between boxes\n cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)\n\n # Compute the giou cost between boxes\n cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))\n\n # Final cost matrix\n cost_matrix = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou\n cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu()\n\n sizes = [len(v[\"boxes\"]) for v in targets]\n indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))]\n return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\n\nclass SetCriterion(torch.nn.Module):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/models/detr.py)\n \"\"\"\n\n def __init__(self, num_classes, matcher, weight_dict, eos_coef, losses):\n \"\"\"Create the criterion.\n Parameters:\n num_classes: number of object categories, omitting the special no-object category\n matcher: module able to compute a matching between targets and proposals\n weight_dict: dict containing as key the names of the losses and as values their relative weight.\n eos_coef: relative classification weight applied to the no-object category\n losses: list of all the losses to be applied. See get_loss for list of available losses.\n \"\"\"\n\n super().__init__()\n self.num_classes = num_classes\n self.matcher = matcher\n self.weight_dict = weight_dict\n self.eos_coef = eos_coef\n self.losses = losses\n empty_weight = torch.ones(self.num_classes + 1)\n empty_weight[-1] = self.eos_coef\n self.register_buffer(\"empty_weight\", empty_weight)\n\n @staticmethod\n def dice_loss(inputs, targets, num_boxes):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/models/segmentation.py)\n \"\"\"\n inputs = inputs.sigmoid()\n inputs = inputs.flatten(1)\n numerator = 2 * (inputs * targets).sum(1)\n denominator = inputs.sum(-1) + targets.sum(-1)\n loss = 1 - (numerator + 1) / (denominator + 1)\n return loss.sum() / num_boxes\n\n @staticmethod\n def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/models/segmentation.py)\n \"\"\"\n\n prob = inputs.sigmoid()\n ce_loss = torch.nn.functional.binary_cross_entropy_with_logits(inputs, targets, reduction=\"none\")\n p_t = prob * targets + (1 - prob) * (1 - targets)\n loss = ce_loss * ((1 - p_t) ** gamma)\n\n if alpha >= 0:\n alpha_t = alpha * targets + (1 - alpha) * (1 - targets)\n loss = alpha_t * loss\n\n return loss.mean(1).sum() / num_boxes\n\n def loss_labels(self, outputs, targets, indices):\n \"\"\"Classification loss (NLL)\n targets dicts must contain the key \"labels\" containing a tensor of dim [nb_target_boxes]\n \"\"\"\n\n src_logits = outputs[\"pred_logits\"]\n\n idx = self._get_src_permutation_idx(indices)\n target_classes_o = torch.cat([t[\"labels\"][J] for t, (_, J) in zip(targets, indices)])\n target_classes = torch.full(src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device)\n target_classes[idx] = target_classes_o\n\n loss_ce = torch.nn.functional.cross_entropy(\n src_logits.transpose(1, 2), target_classes, self.empty_weight.to(src_logits.device)\n )\n losses = {\"loss_ce\": loss_ce}\n return losses\n\n @staticmethod\n def loss_cardinality(outputs, targets):\n \"\"\"Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes\n This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients\n \"\"\"\n\n pred_logits = outputs[\"pred_logits\"]\n device = pred_logits.device\n tgt_lengths = torch.as_tensor([len(v[\"labels\"]) for v in targets], device=device)\n card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)\n card_err = torch.nn.functional.l1_loss(card_pred.float(), tgt_lengths.float())\n losses = {\"cardinality_error\": card_err}\n return losses\n\n def loss_boxes(self, outputs, targets, indices, num_boxes):\n \"\"\"Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss\n targets dicts must contain the key \"boxes\" containing a tensor of dim [nb_target_boxes, 4]\n The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.\n \"\"\"\n\n idx = self._get_src_permutation_idx(indices)\n src_boxes = outputs[\"pred_boxes\"][idx]\n target_boxes = torch.cat([t[\"boxes\"][i] for t, (_, i) in zip(targets, indices)], dim=0)\n\n loss_bbox = torch.nn.functional.l1_loss(src_boxes, target_boxes, reduction=\"none\")\n\n losses = {}\n losses[\"loss_bbox\"] = loss_bbox.sum() / num_boxes\n\n loss_giou = 1 - torch.diag(generalized_box_iou(box_cxcywh_to_xyxy(src_boxes), box_cxcywh_to_xyxy(target_boxes)))\n losses[\"loss_giou\"] = loss_giou.sum() / num_boxes\n return losses\n\n def loss_masks(self, outputs, targets, indices, num_boxes):\n \"\"\"Compute the losses related to the masks: the focal loss and the dice loss.\n targets dicts must contain the key \"masks\" containing a tensor of dim [nb_target_boxes, h, w]\n \"\"\"\n import torchvision\n\n src_idx = self._get_src_permutation_idx(indices)\n tgt_idx = self._get_tgt_permutation_idx(indices)\n src_masks = outputs[\"pred_masks\"]\n src_masks = src_masks[src_idx]\n masks = [t[\"masks\"] for t in targets]\n target_masks, _ = nested_tensor_from_tensor_list(masks).decompose()\n target_masks = target_masks.to_device(src_masks)\n target_masks = target_masks[tgt_idx]\n\n src_masks = torchvision.ops.misc.interpolate(\n src_masks[:, None], size=target_masks.shape[-2:], mode=\"bilinear\", align_corners=False\n )\n src_masks = src_masks[:, 0].flatten(1)\n\n target_masks = target_masks.flatten(1)\n target_masks = target_masks.view(src_masks.shape)\n losses = {\n \"loss_mask\": self.sigmoid_focal_loss(src_masks, target_masks, num_boxes),\n \"loss_dice\": self.dice_loss(src_masks, target_masks, num_boxes),\n }\n return losses\n\n @staticmethod\n def _get_src_permutation_idx(indices):\n \"\"\"\n permute predictions following indices\n \"\"\"\n\n batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])\n src_idx = torch.cat([src for (src, _) in indices])\n return batch_idx, src_idx\n\n @staticmethod\n def _get_tgt_permutation_idx(indices):\n \"\"\"\n permute targets following indices\n \"\"\"\n\n batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])\n tgt_idx = torch.cat([tgt for (_, tgt) in indices])\n return batch_idx, tgt_idx\n\n def get_loss(self, loss, outputs, targets, indices, num_boxes):\n \"\"\"\n Get the Hungarian Loss\n \"\"\"\n if loss == \"labels\":\n return self.loss_labels(outputs, targets, indices)\n if loss == \"cardinality\":\n with torch.no_grad():\n return self.loss_cardinality(outputs, targets)\n if loss == \"boxes\":\n return self.loss_boxes(outputs, targets, indices, num_boxes)\n if loss == \"masks\":\n return self.loss_masks(outputs, targets, indices, num_boxes)\n raise ValueError(\"No loss selected.\")\n\n def forward(self, outputs, targets):\n \"\"\"This performs the loss computation.\n Parameters:\n outputs: dict of tensors, see the output specification of the model for the format\n targets: list of dicts, such that len(targets) == batch_size.\n The expected keys in each dict depends on the losses applied, see each loss' doc\n \"\"\"\n\n outputs_without_aux = {k: v for k, v in outputs.items() if k != \"aux_outputs\"}\n\n # Retrieve the matching between the outputs of the last layer and the targets\n with torch.no_grad():\n indices = self.matcher(outputs_without_aux, targets)\n\n # Compute the average number of target boxes across all nodes, for normalization purposes\n num_boxes = sum(len(t[\"labels\"]) for t in targets)\n num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)\n num_boxes = torch.clamp(num_boxes, min=1).item()\n\n # Compute all the requested losses\n losses = {}\n for loss in self.losses:\n losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))\n\n # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.\n if \"aux_outputs\" in outputs:\n for i, aux_outputs in enumerate(outputs[\"aux_outputs\"]):\n with torch.no_grad():\n indices = self.matcher(aux_outputs, targets)\n for loss in self.losses:\n\n l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes)\n l_dict = {k + f\"_{i}\": v for k, v in l_dict.items()}\n losses.update(l_dict)\n\n return losses\n\n\ndef box_cxcywh_to_xyxy(x: \"torch.Tensor\"):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/util/box_ops.py)\n \"\"\"\n\n x_c, y_c, width, height = x.unbind(1)\n box = [(x_c - 0.5 * width), (y_c - 0.5 * height), (x_c + 0.5 * width), (y_c + 0.5 * height)]\n return torch.stack(box, dim=1)\n\n\ndef box_xyxy_to_cxcywh(x: \"torch.Tensor\"):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/util/box_ops.py)\n \"\"\"\n\n x_0, y_0, x_1, y_1 = x.unbind(-1)\n box = [(x_0 + x_1) / 2, (y_0 + y_1) / 2, (x_1 - x_0), (y_1 - y_0)]\n return torch.stack(box, dim=-1)\n\n\ndef rescale_bboxes(out_bbox: \"torch.Tensor\", size: tuple[int, int]):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (inference notebook)\n \"\"\"\n\n img_w, img_h = size\n box = box_cxcywh_to_xyxy(out_bbox)\n box = box * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32)\n return box\n\n\ndef revert_rescale_bboxes(out_bbox: \"torch.Tensor\", size: tuple[int, int]):\n \"\"\"\n Adapted from DETR source: https://github.com/facebookresearch/detr\n (inference notebook)\n\n This method reverts bounding box rescaling to match input image size\n \"\"\"\n\n img_w, img_h = size\n box = out_bbox / torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32).to(out_bbox.device)\n box = box_xyxy_to_cxcywh(box)\n return box\n\n\ndef box_iou(boxes1: \"torch.Tensor\", boxes2: \"torch.Tensor\"):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/util/box_ops.py)\n \"\"\"\n from torchvision.ops.boxes import box_area\n\n area1 = box_area(boxes1)\n area2 = box_area(boxes2)\n\n l_t = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]\n r_b = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]\n\n w_h = (r_b - l_t).clamp(min=0) # [N,M,2]\n inter = w_h[:, :, 0] * w_h[:, :, 1] # [N,M]\n\n union = area1[:, None] + area2 - inter\n\n iou = inter / union\n return iou, union\n\n\ndef generalized_box_iou(boxes1: \"torch.Tensor\", boxes2: \"torch.Tensor\"):\n \"\"\"\n From DETR source: https://github.com/facebookresearch/detr\n (detr/util/box_ops.py)\n \"\"\"\n\n assert (boxes1[:, 2:] >= boxes1[:, :2]).all()\n assert (boxes2[:, 2:] >= boxes2[:, :2]).all()\n iou, union = box_iou(boxes1, boxes2)\n\n l_t = torch.min(boxes1[:, None, :2], boxes2[:, :2])\n r_b = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])\n\n w_h = (r_b - l_t).clamp(min=0) # [N,M,2]\n area = w_h[:, :, 0] * w_h[:, :, 1]\n\n return iou - (area - union) / area\n\n\ndef nested_tensor_from_tensor_list(tensor_list: list | \"torch.Tensor\"):\n \"\"\"\n Adapted from DETR source: https://github.com/facebookresearch/detr\n (detr/util/misc.py)\n \"\"\"\n\n if tensor_list[0].ndim == 3:\n img_shape_list = [list(img.shape) for img in tensor_list]\n max_size = img_shape_list[0]\n for sublist in img_shape_list[1:]:\n for index, item in enumerate(sublist):\n max_size[index] = max(max_size[index], item)\n batch_shape = [len(tensor_list)] + max_size\n batch, _, _, width = batch_shape\n dtype = tensor_list[0].dtype\n device = tensor_list[0].device\n tensor = torch.zeros(batch_shape, dtype=dtype, device=device)\n mask = torch.ones((batch, batch, width), dtype=torch.bool, device=device)\n for img, _, m in zip(tensor_list, tensor, mask):\n m[: img.shape[1], : img.shape[2]] = False\n else:\n raise ValueError(\"not supported\")\n return NestedTensor(tensor_list, mask)\n\n\ndef grad_enabled_forward(self, samples: NestedTensor):\n \"\"\"\n Adapted from DETR source: https://github.com/facebookresearch/detr\n (detr/models/detr.py)\n \"\"\"\n\n if isinstance(samples, (list, torch.Tensor)):\n samples = nested_tensor_from_tensor_list(samples)\n features, pos = self.backbone(samples)\n src, mask = features[-1].decompose()\n assert mask is not None\n h_s = self.transformer(self.input_proj(src), mask, self.query_embed.weight, pos[-1])[0]\n outputs_class = self.class_embed(h_s)\n outputs_coord = self.bbox_embed(h_s).sigmoid()\n out = {\"pred_logits\": outputs_class[-1], \"pred_boxes\": outputs_coord[-1]}\n if self.aux_loss:\n out[\"aux_outputs\"] = self._set_aux_loss(outputs_class, outputs_coord)\n return out\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/object_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements mixin abstract base class for all object detectors in ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\n\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import LossGradientsMixin\n\n\nclass ObjectDetectorMixin(ABC):\n \"\"\"\n Mix-in Base class for ART object detectors.\n \"\"\"\n\n @property\n @abstractmethod\n def native_label_is_pytorch_format(self) -> bool:\n \"\"\"\n Are the native labels in PyTorch format [x1, y1, x2, y2]?\n \"\"\"\n raise NotImplementedError\n\n\nclass ObjectDetector(ObjectDetectorMixin, LossGradientsMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/pytorch_detection_transformer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for DEtection TRansformer (DETR) in PyTorch.\n\n| Paper link: https://arxiv.org/abs/2005.12872\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.defences.postprocessor.postprocessor import Postprocessor\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchDetectionTransformer(PyTorchObjectDetector):\n \"\"\"\n This class implements a model-specific object detector using DEtection TRansformer (DETR)\n and PyTorch following the input and output formats of torchvision.\n\n | Paper link: https://arxiv.org/abs/2005.12872\n \"\"\"\n\n def __init__(\n self,\n model: \"torch.nn.Module\" | None = None,\n input_shape: tuple[int, ...] = (3, 800, 800),\n optimizer: \"torch.optim.Optimizer\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool = True,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n attack_losses: tuple[str, ...] = (\n \"loss_ce\",\n \"loss_bbox\",\n \"loss_giou\",\n ),\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Initialization.\n\n :param model: DETR model. The output of the model is `list[dict[str, torch.Tensor]]`, one for each input\n image. The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores of each prediction.\n :param input_shape: Tuple of the form `(height, width)` of ints representing input image height and width.\n :param optimizer: The optimizer for training the classifier.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the estimator.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the estimator.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param attack_losses: Tuple of any combination of strings of loss components: 'loss_ce', 'loss_bbox', and\n 'loss_giou'.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n \"\"\"\n import torch\n from art.estimators.object_detection.detr import HungarianMatcher, SetCriterion, grad_enabled_forward\n\n if model is None: # pragma: no cover\n model = torch.hub.load(\"facebookresearch/detr\", \"detr_resnet50\", pretrained=True)\n\n func_type = type(model.forward)\n model.forward = func_type(grad_enabled_forward, model) # type: ignore\n\n super().__init__(\n model=model,\n input_shape=input_shape,\n optimizer=optimizer,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n attack_losses=attack_losses,\n device_type=device_type,\n )\n\n cost_class = 1.0\n cost_bbox = 5.0\n cost_giou = 2.0\n bbox_loss_coef = 5.0\n giou_loss_coef = 2.0\n eos_coef = 0.1\n num_classes = 91\n matcher = HungarianMatcher(cost_class=cost_class, cost_bbox=cost_bbox, cost_giou=cost_giou)\n losses = [\"labels\", \"boxes\", \"cardinality\"]\n\n self.weight_dict = {\"loss_ce\": 1, \"loss_bbox\": bbox_loss_coef, \"loss_giou\": giou_loss_coef}\n self.criterion = SetCriterion(\n num_classes, matcher=matcher, weight_dict=self.weight_dict, eos_coef=eos_coef, losses=losses\n )\n\n def _translate_labels(self, labels: list[dict[str, \"torch.Tensor\"]]) -> list[dict[str, \"torch.Tensor\"]]:\n \"\"\"\n Translate object detection labels from ART format (torchvision) to the model format (DETR) and\n move tensors to GPU, if applicable.\n\n :param labels: Object detection labels in format x1y1x2y2 (torchvision).\n :return: Object detection labels in format xcycwh (DETR).\n \"\"\"\n from art.estimators.object_detection.detr import revert_rescale_bboxes\n\n if self.channels_first:\n height = self.input_shape[1]\n width = self.input_shape[2]\n else:\n height = self.input_shape[0]\n width = self.input_shape[1]\n\n labels_translated: list[dict[str, \"torch.Tensor\"]] = []\n\n for label_dict in labels:\n label_dict_translated = {}\n\n boxes = revert_rescale_bboxes(label_dict[\"boxes\"], (height, width))\n label_dict_translated[\"boxes\"] = boxes.to(self.device)\n\n label = label_dict[\"labels\"]\n label_dict_translated[\"labels\"] = label.to(self.device)\n\n if \"scores\" in label_dict:\n scores = label_dict[\"scores\"]\n label_dict_translated[\"scores\"] = scores.to(self.device)\n\n labels_translated.append(label_dict_translated)\n\n return labels_translated\n\n def _translate_predictions(self, predictions: dict[str, \"torch.Tensor\"]) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Translate object detection predictions from the model format (DETR) to ART format (torchvision) and\n convert tensors to numpy arrays.\n\n :param predictions: Object detection labels in format xcycwh (DETR).\n :return: Object detection labels in format x1y1x2y2 (torchvision).\n \"\"\"\n from art.estimators.object_detection.detr import rescale_bboxes\n\n if self.channels_first:\n height = self.input_shape[1]\n width = self.input_shape[2]\n else:\n height = self.input_shape[0]\n width = self.input_shape[1]\n\n pred_boxes = predictions[\"pred_boxes\"]\n pred_logits = predictions[\"pred_logits\"]\n\n predictions_x1y1x2y2: list[dict[str, np.ndarray]] = []\n\n for pred_box, pred_logit in zip(pred_boxes, pred_logits):\n boxes = rescale_bboxes(pred_box.detach().cpu(), (height, width)).numpy()\n labels = pred_logit.unsqueeze(0).softmax(-1)[0, :, :-1].max(dim=1)[1].detach().cpu().numpy()\n scores = pred_logit.unsqueeze(0).softmax(-1)[0, :, :-1].max(dim=1)[0].detach().cpu().numpy()\n\n pred_dict = {\n \"boxes\": boxes,\n \"labels\": labels,\n \"scores\": scores,\n }\n\n predictions_x1y1x2y2.append(pred_dict)\n\n return predictions_x1y1x2y2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/pytorch_faster_rcnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for Faster R-CNN v3 in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1506.01497\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\n\nif TYPE_CHECKING:\n\n import torch\n import torchvision\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchFasterRCNN(PyTorchObjectDetector):\n \"\"\"\n This class implements a model-specific object detector using Faster R-CNN and PyTorch following the input and output\n formats of torchvision.\n\n | Paper link: https://arxiv.org/abs/1506.01497\n \"\"\"\n\n def __init__(\n self,\n model: \"torchvision.models.detection.FasterRCNN\" | None = None,\n input_shape: tuple[int, ...] = (-1, -1, -1),\n optimizer: \"torch.optim.Optimizer\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool = True,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n attack_losses: tuple[str, ...] = (\n \"loss_classifier\",\n \"loss_box_reg\",\n \"loss_objectness\",\n \"loss_rpn_box_reg\",\n ),\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Initialization.\n\n :param model: Faster R-CNN model. The output of the model is `list[dict[str, torch.Tensor]]`, one for\n each input image. The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores of each prediction.\n :param input_shape: The shape of one input sample.\n :param optimizer: The optimizer for training the classifier.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param attack_losses: Tuple of any combination of strings of loss components: 'loss_classifier', 'loss_box_reg',\n 'loss_objectness', and 'loss_rpn_box_reg'.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n \"\"\"\n import torchvision\n from torchvision.models import ResNet50_Weights\n from torchvision.models.detection import FasterRCNN_ResNet50_FPN_Weights\n\n if model is None: # pragma: no cover\n model = torchvision.models.detection.fasterrcnn_resnet50_fpn(\n weights=FasterRCNN_ResNet50_FPN_Weights.COCO_V1,\n progress=True,\n num_classes=91,\n weights_backbone=ResNet50_Weights.IMAGENET1K_V1,\n )\n\n super().__init__(\n model=model,\n input_shape=input_shape,\n optimizer=optimizer,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n attack_losses=attack_losses,\n device_type=device_type,\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/pytorch_object_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for PyTorch object detectors.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom packaging.version import parse\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\nfrom art.estimators.object_detection.utils import cast_inputs_to_pt\nfrom art.estimators.pytorch import PyTorchEstimator\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchObjectDetector(ObjectDetectorMixin, PyTorchEstimator):\n \"\"\"\n This module implements the task specific estimator for PyTorch object detection models following the input and\n output formats of torchvision.\n \"\"\"\n\n estimator_params = PyTorchEstimator.estimator_params + [\"input_shape\", \"optimizer\", \"attack_losses\"]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n input_shape: tuple[int, ...] = (-1, -1, -1),\n optimizer: \"torch.optim.Optimizer\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool = True,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n attack_losses: tuple[str, ...] = (\n \"loss_classifier\",\n \"loss_box_reg\",\n \"loss_objectness\",\n \"loss_rpn_box_reg\",\n ),\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Initialization.\n\n :param model: Object detection model. The output of the model is `list[dict[str, torch.Tensor]]`, one for\n each input image. The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores of each prediction.\n :param input_shape: The shape of one input sample.\n :param optimizer: The optimizer for training the classifier.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param attack_losses: Tuple of any combination of strings of loss components: 'loss_classifier', 'loss_box_reg',\n 'loss_objectness', and 'loss_rpn_box_reg'.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n \"\"\"\n import torch\n import torchvision\n\n torch_version = list(parse(torch.__version__.lower()).release)\n torchvision_version = list(parse(torchvision.__version__.lower()).release)\n assert not (torch_version[0] == 1 and (torch_version[1] == 8 or torch_version[1] == 9)), (\n \"PyTorchObjectDetector does not support torch==1.8 and torch==1.9 because of \"\n \"https://github.com/pytorch/vision/issues/4153. Support will return for torch==1.10.\"\n )\n assert not (torchvision_version[0] == 0 and (torchvision_version[1] == 9 or torchvision_version[1] == 10)), (\n \"PyTorchObjectDetector does not support torchvision==0.9 and torchvision==0.10 because of \"\n \"https://github.com/pytorch/vision/issues/4153. Support will return for torchvision==0.11.\"\n )\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n\n self._input_shape = input_shape\n self._optimizer = optimizer\n self._attack_losses = attack_losses\n\n # Parameters used for subclasses\n self.weight_dict: dict[str, float] | None = None\n self.criterion: torch.nn.Module | None = None\n\n if self.clip_values is not None:\n if self.clip_values[0] != 0:\n raise ValueError(\"This classifier requires un-normalized input images with clip_vales=(0, max_value).\")\n if self.clip_values[1] <= 0: # pragma: no cover\n raise ValueError(\"This classifier requires un-normalized input images with clip_vales=(0, max_value).\")\n\n if self.postprocessing_defences is not None:\n raise ValueError(\"This estimator does not support `postprocessing_defences`.\")\n\n self._model: torch.nn.Module\n self._model.to(self._device)\n self._model.eval()\n\n @property\n def native_label_is_pytorch_format(self) -> bool:\n \"\"\"\n Are the native labels in PyTorch format [x1, y1, x2, y2]?\n \"\"\"\n return True\n\n @property\n def model(self) -> \"torch.nn.Module\":\n return self._model\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape\n\n @property\n def optimizer(self) -> \"torch.optim.Optimizer\" | None:\n \"\"\"\n Return the optimizer.\n\n :return: The optimizer.\n \"\"\"\n return self._optimizer\n\n @property\n def attack_losses(self) -> tuple[str, ...]:\n \"\"\"\n Return the combination of strings of the loss components.\n\n :return: The combination of strings of the loss components.\n \"\"\"\n return self._attack_losses\n\n @property\n def device(self) -> \"torch.device\":\n \"\"\"\n Get current used device.\n\n :return: Current used device.\n \"\"\"\n return self._device\n\n def _preprocess_and_convert_inputs(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: list[dict[str, np.ndarray | \"torch.Tensor\"]] | None = None,\n fit: bool = False,\n no_grad: bool = True,\n ) -> tuple[\"torch.Tensor\", list[dict[str, \"torch.Tensor\"]]]:\n \"\"\"\n Apply preprocessing on inputs `(x, y)` and convert to tensors, if needed.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, np.ndarray | torch.Tensor]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :param fit: `True` if the function is call before fit/training and `False` if the function is called before a\n predict operation.\n :param no_grad: `True` if no gradients required.\n :return: Preprocessed inputs `(x, y)` as tensors.\n \"\"\"\n import torch\n\n if self.clip_values is not None:\n norm_factor = self.clip_values[1]\n else:\n norm_factor = 1.0\n\n if self.all_framework_preprocessing:\n # Convert samples into tensor\n x_tensor, y_tensor = cast_inputs_to_pt(x, y)\n\n if not self.channels_first:\n x_tensor = torch.permute(x_tensor, (0, 3, 1, 2))\n x_tensor = x_tensor / norm_factor # type: ignore\n\n # Set gradients\n if not no_grad:\n if x_tensor.is_leaf:\n x_tensor.requires_grad = True\n else:\n x_tensor.retain_grad()\n\n # Apply framework-specific preprocessing\n x_preprocessed_tensor, y_preprocessed_tensor = self._apply_preprocessing(\n x=x_tensor, y=y_tensor, fit=fit, no_grad=no_grad\n )\n\n elif isinstance(x, np.ndarray):\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x=x, y=y, fit=fit, no_grad=no_grad)\n\n # Convert inputs into tensor\n x_preprocessed_tensor, y_preprocessed_tensor = cast_inputs_to_pt(x_preprocessed, y_preprocessed)\n\n if not self.channels_first:\n x_preprocessed_tensor = torch.permute(x_preprocessed_tensor, (0, 3, 1, 2))\n x_preprocessed_tensor = x_preprocessed_tensor / torch.tensor(norm_factor, device=self.device)\n\n # Set gradients\n if not no_grad:\n x_preprocessed_tensor.requires_grad = True\n\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n return x_preprocessed_tensor, y_preprocessed_tensor\n\n def _translate_labels(self, labels: list[dict[str, \"torch.Tensor\"]]) -> Any:\n \"\"\"\n Translate object detection labels from ART format (torchvision) to the model format (torchvision) and\n move tensors to GPU, if applicable.\n\n :param labels: Object detection labels in format x1y1x2y2 (torchvision).\n :return: Object detection labels in format x1y1x2y2 (torchvision).\n \"\"\"\n labels_translated = [{k: v.to(self.device) for k, v in y_i.items()} for y_i in labels]\n return labels_translated\n\n def _translate_predictions(self, predictions: Any) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Translate object detection predictions from the model format (torchvision) to ART format (torchvision) and\n convert tensors to numpy arrays.\n\n :param predictions: Object detection predictions in format x1y1x2y2 (torchvision).\n :return: Object detection predictions in format x1y1x2y2 (torchvision).\n \"\"\"\n predictions_x1y1x2y2: list[dict[str, np.ndarray]] = []\n for pred in predictions:\n prediction = {}\n\n prediction[\"boxes\"] = pred[\"boxes\"].detach().cpu().numpy()\n prediction[\"labels\"] = pred[\"labels\"].detach().cpu().numpy()\n prediction[\"scores\"] = pred[\"scores\"].detach().cpu().numpy()\n if \"masks\" in pred:\n prediction[\"masks\"] = pred[\"masks\"].detach().cpu().numpy().squeeze()\n\n predictions_x1y1x2y2.append(prediction)\n\n return predictions_x1y1x2y2\n\n def _get_losses(\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]]\n ) -> tuple[dict[str, \"torch.Tensor\"], \"torch.Tensor\"]:\n \"\"\"\n Get the loss tensor output of the model including all preprocessing.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Loss components and gradients of the input `x`.\n \"\"\"\n self._model.train()\n\n self.set_dropout(False)\n self.set_batchnorm(False)\n self.set_multihead_attention(False)\n\n # Apply preprocessing and convert to tensors\n x_preprocessed, y_preprocessed = self._preprocess_and_convert_inputs(x=x, y=y, fit=False, no_grad=False)\n\n # Move inputs to device\n x_preprocessed = x_preprocessed.to(self.device)\n y_preprocessed = self._translate_labels(y_preprocessed)\n\n # Set gradients again after inputs are moved to another device\n if x_preprocessed.is_leaf:\n x_preprocessed.requires_grad = True\n else:\n x_preprocessed.retain_grad()\n\n if self.criterion is None:\n loss_components = self._model(x_preprocessed, y_preprocessed)\n else:\n outputs = self._model(x_preprocessed)\n loss_components = self.criterion(outputs, y_preprocessed)\n\n return loss_components, x_preprocessed\n\n def loss_gradient(\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]], **kwargs\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Loss gradients of the same shape as `x`.\n \"\"\"\n import torch\n\n loss_components, x_grad = self._get_losses(x=x, y=y)\n\n # Compute the loss\n if self.weight_dict is None:\n loss = sum(loss_components[loss_name] for loss_name in self.attack_losses if loss_name in loss_components)\n else:\n loss = sum(\n loss_component * self.weight_dict[loss_name]\n for loss_name, loss_component in loss_components.items()\n if loss_name in self.weight_dict\n )\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n loss.backward(retain_graph=True) # type: ignore\n\n grads: torch.Tensor | np.ndarray\n\n if x_grad.grad is not None:\n if isinstance(x, np.ndarray):\n grads = x_grad.grad.cpu().numpy()\n else:\n grads = x_grad.grad.clone()\n else:\n raise ValueError(\"Gradient term in PyTorch model is `None`.\")\n\n if self.clip_values is not None:\n grads = grads / self.clip_values[1]\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n if not self.channels_first:\n if isinstance(x, np.ndarray):\n grads = np.transpose(grads, (0, 2, 3, 1))\n elif isinstance(grads, torch.Tensor):\n # grads_tensor: torch.Tensor = grads\n grads = torch.permute(grads, (0, 2, 3, 1))\n\n assert grads.shape == x.shape\n\n return grads\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape NCHW or NHWC.\n :param batch_size: Batch size.\n :return: Predictions of format `list[dict[str, np.ndarray]]`, one for each input image. The fields of the dict\n are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores or each prediction.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model to evaluation mode\n self._model.eval()\n\n # Apply preprocessing and convert to tensors\n x_preprocessed, _ = self._preprocess_and_convert_inputs(x=x, y=None, fit=False, no_grad=True)\n\n # Create dataloader\n dataset = TensorDataset(x_preprocessed)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=False)\n\n predictions: list[dict[str, np.ndarray]] = []\n for (x_batch,) in dataloader:\n # Move inputs to device\n x_batch = x_batch.to(self._device)\n\n # Run prediction\n with torch.no_grad():\n outputs = self._model(x_batch)\n\n predictions_x1y1x2y2 = self._translate_predictions(outputs)\n predictions.extend(predictions_x1y1x2y2)\n\n return predictions\n\n def fit(\n self,\n x: np.ndarray,\n y: list[dict[str, np.ndarray | \"torch.Tensor\"]],\n batch_size: int = 128,\n nb_epochs: int = 10,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from torch.utils.data import Dataset, DataLoader\n\n # Set model to train mode\n self._model.train()\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n # Apply preprocessing and convert to tensors\n x_preprocessed, y_preprocessed = self._preprocess_and_convert_inputs(x=x, y=y, fit=True, no_grad=True)\n\n class ObjectDetectionDataset(Dataset):\n \"\"\"\n Object detection dataset in PyTorch.\n \"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, idx):\n return self.x[idx], self.y[idx]\n\n # Create dataloader\n dataset = ObjectDetectionDataset(x_preprocessed, y_preprocessed)\n dataloader = DataLoader(\n dataset=dataset,\n batch_size=batch_size,\n shuffle=True,\n drop_last=drop_last,\n collate_fn=lambda batch: list(zip(*batch)),\n )\n\n # Start training\n for _ in range(nb_epochs):\n # Train for one epoch\n for x_batch, y_batch in dataloader:\n # Move inputs to device\n x_batch = torch.stack(x_batch).to(self.device)\n y_batch = self._translate_labels(y_batch)\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Get the loss components\n if self.criterion is None:\n loss_components = self._model(x_batch, y_batch)\n else:\n outputs = self._model(x_batch)\n loss_components = self.criterion(outputs, y_batch)\n\n # Form the loss tensor\n if self.weight_dict is None:\n loss = sum(\n loss_components[loss_name] for loss_name in self.attack_losses if loss_name in loss_components\n )\n else:\n loss = sum(\n loss_component * self.weight_dict[loss_name]\n for loss_name, loss_component in loss_components.items()\n if loss_name in self.weight_dict\n )\n\n # Do training\n loss.backward() # type: ignore\n self._optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n raise NotImplementedError\n\n def compute_losses(\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]]\n ) -> dict[str, np.ndarray]:\n \"\"\"\n Compute all loss components.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Dictionary of loss components.\n \"\"\"\n loss_components, _ = self._get_losses(x=x, y=y)\n output = {}\n for key, value in loss_components.items():\n if key in self.attack_losses:\n output[key] = value.detach().cpu().numpy()\n return output\n\n def compute_loss( # type: ignore\n self, x: np.ndarray | \"torch.Tensor\", y: list[dict[str, np.ndarray | \"torch.Tensor\"]], **kwargs\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Loss.\n \"\"\"\n import torch\n\n loss_components, _ = self._get_losses(x=x, y=y)\n\n # Compute the loss\n if self.weight_dict is None:\n loss = sum(loss_components[loss_name] for loss_name in self.attack_losses if loss_name in loss_components)\n else:\n loss = sum(\n loss_component * self.weight_dict[loss_name]\n for loss_name, loss_component in loss_components.items()\n if loss_name in self.weight_dict\n )\n\n assert isinstance(loss, torch.Tensor)\n\n if isinstance(x, torch.Tensor):\n return loss\n\n return loss.detach().cpu().numpy()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/pytorch_yolo.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for PyTorch YOLO v3, v5, v8+ object detectors.\n\n| Paper link: https://arxiv.org/abs/1804.02767\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchYolo(PyTorchObjectDetector):\n \"\"\"\n This module implements the model- and task specific estimator for YOLO object detector models in PyTorch.\n\n | Paper link: https://arxiv.org/abs/1804.02767\n \"\"\"\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n input_shape: tuple[int, ...] = (3, 416, 416),\n optimizer: \"torch.optim.Optimizer\" | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool = True,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n attack_losses: tuple[str, ...] = (\n \"loss_classifier\",\n \"loss_box_reg\",\n \"loss_objectness\",\n \"loss_rpn_box_reg\",\n ),\n device_type: str = \"gpu\",\n is_ultralytics: bool = False,\n model_name: str | None = None,\n ):\n \"\"\"\n Initialization.\n\n :param model: YOLO v3, v5, or v8+ model wrapped as demonstrated in examples/get_started_yolo.py.\n The output of the model is `list[dict[str, torch.Tensor]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n - scores [N]: the scores of each prediction.\n :param input_shape: The shape of one input sample.\n :param optimizer: The optimizer for training the classifier.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param attack_losses: Tuple of any combination of strings of loss components: 'loss_classifier', 'loss_box_reg',\n 'loss_objectness', and 'loss_rpn_box_reg'.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n :param model_name: The name of the model (e.g., 'yolov8n', 'yolov10n') for determining loss function.\n \"\"\"\n if is_ultralytics:\n from art.estimators.object_detection.pytorch_yolo_loss_wrapper import PyTorchYoloLossWrapper\n\n model = PyTorchYoloLossWrapper(model, model_name)\n\n super().__init__(\n model=model,\n input_shape=input_shape,\n optimizer=optimizer,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n attack_losses=attack_losses,\n device_type=device_type,\n )\n\n def _translate_labels(self, labels: list[dict[str, \"torch.Tensor\"]]) -> \"torch.Tensor\":\n \"\"\"\n Translate object detection labels from ART format (torchvision) to the model format (YOLO) and\n move tensors to GPU, if applicable.\n\n :param labels: Object detection labels in format x1y1x2y2 (torchvision).\n :return: Object detection labels in format xcycwh (YOLO).\n \"\"\"\n import torch\n\n if self.channels_first:\n height = self.input_shape[1]\n width = self.input_shape[2]\n else:\n height = self.input_shape[0]\n width = self.input_shape[1]\n\n labels_xcycwh_list = []\n\n for i, label_dict in enumerate(labels):\n # create 2D tensor to encode labels and bounding boxes\n label_xcycwh = torch.zeros(len(label_dict[\"boxes\"]), 6, device=self.device)\n label_xcycwh[:, 0] = i\n label_xcycwh[:, 1] = label_dict[\"labels\"]\n label_xcycwh[:, 2:6] = label_dict[\"boxes\"]\n\n # normalize bounding boxes to [0, 1]\n label_xcycwh[:, 2:6:2] /= width\n label_xcycwh[:, 3:6:2] /= height\n\n # convert from x1y1x2y2 to xcycwh\n label_xcycwh[:, 4] -= label_xcycwh[:, 2]\n label_xcycwh[:, 5] -= label_xcycwh[:, 3]\n label_xcycwh[:, 2] += label_xcycwh[:, 4] / 2\n label_xcycwh[:, 3] += label_xcycwh[:, 5] / 2\n labels_xcycwh_list.append(label_xcycwh)\n\n labels_xcycwh = torch.vstack(labels_xcycwh_list)\n return labels_xcycwh\n\n def _translate_predictions(self, predictions: \"torch.Tensor\") -> list[dict[str, np.ndarray]]:\n \"\"\"\n Translate object detection predictions from the model format (YOLO) to ART format (torchvision) and\n convert tensors to numpy arrays.\n\n :param predictions: Object detection labels in format xcycwh (YOLO) or list of dicts (YOLO v8+).\n :return: Object detection labels in format x1y1x2y2 (torchvision).\n \"\"\"\n import torch\n\n predictions_x1y1x2y2: list[dict[str, np.ndarray]] = []\n\n # Handle YOLO v8+ predictions (list of dicts)\n if isinstance(predictions, list) and len(predictions) > 0 and isinstance(predictions[0], dict):\n for pred in predictions:\n prediction = {}\n prediction[\"boxes\"] = pred[\"boxes\"].detach().cpu().numpy()\n prediction[\"labels\"] = pred[\"labels\"].detach().cpu().numpy()\n prediction[\"scores\"] = pred[\"scores\"].detach().cpu().numpy()\n predictions_x1y1x2y2.append(prediction)\n return predictions_x1y1x2y2\n\n # Handle traditional YOLO predictions (tensor format)\n if self.channels_first:\n height = self.input_shape[1]\n width = self.input_shape[2]\n else:\n height = self.input_shape[0]\n width = self.input_shape[1]\n\n for pred in predictions:\n boxes = torch.vstack(\n [\n torch.maximum((pred[:, 0] - pred[:, 2] / 2), torch.tensor(0, device=self.device)),\n torch.maximum((pred[:, 1] - pred[:, 3] / 2), torch.tensor(0, device=self.device)),\n torch.minimum((pred[:, 0] + pred[:, 2] / 2), torch.tensor(height, device=self.device)),\n torch.minimum((pred[:, 1] + pred[:, 3] / 2), torch.tensor(width, device=self.device)),\n ]\n ).permute((1, 0))\n labels = torch.argmax(pred[:, 5:], dim=1)\n scores = pred[:, 4]\n\n pred_dict = {\n \"boxes\": boxes.detach().cpu().numpy(),\n \"labels\": labels.detach().cpu().numpy(),\n \"scores\": scores.detach().cpu().numpy(),\n }\n\n predictions_x1y1x2y2.append(pred_dict)\n\n return predictions_x1y1x2y2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/pytorch_yolo_loss_wrapper.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2025\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nPyTorch-specific YOLO loss wrapper for ART for yolo versions 8 and above.\n\"\"\"\n\nimport torch\n\n\nclass PyTorchYoloLossWrapper(torch.nn.Module):\n \"\"\"Wrapper for YOLO v8+ models to handle loss dict format.\"\"\"\n\n def __init__(self, model, name):\n super().__init__()\n self.model = model\n try:\n from ultralytics.models.yolo.detect import DetectionPredictor\n from ultralytics.utils.loss import v8DetectionLoss, E2EDetectLoss\n\n self.detection_predictor = DetectionPredictor()\n self.model.args = self.detection_predictor.args\n if \"v10\" in name:\n self.model.criterion = E2EDetectLoss(model)\n else:\n self.model.criterion = v8DetectionLoss(model)\n except ImportError as e:\n raise ImportError(\"The 'ultralytics' package is required for YOLO v8+ models but not installed.\") from e\n\n def forward(self, x, targets=None):\n \"\"\"Transforms the target to dict expected by model.loss\"\"\"\n if self.training:\n if targets is None:\n raise ValueError(\"Targets should not be None when training.\")\n items = {}\n items[\"batch_idx\"] = targets[:, 0]\n items[\"bboxes\"] = targets[:, 2:6]\n items[\"cls\"] = targets[:, 1]\n items[\"img\"] = x\n loss, loss_components = self.model.loss(items)\n loss_components_dict = {\"loss_total\": loss.sum()}\n loss_components_dict[\"loss_box\"] = loss_components[0].sum()\n loss_components_dict[\"loss_cls\"] = loss_components[1].sum()\n loss_components_dict[\"loss_dfl\"] = loss_components[2].sum()\n return loss_components_dict\n else:\n preds = self.model(x)\n self.detection_predictor.model = self.model\n self.detection_predictor.batch = [x]\n preds = self.detection_predictor.postprocess(preds, x, x)\n items = []\n for pred in preds:\n items.append(\n {\"boxes\": pred.boxes.xyxy, \"scores\": pred.boxes.conf, \"labels\": pred.boxes.cls.type(torch.int)}\n )\n return items\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/tensorflow_v2_faster_rcnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for Faster R-CNN in TensorFlowV2.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\nfrom art.utils import get_file\nfrom art import config\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n from object_detection.meta_architectures.faster_rcnn_meta_arch import FasterRCNNMetaArch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass TensorFlowV2FasterRCNN(ObjectDetectorMixin, TensorFlowV2Estimator):\n \"\"\"\n This class implements a model-specific object detector using Faster-RCNN and TensorFlowV2.\n \"\"\"\n\n estimator_params = TensorFlowV2Estimator.estimator_params + [\"images\", \"is_training\", \"attack_losses\"]\n\n def __init__(\n self,\n input_shape: tuple[int, ...],\n model: \"FasterRCNNMetaArch\" | None = None,\n filename: str | None = None,\n url: str | None = None,\n is_training: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool = False,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n attack_losses: tuple[str, ...] = (\n \"Loss/RPNLoss/localization_loss\",\n \"Loss/RPNLoss/objectness_loss\",\n \"Loss/BoxClassifierLoss/localization_loss\",\n \"Loss/BoxClassifierLoss/classification_loss\",\n ),\n ):\n \"\"\"\n Initialization of an instance TensorFlowV2FasterRCNN.\n\n :param input_shape: A tuple indicating input shape in form (height, width, channels)\n :param model: A TensorFlowV2 Faster-RCNN model. The output that can be computed from the model includes a tuple\n of (predictions, losses, detections):\n - predictions: a dictionary holding \"raw\" prediction tensors.\n - losses: a dictionary mapping loss keys (`Loss/RPNLoss/localization_loss`,\n `Loss/RPNLoss/objectness_loss`, `Loss/BoxClassifierLoss/localization_loss`,\n `Loss/BoxClassifierLoss/classification_loss`) to scalar tensors representing\n corresponding loss values.\n - detections: a dictionary containing final detection results.\n :param filename: Filename of the detection model without filename extension.\n :param url: URL to download archive of detection model including filename extension.\n :param is_training: A boolean indicating whether the training version of the computation graph should be\n constructed.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for input image features. If floats are provided, these will be\n used as the range of all features. If arrays are provided, each value will be considered\n the bound for a feature, thus the shape of clip values needs to match the total number\n of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtractor, divider)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The\n input will then be divided by the second one.\n :param attack_losses: Tuple of any combination of strings of the following loss components:\n `first_stage_localization_loss`, `first_stage_objectness_loss`,\n `second_stage_localization_loss`, `second_stage_classification_loss`.\n \"\"\"\n\n # Load model\n if model is None:\n # If model is None, then we need to have parameters filename and url to download, extract and load the\n # object detection model\n if filename is None or url is None:\n filename, url = (\n \"faster_rcnn_resnet50_v1_640x640_coco17_tpu-8\",\n \"http://download.tensorflow.org/models/object_detection/tf2/20200711/\"\n \"faster_rcnn_resnet50_v1_640x640_coco17_tpu-8.tar.gz\",\n )\n\n model = self._load_model(filename=filename, url=url, is_training=is_training)\n\n # Super initialization\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n # Check clip values\n if self.clip_values is not None:\n if not np.all(self.clip_values[0] == 0):\n raise ValueError(\"This estimator supports input images with clip_vales=(0, 255).\")\n if not np.all(self.clip_values[1] == 255): # pragma: no cover\n raise ValueError(\"This estimator supports input images with clip_vales=(0, 255).\")\n\n # Check preprocessing and postprocessing defences\n if self.preprocessing_defences is not None:\n raise ValueError(\"This estimator does not support `preprocessing_defences`.\")\n if self.postprocessing_defences is not None:\n raise ValueError(\"This estimator does not support `postprocessing_defences`.\")\n\n # Save new attributes\n self._input_shape: tuple[int, ...] = input_shape\n self._detections: list[dict[str, np.ndarray]] = []\n self._predictions: list[np.ndarray] = []\n self._losses: dict[str, np.ndarray] = {}\n self.is_training: bool = is_training\n self.attack_losses: tuple[str, ...] = attack_losses\n\n @property\n def native_label_is_pytorch_format(self) -> bool:\n \"\"\"\n Are the native labels in PyTorch format [x1, y1, x2, y2]?\n \"\"\"\n return False\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape\n\n @staticmethod\n def _load_model(\n filename: str | None = None,\n url: str | None = None,\n is_training: bool = False,\n ) -> tuple[dict[str, \"tf.Tensor\"], ...]:\n \"\"\"\n Download, extract and load a model from a URL if it is not already in the cache. The file indicated by `url`\n is downloaded to the path ~/.art/data and given the name `filename`. Files in tar, tar.gz, tar.bz, and zip\n formats will also be extracted. Then the model is loaded, pipelined and its outputs are returned as a tuple\n of (predictions, losses, detections).\n\n :param filename: Name of the file.\n :param url: Download URL.\n :param is_training: A boolean indicating whether the training version of the computation graph should be\n constructed.\n :return: the object detection model restored from checkpoint\n \"\"\"\n import tensorflow as tf\n\n from object_detection.utils import config_util\n from object_detection.builders import model_builder\n\n # If obj_detection_model is None, then we need to have parameters filename and url to download, extract\n # and load the object detection model\n if filename is None or url is None: # pragma: no cover\n raise ValueError(\n \"Need input parameters `filename` and `url` to download, \"\n \"extract and load the object detection model.\"\n )\n\n # Download and extract\n path = get_file(filename=filename, path=config.ART_DATA_PATH, url=url, extract=True)\n # Load model config\n pipeline_config = path + \"/pipeline.config\"\n configs = config_util.get_configs_from_pipeline_file(pipeline_config)\n configs[\"model\"].faster_rcnn.second_stage_batch_size = configs[\"model\"].faster_rcnn.first_stage_max_proposals\n\n # Load model\n obj_detection_model = model_builder.build(\n model_config=configs[\"model\"], is_training=is_training, add_summaries=False\n )\n\n # Restore checkpoint\n ckpt = tf.compat.v2.train.Checkpoint(model=obj_detection_model)\n ckpt.restore(path + \"/checkpoint/ckpt-0\").expect_partial()\n\n return obj_detection_model\n\n def loss_gradient(\n self, x: np.ndarray, y: list[dict[str, np.ndarray]], standardise_output: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples of shape (nb_samples, height, width, nb_channels).\n :param y: Targets of format `list[dict[str, np.ndarray]]`, one for each input image. The fields of the dict are\n as follows:\n\n - boxes [N, 4]: the boxes in [y1, x1, y2, x2] in scale [0, 1] (`standardise_output=False`) or\n [x1, y1, x2, y2] in image scale (`standardise_output=True`) format,\n with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image in TensorFlow (`standardise_output=False`) or PyTorch\n (`standardise_output=True`) format\n\n :param standardise_output: True if `y` is provided in standardised PyTorch format. Box coordinates will be\n scaled back to [0, 1], label index will be decreased by 1 and the boxes will be\n changed from [x1, y1, x2, y2] to [y1, x1, y2, x2] format, with\n 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n :return: Loss gradients of the same shape as `x`.\n \"\"\"\n import tensorflow as tf\n\n # Only do loss_gradient if is_training is False\n if self.is_training:\n raise NotImplementedError(\n \"This object detector was loaded in training mode and therefore not support loss_gradient.\"\n )\n\n if standardise_output:\n from art.estimators.object_detection.utils import convert_pt_to_tf\n\n y = convert_pt_to_tf(y=y, height=x.shape[1], width=x.shape[2])\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n groundtruth_boxes_list = [tf.convert_to_tensor(y[i][\"boxes\"]) for i in range(x.shape[0])]\n\n groundtruth_classes_list = [\n tf.one_hot(groundtruth_class, self._model.num_classes, on_value=1.0, off_value=0.0)\n for groundtruth_class in [tf.convert_to_tensor(y[i][\"labels\"]) for i in range(x.shape[0])]\n ]\n\n groundtruth_weights_list = [[1] * len(y[i][\"labels\"]) for i in range(x.shape[0])]\n\n self._model.provide_groundtruth(\n groundtruth_boxes_list=groundtruth_boxes_list,\n groundtruth_classes_list=groundtruth_classes_list,\n groundtruth_weights_list=groundtruth_weights_list,\n )\n\n with tf.GradientTape() as tape:\n\n x_preprocessed = tf.convert_to_tensor(x_preprocessed)\n tape.watch(x_preprocessed)\n\n preprocessed_images, true_image_shapes = self._model.preprocess(x_preprocessed)\n predictions = self._model.predict(preprocessed_images, true_image_shapes)\n losses = self._model.loss(predictions, true_image_shapes)\n\n loss = None\n for loss_name in self.attack_losses:\n if loss is None:\n loss = losses[loss_name]\n else:\n loss = loss + losses[loss_name]\n\n grads = tape.gradient(loss, x_preprocessed)\n\n grads = self._apply_preprocessing_gradient(x, grads)\n assert grads.shape == x_preprocessed.shape\n\n return grads\n\n def predict(\n self, x: np.ndarray, batch_size: int = 128, standardise_output: bool = False, **kwargs\n ) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape (nb_samples, height, width, nb_channels).\n :param batch_size: Batch size.\n :param standardise_output: True if output should be standardised to PyTorch format. Box coordinates will be\n scaled from [0, 1] to image dimensions, label index will be increased by 1 to adhere\n to COCO categories and the boxes will be changed to [x1, y1, x2, y2] format, with\n 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n\n\n :return: Predictions of format `list[dict[str, np.ndarray]]`, one for each input image. The\n fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [y1, x1, y2, x2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n Can be changed to PyTorch format with `standardise_output=True`.\n - labels [N]: the labels for each image in TensorFlow format. Can be changed to PyTorch format with\n `standardise_output=True`.\n - scores [N]: the scores or each prediction.\n \"\"\"\n\n import tensorflow as tf\n\n # Only do prediction if is_training is False\n if self.is_training:\n raise NotImplementedError(\n \"This object detector was loaded in training mode and therefore does not support prediction.\"\n )\n\n # Apply preprocessing\n x, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run prediction with batch processing\n num_samples = x.shape[0]\n num_batch = int(np.ceil(num_samples / float(batch_size)))\n results = []\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = m * batch_size, min((m + 1) * batch_size, num_samples)\n\n preprocessed_images, true_image_shapes = self._model.preprocess(tf.convert_to_tensor(x[begin:end]))\n predictions = self._model.predict(preprocessed_images, true_image_shapes)\n batch_results = self._model.postprocess(predictions, true_image_shapes)\n\n for i in range(end - begin):\n d_sample = {}\n\n d_sample[\"boxes\"] = batch_results[\"detection_boxes\"][i].numpy()\n d_sample[\"labels\"] = batch_results[\"detection_classes\"][i].numpy().astype(np.int32)\n\n if standardise_output:\n from art.estimators.object_detection.utils import convert_tf_to_pt\n\n d_sample = convert_tf_to_pt(y=[d_sample], height=x.shape[1], width=x.shape[2])[0]\n\n d_sample[\"scores\"] = batch_results[\"detection_scores\"][i].numpy()\n\n results.append(d_sample)\n\n self._detections = results\n self._predictions = [i[\"scores\"] for i in results]\n\n return results\n\n @property\n def predictions(self) -> list[np.ndarray]:\n \"\"\"\n Get the `_predictions` attribute.\n\n :return: A dictionary holding \"raw\" prediction tensors.\n \"\"\"\n return self._predictions\n\n @property\n def losses(self) -> dict[str, np.ndarray]:\n \"\"\"\n Get the `_losses` attribute.\n\n :return: A dictionary mapping loss keys (`Loss/RPNLoss/localization_loss`, `Loss/RPNLoss/objectness_loss`,\n `Loss/BoxClassifierLoss/localization_loss`, `Loss/BoxClassifierLoss/classification_loss`) to scalar\n tensors representing corresponding loss values.\n \"\"\"\n return self._losses\n\n @property\n def detections(self) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Get the `_detections` attribute.\n\n :return: A dictionary containing final detection results.\n \"\"\"\n return self._detections\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n raise NotImplementedError\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Targets of format `list[dict[str, np.ndarray]]`, one for each input image. The fields of the dict are\n as follows:\n - boxes [N, 4]: the boxes in [y1, x1, y2, x2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image in TensorFlow format.\n - scores [N]: the scores or each prediction.\n :return: np.float32 representing total loss.\n \"\"\"\n\n import tensorflow as tf\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n x_preprocessed = tf.convert_to_tensor(x_preprocessed)\n\n groundtruth_boxes_list = [tf.convert_to_tensor(y[i][\"boxes\"]) for i in range(x.shape[0])]\n\n groundtruth_classes_list = [\n tf.one_hot(groundtruth_class, self._model.num_classes, on_value=1.0, off_value=0.0)\n for groundtruth_class in [tf.convert_to_tensor(y[i][\"labels\"]) for i in range(x.shape[0])]\n ]\n\n groundtruth_weights_list = [[1] * len(y[i][\"labels\"]) for i in range(x.shape[0])]\n\n self._model.provide_groundtruth(\n groundtruth_boxes_list=groundtruth_boxes_list,\n groundtruth_classes_list=groundtruth_classes_list,\n groundtruth_weights_list=groundtruth_weights_list,\n )\n\n preprocessed_images, true_image_shapes = self._model.preprocess(x_preprocessed)\n predictions = self._model.predict(preprocessed_images, true_image_shapes)\n losses = self._model.loss(predictions, true_image_shapes)\n\n loss = None\n for loss_name in self.attack_losses:\n if loss is None:\n loss = losses[loss_name].numpy()\n else:\n loss = loss + losses[loss_name].numpy()\n\n total_loss = np.array([loss])\n\n return total_loss\n\n def compute_losses(self, x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:\n \"\"\"\n Compute all loss components.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Targets of format `list[dict[str, np.ndarray]]`, one for each input image. The fields of the dict are\n as follows:\n - boxes [N, 4]: the boxes in [y1, x1, y2, x2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image in TensorFlow format.\n - scores [N]: the scores or each prediction.\n :return: Dictionary of loss components.\n \"\"\"\n\n import tensorflow as tf\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n x_preprocessed = tf.convert_to_tensor(x_preprocessed)\n\n groundtruth_boxes_list = [tf.convert_to_tensor(y[i][\"boxes\"]) for i in range(x.shape[0])]\n\n groundtruth_classes_list = [\n tf.one_hot(groundtruth_class, self._model.num_classes, on_value=1.0, off_value=0.0)\n for groundtruth_class in [tf.convert_to_tensor(y[i][\"labels\"]) for i in range(x.shape[0])]\n ]\n\n groundtruth_weights_list = [[1] * len(y[i][\"labels\"]) for i in range(x.shape[0])]\n\n self._model.provide_groundtruth(\n groundtruth_boxes_list=groundtruth_boxes_list,\n groundtruth_classes_list=groundtruth_classes_list,\n groundtruth_weights_list=groundtruth_weights_list,\n )\n\n preprocessed_images, true_image_shapes = self._model.preprocess(x_preprocessed)\n predictions = self._model.predict(preprocessed_images, true_image_shapes)\n losses = self._model.loss(predictions, true_image_shapes)\n\n for loss_name in self.attack_losses:\n self._losses[loss_name] = losses[loss_name].numpy()\n\n return self._losses\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_detection/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module contains utility functions for object detection.\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n\n import torch\n\n\ndef convert_tf_to_pt(y: list[dict[str, np.ndarray]], height: int, width: int) -> list[dict[str, np.ndarray]]:\n \"\"\"\n :param y: Target values of format `list[dict[Tensor]]`, one for each input image. The fields of the dict are as\n follows:\n\n - boxes (FloatTensor[N, 4]): the boxes in [y1, x1, y2, x2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H in scale [0, 1].\n - labels (Int64Tensor[N]): the labels for each image\n - scores (Tensor[N]): the scores or each prediction.\n :param height: Height of images in pixels.\n :param width: Width if images in pixels.\n\n :return: Target values of format `list[dict[Tensor]]`, one for each input image. The fields of the dict are as\n follows:\n\n - boxes (FloatTensor[N, 4]): the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H in image scale.\n - labels (Int64Tensor[N]): the labels for each image\n - scores (Tensor[N]): the scores or each prediction.\n \"\"\"\n for i, _ in enumerate(y):\n y[i][\"boxes\"][:, 0] *= height\n y[i][\"boxes\"][:, 1] *= width\n y[i][\"boxes\"][:, 2] *= height\n y[i][\"boxes\"][:, 3] *= width\n\n y[i][\"boxes\"] = y[i][\"boxes\"][:, [1, 0, 3, 2]]\n\n y[i][\"labels\"] = y[i][\"labels\"] + 1\n\n return y\n\n\ndef convert_pt_to_tf(y: list[dict[str, np.ndarray]], height: int, width: int) -> list[dict[str, np.ndarray]]:\n \"\"\"\n :param y: Target values of format `list[dict[Tensor]]`, one for each input image. The fields of the dict are as\n follows:\n\n - boxes (FloatTensor[N, 4]): the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H in image scale.\n - labels (Int64Tensor[N]): the labels for each image\n - scores (Tensor[N]): the scores or each prediction.\n :param height: Height of images in pixels.\n :param width: Width if images in pixels.\n\n :return: Target values of format `list[dict[Tensor]]`, one for each input image. The fields of the dict are as\n follows:\n\n - boxes (FloatTensor[N, 4]): the boxes in [y1, x1, y2, x2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H in scale [0, 1].\n - labels (Int64Tensor[N]): the labels for each image\n - scores (Tensor[N]): the scores or each prediction.\n \"\"\"\n for i, _ in enumerate(y):\n\n y[i][\"boxes\"][:, 0] /= width\n y[i][\"boxes\"][:, 1] /= height\n y[i][\"boxes\"][:, 2] /= width\n y[i][\"boxes\"][:, 3] /= height\n\n y[i][\"boxes\"] = y[i][\"boxes\"][:, [1, 0, 3, 2]]\n\n y[i][\"labels\"] = y[i][\"labels\"] - 1\n\n return y\n\n\ndef cast_inputs_to_pt(\n x: np.ndarray | \"torch.Tensor\",\n y: list[dict[str, np.ndarray | \"torch.Tensor\"]] | None = None,\n) -> tuple[\"torch.Tensor\", list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Cast object detection inputs `(x, y)` to PyTorch tensors.\n\n :param x: Samples of shape NCHW or NHWC.\n :param y: Target values of format `list[dict[str, Union[np.ndarray, torch.Tensor]]]`, one for each input image.\n The fields of the dict are as follows:\n\n - boxes [N, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n - labels [N]: the labels for each image.\n :return: Object detection inputs `(x, y)` as tensors.\n \"\"\"\n import torch\n\n # Convert images into tensor\n if isinstance(x, np.ndarray):\n x_tensor = torch.from_numpy(x)\n else:\n x_tensor = x\n\n y_tensor: list[dict[str, torch.Tensor]] | None = None\n\n # Convert labels into tensor\n if isinstance(y, list):\n y_tensor = []\n for y_i in y:\n y_t = {}\n\n if isinstance(y_i[\"boxes\"], np.ndarray):\n y_t[\"boxes\"] = torch.from_numpy(y_i[\"boxes\"]).to(dtype=torch.float32)\n else:\n y_t[\"boxes\"] = y_i[\"boxes\"]\n\n if isinstance(y_i[\"labels\"], np.ndarray):\n y_t[\"labels\"] = torch.from_numpy(y_i[\"labels\"]).to(dtype=torch.int64)\n else:\n y_t[\"labels\"] = y_i[\"labels\"]\n\n if \"masks\" in y_i:\n if isinstance(y_i[\"masks\"], np.ndarray):\n y_t[\"masks\"] = torch.from_numpy(y_i[\"masks\"]).to(dtype=torch.uint8)\n else:\n y_t[\"masks\"] = y_i[\"masks\"]\n\n y_tensor.append(y_t)\n elif isinstance(y, dict):\n y_tensor = []\n for i in range(len(y[\"boxes\"])):\n y_t = {}\n\n y_t[\"boxes\"] = y[\"boxes\"][i]\n y_t[\"labels\"] = y[\"labels\"][i]\n if \"masks\" in y:\n y_t[\"masks\"] = y[\"masks\"][i]\n\n y_tensor.append(y_t)\n else:\n y_tensor = y\n\n return x_tensor, y_tensor\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_tracking/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule containing estimators for object tracking.\n\"\"\"\n\nfrom art.estimators.object_tracking.object_tracker import ObjectTrackerMixin\n\nfrom art.estimators.object_tracking.pytorch_goturn import PyTorchGoturn\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_tracking/object_tracker.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements mixin abstract base class for all object trackers in ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\n\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import LossGradientsMixin\n\n\nclass ObjectTrackerMixin(ABC):\n \"\"\"\n Mix-in Base class for ART object trackers.\n \"\"\"\n\n @property\n @abstractmethod\n def native_label_is_pytorch_format(self) -> bool:\n \"\"\"\n Are the native labels in PyTorch format [x1, y1, x2, y2]?\n \"\"\"\n raise NotImplementedError\n\n\nclass ObjectTracker(ObjectTrackerMixin, LossGradientsMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n pass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/object_tracking/pytorch_goturn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2019 Nrupatunga\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# MIT License\n#\n# Copyright (c) 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for PyTorch GOTURN object tracker.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport time\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.object_tracking.object_tracker import ObjectTrackerMixin\nfrom art.estimators.pytorch import PyTorchEstimator\n\nif TYPE_CHECKING:\n\n import PIL\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.defences.postprocessor.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchGoturn(ObjectTrackerMixin, PyTorchEstimator):\n \"\"\"\n This module implements the task- and model-specific estimator for PyTorch GOTURN (object tracking).\n \"\"\"\n\n estimator_params = PyTorchEstimator.estimator_params + [\"attack_losses\"]\n\n def __init__(\n self,\n model,\n input_shape: tuple[int, ...],\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n channels_first: bool | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Initialization.\n\n :param model: GOTURN model.\n :param input_shape: Shape of one input sample as expected by the model, e.g. input_shape=(3, 227, 227).\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param channels_first: Set channels first or last.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n \"\"\"\n import torch\n\n # Set device\n self._device: torch.device\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self._device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self._device = torch.device(f\"cuda:{cuda_idx}\")\n\n model.to(self._device)\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n # got-10k toolkit\n # Tracker.__init__(self, name=\"PyTorchGoturn\", is_deterministic=True)\n self.name = \"PyTorchGoturn\"\n self.is_deterministic = True\n\n self._input_shape = input_shape\n\n if self.clip_values is not None:\n if self.clip_values[0] != 0: # pragma: no cover\n raise ValueError(\"This classifier requires un-normalized input images with clip_vales=(0, 255).\")\n if self.clip_values[1] not in [1, 255]: # pragma: no cover\n raise ValueError(\n \"This classifier requires un-normalized input images with clip_vales=(0, 1) or \"\n \"clip_vales=(0, 255).\"\n )\n\n if self.postprocessing_defences is not None: # pragma: no cover\n raise ValueError(\"This estimator does not support `postprocessing_defences`.\")\n\n self.attack_losses: tuple[str, ...] = (\"torch.nn.L1Loss\",)\n\n @property\n def native_label_is_pytorch_format(self) -> bool:\n \"\"\"\n Are the native labels in PyTorch format [x1, y1, x2, y2]?\n \"\"\"\n return True\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def device(self) -> \"torch.device\":\n \"\"\"\n Get current used device.\n\n :return: Current used device.\n \"\"\"\n return self._device\n\n def _get_losses(\n self,\n x: np.ndarray,\n y: list[dict[str, np.ndarray | \"torch.Tensor\"]],\n reduction: str = \"sum\",\n ) -> tuple[dict[str, \"torch.Tensor\" | int | list[\"torch.Tensor\"]], list[\"torch.Tensor\"], list[\"torch.Tensor\"]]:\n \"\"\"\n Get the loss tensor output of the model including all preprocessing.\n\n :param x: Samples of shape (nb_samples, nb_frames, height, width, nb_channels).\n :param y: Target values of format `list[dict[str, np.ndarray]]`, one dictionary for each input image. The keys\n of the dictionary are:\n\n - boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'sum'.\n 'none': no reduction will be applied.\n 'sum': the output will be summed.\n :return: Loss dictionary, list of input tensors, and list of gradient tensors.\n \"\"\"\n import torch\n\n self._model.train()\n\n # Apply preprocessing\n if self.all_framework_preprocessing:\n if isinstance(x, torch.Tensor):\n raise NotImplementedError\n\n if y is not None and isinstance(y[0][\"boxes\"], np.ndarray):\n y_tensor = []\n for i, y_i in enumerate(y):\n y_t = {}\n y_t[\"boxes\"] = torch.from_numpy(y_i[\"boxes\"]).float().to(self.device) # type: ignore\n y_tensor.append(y_t)\n else:\n y_tensor = y # type: ignore\n\n image_tensor_list_grad = []\n y_preprocessed = []\n inputs_t: list[\"torch.Tensor\"] = []\n\n for i in range(x.shape[0]):\n if self.clip_values is not None:\n x_grad = torch.from_numpy(x[i]).to(self.device).float()\n else:\n x_grad = torch.from_numpy(x[i]).to(self.device).float()\n x_grad.requires_grad = True\n image_tensor_list_grad.append(x_grad)\n x_grad_1 = torch.unsqueeze(x_grad, dim=0)\n x_preprocessed_i, y_preprocessed_i = self._apply_preprocessing(\n x_grad_1, y=[y_tensor[i]], fit=False, no_grad=False\n )\n x_preprocessed_i = torch.squeeze(x_preprocessed_i)\n y_preprocessed.append(y_preprocessed_i[0])\n inputs_t.append(x_preprocessed_i)\n\n elif isinstance(x, np.ndarray):\n raise NotImplementedError\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n labels_t = y_preprocessed # type: ignore\n\n if isinstance(y[0][\"boxes\"], np.ndarray):\n y_init = torch.from_numpy(y[0][\"boxes\"]).to(self.device)\n else:\n y_init = y[0][\"boxes\"]\n\n loss_list = []\n\n for i in range(x.shape[0]):\n x_i = inputs_t[i]\n y_pred = self._track(x=x_i, y_init=y_init[i])\n gt_bb = labels_t[i][\"boxes\"]\n loss = torch.nn.L1Loss(size_average=False)(y_pred.float(), gt_bb.float())\n loss_list.append(loss)\n\n loss_dict: dict[str, \"torch.Tensor\" | int | list[\"torch.Tensor\"]] = {}\n if reduction == \"sum\":\n loss_dict[\"torch.nn.L1Loss\"] = sum(loss_list)\n elif reduction == \"none\":\n loss_dict[\"torch.nn.L1Loss\"] = loss_list\n else:\n raise ValueError(\"Reduction not recognised.\")\n\n return loss_dict, inputs_t, image_tensor_list_grad\n\n def loss_gradient(self, x: np.ndarray, y: list[dict[str, np.ndarray | \"torch.Tensor\"]], **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples of shape (nb_samples, height, width, nb_channels).\n :param y: Target values of format `list[dict[Tensor]]`, one for each input image. The\n fields of the dict are as follows:\n\n - boxes (FloatTensor[N, 4]): the predicted boxes in [x1, y1, x2, y2] format, with values \\\n between 0 and H and 0 and W.\n - labels (Int64Tensor[N]): the predicted labels for each image.\n - scores (Tensor[N]): the scores or each prediction.\n :return: Loss gradients of the same shape as `x`.\n \"\"\"\n grad_list = []\n\n for i in range(x.shape[0]):\n\n x_i = x[[i]]\n y_i = [y[i]]\n\n output, _, image_tensor_list_grad = self._get_losses(x=x_i, y=y_i)\n\n # Compute the gradient and return\n loss: torch.Tensor | None = None\n\n for loss_name in self.attack_losses:\n val: Any = output[loss_name]\n if isinstance(val, list):\n val = torch.stack(val).sum() # Or sum(val)\n if loss is None:\n loss = val\n else:\n loss = loss + val\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n loss.backward(retain_graph=True) # type: ignore\n\n for img in image_tensor_list_grad:\n if img.grad is not None:\n gradients = img.grad.cpu().numpy().copy()\n else:\n gradients = None\n grad_list.append(gradients)\n\n grads = np.array(grad_list)\n\n if grads.shape[0] == 1:\n grads_ = np.empty(len(grads), dtype=object)\n grads_[:] = list(grads)\n grads = grads_\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n if x.dtype != object:\n grads = np.array([i for i in grads], dtype=x.dtype) # pylint: disable=unnecessary-comprehension\n assert grads.shape == x.shape and grads.dtype == x.dtype\n\n return grads\n\n def _preprocess(self, img: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Preprocess image before forward pass, this is the same preprocessing used during training, please refer to\n collate function in train.py for reference\n\n :param img: Single frame od shape (nb_samples, height, width, nb_channels).\n :return: Preprocessed frame.\n \"\"\"\n import torch\n from torch.nn.functional import interpolate\n\n from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n if self.preprocessing is not None and isinstance(self.preprocessing, StandardisationMeanStdPyTorch):\n mean_np = self.preprocessing.mean\n std_np = self.preprocessing.std\n else:\n mean_np = np.ones(shape=(3, 1, 1), dtype=float)\n std_np = np.ones(shape=(3, 1, 1), dtype=float)\n mean = torch.from_numpy(mean_np).reshape((3, 1, 1))\n std = torch.from_numpy(std_np).reshape((3, 1, 1))\n img = img.permute(2, 0, 1)\n img = img * std + mean\n img = torch.unsqueeze(img, dim=0)\n img = interpolate(img, size=(self.input_shape[1], self.input_shape[2]), mode=\"bicubic\")\n if self.clip_values is not None:\n img = torch.clamp(img, float(self.clip_values[0]), float(self.clip_values[1]))\n img = torch.squeeze(img)\n img = (img - mean) / std\n return img\n\n def _track_step(\n self, curr_frame: \"torch.Tensor\", prev_frame: \"torch.Tensor\", rect: \"torch.Tensor\"\n ) -> \"torch.Tensor\":\n \"\"\"\n Track current frame.\n\n :param curr_frame: Current frame.\n :param prev_frame: Previous frame.\n :return: bounding box of previous frame\n \"\"\"\n import torch\n\n prev_bbox = rect\n\n k_context_factor = 2\n\n def compute_output_height_f(bbox_tight: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute height of search/target region.\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :return: Output height.\n \"\"\"\n bbox_height = bbox_tight[3] - bbox_tight[1]\n output_height = k_context_factor * bbox_height\n\n return torch.maximum(torch.tensor(1.0).to(self.device), output_height)\n\n def compute_output_width_f(bbox_tight: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute width of search/target region.\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :return: Output width.\n \"\"\"\n bbox_width = bbox_tight[2] - bbox_tight[0]\n output_width = k_context_factor * bbox_width\n\n return torch.maximum(torch.tensor(1.0).to(self.device), output_width)\n\n def get_center_x_f(bbox_tight: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute x-coordinate of the bounding box center.\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :return: x-coordinate of the bounding box center.\n \"\"\"\n return (bbox_tight[0] + bbox_tight[2]) / 2.0\n\n def get_center_y_f(bbox_tight: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Compute y-coordinate of the bounding box center\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :return: y-coordinate of the bounding box center.\n \"\"\"\n return (bbox_tight[1] + bbox_tight[3]) / 2.0\n\n def compute_crop_pad_image_location(\n bbox_tight: \"torch.Tensor\", image: \"torch.Tensor\"\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"]:\n \"\"\"\n Get the valid image coordinates for the context region in target or search region in full image\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :param image: Frame to be cropped and padded.\n :return: x-coordinate of the bounding box center.\n \"\"\"\n\n # Center of the bounding box\n # bbox_center_x = bbox_tight.get_center_x()\n # bbox_center_y = bbox_tight.get_center_y()\n bbox_center_x = get_center_x_f(bbox_tight)\n bbox_center_y = get_center_y_f(bbox_tight)\n\n image_height = image.shape[0]\n image_width = image.shape[1]\n\n # Padded output width and height\n # output_width = bbox_tight.compute_output_width()\n # output_height = bbox_tight.compute_output_height()\n output_width = compute_output_width_f(bbox_tight)\n output_height = compute_output_height_f(bbox_tight)\n\n roi_left = torch.maximum(torch.tensor(0.0).to(self.device), bbox_center_x - (output_width / 2.0))\n roi_bottom = torch.maximum(torch.tensor(0.0).to(self.device), bbox_center_y - (output_height / 2.0))\n\n # New ROI width\n # -------------\n # 1. left_half should not go out of bound on the left side of the\n # image\n # 2. right_half should not go out of bound on the right side of the\n # image\n left_half = torch.minimum(output_width / 2.0, bbox_center_x)\n right_half = torch.minimum(output_width / 2.0, image_width - bbox_center_x)\n roi_width = torch.maximum(torch.tensor(1.0).to(self.device), left_half + right_half)\n\n # New ROI height\n # Similar logic applied that is applied for 'New ROI width'\n top_half = torch.minimum(output_height / 2.0, bbox_center_y)\n bottom_half = torch.minimum(output_height / 2.0, image_height - bbox_center_y)\n roi_height = torch.maximum(torch.tensor(1.0).to(self.device), top_half + bottom_half)\n\n # Padded image location in the original image\n # objPadImageLocation = BoundingBox(roi_left, roi_bottom, roi_left + roi_width, roi_bottom + roi_height)\n #\n # return objPadImageLocation\n return roi_left, roi_bottom, roi_left + roi_width, roi_bottom + roi_height\n\n def edge_spacing_x_f(bbox_tight: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Edge spacing X to take care of if search/target pad region goes out of bound.\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :return: Edge spacing X.\n \"\"\"\n output_width = compute_output_width_f(bbox_tight)\n bbox_center_x = get_center_x_f(bbox_tight)\n\n return torch.maximum(torch.tensor(0.0).to(self.device), (output_width / 2) - bbox_center_x)\n\n def edge_spacing_y_f(bbox_tight: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Edge spacing X to take care of if search/target pad region goes out of bound.\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :return: Edge spacing X.\n \"\"\"\n output_height = compute_output_height_f(bbox_tight)\n bbox_center_y = get_center_y_f(bbox_tight)\n\n return torch.maximum(torch.tensor(0.0).to(self.device), (output_height / 2) - bbox_center_y)\n\n def crop_pad_image(bbox_tight: \"torch.Tensor\", image: \"torch.Tensor\") -> tuple[\n \"torch.Tensor\",\n tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\"],\n \"torch.Tensor\",\n \"torch.Tensor\",\n ]:\n \"\"\"\n Around the bounding box, we define an extra context factor of 2, which we will crop from the original image.\n\n :param bbox_tight: Coordinates of bounding box [x1, y1, x2, y2].\n :param image: Frame to be cropped and padded.\n :return: Cropped and Padded image.\n \"\"\"\n import math\n import torch\n\n pad_image_location = compute_crop_pad_image_location(bbox_tight, image)\n # roi_left = min(pad_image_location.x1, (image.shape[1] - 1))\n # roi_bottom = min(pad_image_location.y1, (image.shape[0] - 1))\n roi_left = torch.minimum(pad_image_location[0], torch.tensor(image.shape[1] - 1).to(self.device))\n roi_bottom = torch.minimum(pad_image_location[1], torch.tensor(image.shape[0] - 1).to(self.device))\n # roi_width = min(image.shape[1], max(1.0, math.ceil(pad_image_location.x2 - pad_image_location.x1)))\n # roi_height = min(image.shape[0], max(1.0, math.ceil(pad_image_location.y2 - pad_image_location.y1)))\n roi_width = min(image.shape[1], max(1, math.ceil(pad_image_location[2] - pad_image_location[0])))\n roi_height = min(image.shape[0], max(1, math.ceil(pad_image_location[3] - pad_image_location[1])))\n\n roi_bottom_int = int(roi_bottom)\n roi_bottom_height_int = roi_bottom_int + roi_height\n\n roi_left_int = int(roi_left)\n roi_left_width_int = roi_left_int + roi_width\n\n cropped_image = image[roi_bottom_int:roi_bottom_height_int, roi_left_int:roi_left_width_int]\n\n # output_width = max(math.ceil(bbox_tight.compute_output_width()), roi_width)\n # output_height = max(math.ceil(bbox_tight.compute_output_height()), roi_height)\n output_width = max(math.ceil(compute_output_width_f(bbox_tight)), roi_width)\n output_height = max(math.ceil(compute_output_height_f(bbox_tight)), roi_height)\n if image.ndim > 2:\n # output_image = np.zeros((int(output_height), int(output_width), image.shape[2]), dtype=image.dtype)\n output_image = torch.zeros((int(output_height), int(output_width), image.shape[2]), dtype=image.dtype)\n else:\n # output_image = np.zeros((int(output_height), int(output_width)), dtype=image.dtype)\n output_image = torch.zeros((int(output_height), int(output_width)), dtype=image.dtype)\n\n # edge_spacing_x = min(bbox_tight.edge_spacing_x(), (image.shape[1] - 1))\n # edge_spacing_y = min(bbox_tight.edge_spacing_y(), (image.shape[0] - 1))\n edge_spacing_x = torch.minimum(edge_spacing_x_f(bbox_tight), torch.tensor(image.shape[1] - 1))\n edge_spacing_y = torch.minimum(edge_spacing_y_f(bbox_tight), torch.tensor(image.shape[0] - 1))\n\n # rounding should be done to match the width and height\n output_image[\n int(edge_spacing_y) : int(edge_spacing_y) + cropped_image.shape[0],\n int(edge_spacing_x) : int(edge_spacing_x) + cropped_image.shape[1],\n ] = cropped_image\n\n return output_image, pad_image_location, edge_spacing_x, edge_spacing_y\n\n target_pad, _, _, _ = crop_pad_image(prev_bbox, prev_frame)\n cur_search_region, search_location, edge_spacing_x, edge_spacing_y = crop_pad_image(prev_bbox, curr_frame)\n\n target_pad_in = self._preprocess(target_pad).unsqueeze(0).to(self.device)\n cur_search_region_in = self._preprocess(cur_search_region).unsqueeze(0).to(self.device)\n\n pred_bb = self._model.forward(target_pad_in.float(), cur_search_region_in.float())\n\n pred_bb = torch.squeeze(pred_bb)\n\n k_scale_factor = 10\n height = cur_search_region.shape[0]\n width = cur_search_region.shape[1]\n\n # Normalize the image bounding box\n pred_bb[0] = pred_bb[0] / k_scale_factor * width\n pred_bb[2] = pred_bb[2] / k_scale_factor * width\n pred_bb[1] = pred_bb[1] / k_scale_factor * height\n pred_bb[3] = pred_bb[3] / k_scale_factor * height\n\n # brings gradients to zero\n # pred_bb = torch.round(pred_bb)\n\n # move the bounding box to target/search region coordinates\n raw_image = curr_frame\n pred_bb[0] = torch.clamp(pred_bb[0] + search_location[0] - edge_spacing_x, min=0.0)\n pred_bb[1] = torch.clamp(pred_bb[1] + search_location[1] - edge_spacing_y, min=0.0)\n pred_bb[2] = torch.clamp(pred_bb[2] + search_location[0] - edge_spacing_x, max=raw_image.shape[1])\n pred_bb[3] = torch.clamp(pred_bb[3] + search_location[1] - edge_spacing_y, max=raw_image.shape[0])\n\n # brings gradients to zero\n # pred_bb = torch.round(pred_bb)\n\n return pred_bb\n\n def _track(self, x: \"torch.Tensor\", y_init: \"torch.Tensor\") -> \"torch.Tensor\":\n \"\"\"\n Track object across frames.\n\n :param x: A single video of shape (nb_frames, nb_height, nb_width, nb_channels)\n :param y_init: Initial bounding box around object on the first frame of `x`.\n :return: Predicted bounding box coordinates for all frames of shape (nb_frames, 4) in format [x1, y1, x2, y2].\n \"\"\"\n import torch\n\n num_frames = x.shape[0]\n prev = x[0]\n bbox_0 = y_init\n y_pred_list = [y_init]\n\n for i in range(1, num_frames):\n curr = x[i]\n bbox_0 = self._track_step(curr, prev, bbox_0)\n bbox = bbox_0\n prev = curr\n\n y_pred_list.append(bbox)\n\n y_pred = torch.stack(y_pred_list)\n\n return y_pred\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> list[dict[str, np.ndarray]]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape (nb_samples, nb_frames, height, width, nb_channels).\n :param batch_size: Batch size.\n\n :Keyword Arguments:\n * *y_init* (``np.ndarray``) --\n Initial box around object to be tracked as [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n\n :return: Predictions of format `list[dict[str, np.ndarray]]`, one dictionary for each input image. The keys of\n the dictionary are:\n\n - boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n - labels [N_FRAMES]: the labels for each image, default 0.\n - scores [N_FRAMES]: the scores or each prediction, default 1.\n \"\"\"\n import torch\n\n self._model.eval()\n if hasattr(self._model, \"freeze\"):\n self._model.freeze()\n\n y_init = kwargs.get(\"y_init\")\n if y_init is None: # pragma: no cover\n raise ValueError(\"y_init is a required argument for method `predict`.\")\n\n if isinstance(y_init, np.ndarray):\n y_init = torch.from_numpy(y_init).to(self.device).float()\n else:\n y_init = y_init.to(self.device).float()\n\n predictions = []\n\n for i in range(x.shape[0]):\n if isinstance(x, np.ndarray):\n x_i = torch.from_numpy(x[i]).to(self.device)\n else:\n x_i = x[i].to(self.device)\n\n # Apply preprocessing\n x_i = torch.unsqueeze(x_i, dim=0)\n x_i, _ = self._apply_preprocessing(x_i, y=None, fit=False, no_grad=False)\n x_i = torch.squeeze(x_i)\n\n y_pred = self._track(x=x_i, y_init=y_init[i])\n prediction_dict = {}\n if isinstance(x, np.ndarray):\n prediction_dict[\"boxes\"] = y_pred.detach().cpu().numpy()\n else:\n prediction_dict[\"boxes\"] = y_pred\n predictions.append(prediction_dict)\n\n return predictions\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Not implemented.\n \"\"\"\n raise NotImplementedError\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n \"\"\"\n Not implemented.\n \"\"\"\n raise NotImplementedError\n\n def compute_losses(self, x: np.ndarray, y: list[dict[str, np.ndarray | \"torch.Tensor\"]]) -> dict[str, np.ndarray]:\n \"\"\"\n Compute losses.\n\n :param x: Samples of shape (nb_samples, nb_frames, height, width, nb_channels).\n :param y: Target values of format `list[dict[str, np.ndarray]]`, one dictionary for each input image. The keys\n of the dictionary are:\n\n - boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n :return: Dictionary of loss components.\n \"\"\"\n output = self.compute_loss(x=x, y=y)\n output_dict = {}\n output_dict[\"torch.nn.L1Loss\"] = output\n return output_dict\n\n def compute_loss(self, x: np.ndarray, y: list[dict[str, np.ndarray | \"torch.Tensor\"]], **kwargs) -> np.ndarray:\n \"\"\"\n Compute loss.\n\n :param x: Samples of shape (nb_samples, nb_frames, height, width, nb_channels).\n :param y: Target values of format `list[dict[str, np.ndarray]]`, one dictionary for each input image. The keys\n of the dictionary are:\n\n - boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n :return: Total loss.\n \"\"\"\n import torch\n\n output_dict, _, _ = self._get_losses(x=x, y=y)\n\n if isinstance(output_dict[\"torch.nn.L1Loss\"], list):\n output_list = []\n for out in output_dict[\"torch.nn.L1Loss\"]:\n output_list.append(out.detach().cpu().numpy())\n output = np.array(output_list)\n elif isinstance(output_dict[\"torch.nn.L1Loss\"], torch.Tensor):\n output = output_dict[\"torch.nn.L1Loss\"].detach().cpu().numpy()\n else:\n output = np.array(output_dict[\"torch.nn.L1Loss\"])\n\n return output\n\n def init(self, image: \"PIL.JpegImagePlugin.JpegImageFile\", box: np.ndarray): # type: ignore\n \"\"\"\n Method `init` for GOT-10k trackers.\n\n :param image: Current image.\n :param box: Initial boxes.\n :return: Predicted box.\n \"\"\"\n import torch\n\n self.prev = np.array(image) / 255.0\n if self.clip_values is not None:\n self.prev = self.prev * self.clip_values[1]\n self.box = torch.from_numpy(np.array([box[0], box[1], box[2] + box[0], box[3] + box[1]])).to(self.device)\n\n def update(self, image: np.ndarray) -> np.ndarray:\n \"\"\"\n Method `update` for GOT-10k trackers.\n\n :param image: Current image.\n :return: Predicted box.\n \"\"\"\n import torch\n\n curr = torch.from_numpy(image / 255.0)\n if self.clip_values is not None:\n curr = curr * self.clip_values[1] # type: ignore\n curr = curr.to(self.device)\n prev = torch.from_numpy(self.prev).to(self.device)\n\n curr, _ = self._apply_preprocessing(curr, y=None, fit=False)\n\n self.box = self._track_step(curr, prev, self.box)\n self.prev = curr.cpu().detach().numpy()\n\n box_return = self.box.cpu().detach().numpy()\n box_return = np.array(\n [box_return[0], box_return[1], box_return[2] - box_return[0], box_return[3] - box_return[1]]\n )\n\n return box_return\n\n def track(self, img_files: list[str], box: np.ndarray, visualize: bool = False) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Method `track` for GOT-10k toolkit trackers (MIT licence).\n\n :param img_files: Image files.\n :param box: Initial boxes.\n :param visualize: Visualise tracking.\n \"\"\"\n from got10k.utils.viz import show_frame\n from PIL import Image\n\n frame_num = len(img_files)\n boxes = np.zeros((frame_num, 4))\n boxes[0] = box\n times = np.zeros(frame_num)\n\n for i_f, img_file in enumerate(img_files):\n image = Image.open(img_file)\n if not image.mode == \"RGB\":\n image = image.convert(\"RGB\") # type: ignore\n\n start_time = time.time()\n if i_f == 0:\n self.init(image, box)\n else:\n boxes[i_f, :] = self.update(np.array(image))\n times[i_f] = time.time() - start_time\n\n if visualize:\n show_frame(image, boxes[i_f, :])\n\n return boxes, times\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/poison_mitigation/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module implements all poison mitigation models in ART.\n\"\"\"\n\nfrom art.estimators.poison_mitigation import neural_cleanse\nfrom art.estimators.poison_mitigation.strip import strip\nfrom art.estimators.poison_mitigation.neural_cleanse.keras import KerasNeuralCleanse\nfrom art.estimators.poison_mitigation.strip.strip import STRIPMixin\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/poison_mitigation/neural_cleanse/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nNeural cleanse estimators.\n\"\"\"\n\nfrom art.estimators.poison_mitigation.neural_cleanse.neural_cleanse import NeuralCleanseMixin\nfrom art.estimators.poison_mitigation.neural_cleanse.keras import KerasNeuralCleanse\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/poison_mitigation/neural_cleanse/keras.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nImplementation of methods in Neural Cleanse: Identifying and Mitigating Backdoor Attacks in Neural Networks.\nWang et al. (2019).\n\n| Paper link: https://people.cs.uchicago.edu/~ravenben/publications/pdf/backdoor-sp19.pdf\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.estimators.poison_mitigation.neural_cleanse.neural_cleanse import NeuralCleanseMixin\nfrom art.estimators.classification.keras import KerasClassifier, KERAS_MODEL_TYPE\n\nif TYPE_CHECKING:\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass KerasNeuralCleanse(NeuralCleanseMixin, KerasClassifier):\n \"\"\"\n Implementation of methods in Neural Cleanse: Identifying and Mitigating Backdoor Attacks in Neural Networks.\n Wang et al. (2019).\n\n | Paper link: https://people.cs.uchicago.edu/~ravenben/publications/pdf/backdoor-sp19.pdf\n \"\"\"\n\n estimator_params = KerasClassifier.estimator_params + [\n \"steps\",\n \"init_cost\",\n \"norm\",\n \"learning_rate\",\n \"attack_success_threshold\",\n \"patience\",\n \"early_stop\",\n \"early_stop_threshold\",\n \"early_stop_patience\",\n \"cost_multiplier_up\",\n \"cost_multiplier_down\",\n \"batch_size\",\n ]\n\n def __init__(\n self,\n model: KERAS_MODEL_TYPE,\n use_logits: bool = False,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n input_layer: int = 0,\n output_layer: int = 0,\n steps: int = 1000,\n init_cost: float = 1e-3,\n norm: int | float = 2,\n learning_rate: float = 0.1,\n attack_success_threshold: float = 0.99,\n patience: int = 5,\n early_stop: bool = True,\n early_stop_threshold: float = 0.99,\n early_stop_patience: int = 10,\n cost_multiplier: float = 1.5,\n batch_size: int = 32,\n ):\n \"\"\"\n Create a Neural Cleanse classifier.\n\n :param model: Keras model, neural network or other.\n :param use_logits: True if the output of the model are logits; false for probabilities or any other type of\n outputs. Logits output should be favored when possible to ensure attack efficiency.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param input_layer: The index of the layer to consider as input for models with multiple input layers. The layer\n with this index will be considered for computing gradients. For models with only one input\n layer this values is not required.\n :param output_layer: Which layer to consider as the output when the models have multiple output layers. The\n layer with this index will be considered for computing gradients. For models with only one\n output layer this values is not required.\n :param steps: The maximum number of steps to run the Neural Cleanse optimization\n :param init_cost: The initial value for the cost tensor in the Neural Cleanse optimization\n :param norm: The norm to use for the Neural Cleanse optimization, can be 1, 2, or np.inf\n :param learning_rate: The learning rate for the Neural Cleanse optimization\n :param attack_success_threshold: The threshold at which the generated backdoor is successful enough to stop the\n Neural Cleanse optimization\n :param patience: How long to wait for changing the cost multiplier in the Neural Cleanse optimization\n :param early_stop: Whether to allow early stopping in the Neural Cleanse optimization\n :param early_stop_threshold: How close values need to come to max value to start counting early stop\n :param early_stop_patience: How long to wait to determine early stopping in the Neural Cleanse optimization\n :param cost_multiplier: How much to change the cost in the Neural Cleanse optimization\n :param batch_size: The batch size for optimizations in the Neural Cleanse optimization\n \"\"\"\n import tensorflow as tf\n from tensorflow.keras.layers import Lambda\n import keras.backend as K\n from keras.optimizers import Adam\n from keras.losses import categorical_crossentropy\n from keras.metrics import categorical_accuracy\n\n super().__init__(\n model=model,\n use_logits=use_logits,\n channels_first=channels_first,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n input_layer=input_layer,\n output_layer=output_layer,\n steps=steps,\n init_cost=init_cost,\n norm=norm,\n learning_rate=learning_rate,\n attack_success_threshold=attack_success_threshold,\n early_stop=early_stop,\n early_stop_threshold=early_stop_threshold,\n early_stop_patience=early_stop_patience,\n patience=patience,\n cost_multiplier=cost_multiplier,\n batch_size=batch_size,\n )\n mask = np.random.uniform(size=super().input_shape)\n pattern = np.random.uniform(size=super().input_shape)\n self.epsilon = K.epsilon()\n\n # Normalize mask between [0, 1]\n self.mask_tensor_raw = tf.Variable(mask, dtype=tf.float32)\n # self.mask_tensor = tf.math.tanh(self.mask_tensor_raw) / (2.0 - self.epsilon) + 0.5\n\n # Normalize pattern between [0, 1]\n self.pattern_tensor_raw = tf.Variable(pattern, dtype=tf.float32)\n # self.pattern_tensor = tf.expand_dims(tf.math.tanh(self.pattern_tensor_raw) / (2 - self.epsilon) + 0.5, axis=0)\n\n # @tf.function\n def train_step(x_batch, y_batch):\n with tf.GradientTape() as tape:\n # Normalize mask and pattern\n self.mask_tensor = tf.tanh(self.mask_tensor_raw) / (2 - self.epsilon) + 0.5\n self.pattern_tensor = tf.tanh(self.pattern_tensor_raw) / (2 - self.epsilon) + 0.5\n\n # Construct adversarial example\n reverse_mask_tensor = 1.0 - self.mask_tensor\n x_adv = reverse_mask_tensor * x_batch + self.mask_tensor * self.pattern_tensor\n\n # Forward pass\n y_pred = self.model(x_adv, training=False)\n\n # Classification loss\n loss_ce = tf.keras.losses.categorical_crossentropy(y_batch, y_pred, from_logits=self.use_logits)\n\n # Accuracy\n correct = tf.equal(tf.argmax(y_pred, axis=1), tf.argmax(y_batch, axis=1))\n loss_acc = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n # Regularization loss\n if self.norm == 1:\n loss_reg = tf.reduce_sum(tf.abs(self.mask_tensor)) / tf.cast(\n tf.shape(self.mask_tensor)[-1], tf.float32\n )\n elif self.norm == 2:\n loss_reg = tf.sqrt(\n tf.reduce_sum(tf.square(self.mask_tensor)) / tf.cast(tf.shape(self.mask_tensor)[-1], tf.float32)\n )\n else:\n raise ValueError(f\"Unsupported norm {self.norm}\")\n\n # Total loss\n loss_combined = tf.reduce_mean(loss_ce) + self.cost * loss_reg\n\n # Compute gradients\n grads = tape.gradient(loss_combined, [self.mask_tensor_raw, self.pattern_tensor_raw])\n\n # Apply gradients\n self.opt.apply_gradients(zip(grads, [self.mask_tensor_raw, self.pattern_tensor_raw]))\n\n print(loss_acc)\n\n return loss_ce, loss_reg, loss_combined, loss_acc\n\n self.train = train_step\n\n # Initialize cost (as a TensorFlow variable so it can be updated during training)\n self.cost = self.init_cost\n self.cost_tensor = tf.Variable(self.cost, trainable=False, dtype=tf.float32)\n\n self.opt = Adam(learning_rate=self.learning_rate, beta_1=0.5, beta_2=0.9)\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n def reset(self):\n \"\"\"\n Reset the state of the defense\n :return:\n \"\"\"\n import tensorflow as tf\n\n self.cost = self.init_cost\n self.cost_tensor.assign(self.init_cost)\n self.opt.iterations.assign(0)\n if self.opt._variables:\n for var in self.opt._variables:\n var.assign(tf.zeros_like(var))\n\n def generate_backdoor(\n self, x_val: np.ndarray, y_val: np.ndarray, y_target: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generates a possible backdoor for the model. Returns the pattern and the mask\n :return: A tuple of the pattern and mask for the model.\n \"\"\"\n import tensorflow as tf\n import keras.backend as K\n from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n self.reset()\n datagen = ImageDataGenerator()\n gen = datagen.flow(x_val, y_val, batch_size=self.batch_size)\n mask_best: np.ndarray | None = None\n pattern_best: np.ndarray | None = None\n reg_best = float(\"inf\")\n cost_set_counter = 0\n cost_up_counter = 0\n cost_down_counter = 0\n cost_up_flag = False\n cost_down_flag = False\n early_stop_counter = 0\n early_stop_reg_best = reg_best\n mini_batch_size = len(x_val) // self.batch_size\n for _ in tqdm(range(self.steps), desc=f\"Generating backdoor for class {np.argmax(y_target)}\"):\n loss_reg_list = []\n loss_acc_list = []\n\n for _ in range(mini_batch_size):\n x_batch, _ = next(gen)\n y_batch = [y_target] * x_batch.shape[0]\n _, batch_loss_reg, _, batch_loss_acc = self.train(x_batch, y_batch)\n\n loss_reg_list.extend(list(tf.reshape(batch_loss_reg, [-1]).numpy()))\n loss_acc_list.extend(list(tf.reshape(batch_loss_acc, [-1]).numpy()))\n\n avg_loss_reg = np.mean(loss_reg_list)\n avg_loss_acc = np.mean(loss_acc_list)\n\n # save best mask/pattern so far\n if avg_loss_acc >= self.attack_success_threshold and avg_loss_reg < reg_best:\n mask_best = self.mask_tensor.numpy()\n pattern_best = self.pattern_tensor.numpy()\n reg_best = avg_loss_reg\n\n # check early stop\n if self.early_stop: # pragma: no cover\n if reg_best < float(\"inf\"):\n if reg_best >= self.early_stop_threshold * early_stop_reg_best:\n early_stop_counter += 1\n else:\n early_stop_counter = 0\n early_stop_reg_best = min(reg_best, early_stop_reg_best)\n\n if cost_down_flag and cost_up_flag and early_stop_counter >= self.early_stop_patience:\n logger.info(\"Early stop\")\n break\n\n # cost modification\n if avg_loss_acc >= self.attack_success_threshold:\n cost_set_counter += 1\n if cost_set_counter >= self.patience:\n self.cost = self.init_cost\n self.cost_tensor.assign(self.cost)\n cost_up_counter = 0\n cost_down_counter = 0\n cost_up_flag = False\n cost_down_flag = False\n else:\n cost_set_counter = 0\n\n if avg_loss_acc >= self.attack_success_threshold:\n cost_up_counter += 1\n cost_down_counter = 0\n else:\n cost_up_counter = 0\n cost_down_counter += 1\n\n if cost_up_counter >= self.patience:\n cost_up_counter = 0\n self.cost *= self.cost_multiplier_up\n self.cost_tensor.assign(self.cost)\n cost_up_flag = True\n elif cost_down_counter >= self.patience:\n cost_down_counter = 0\n self.cost /= self.cost_multiplier_down\n self.cost_tensor.assign(self.cost)\n cost_down_flag = True\n\n if mask_best is None:\n mask_best = self.mask_tensor.numpy()\n pattern_best = self.pattern_tensor.numpy()\n\n if pattern_best is None:\n raise ValueError(\"Unexpected `None` detected.\")\n\n return mask_best, pattern_best\n\n def _predict_classifier(\n self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs\n ) -> np.ndarray:\n x = x.astype(ART_NUMPY_DTYPE)\n return KerasClassifier.predict(self, x=x, batch_size=batch_size, training_mode=training_mode, **kwargs)\n\n def _fit_classifier(self, x: np.ndarray, y: np.ndarray, batch_size: int, nb_epochs: int, **kwargs) -> None:\n x = x.astype(ART_NUMPY_DTYPE)\n return self.fit(x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def _get_penultimate_layer_activations(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Return the output of the second to last layer for input `x`.\n\n :param x: Input for computing the activations.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n if self.layer_names is not None:\n penultimate_layer = len(self.layer_names) - 2\n else: # pragma: no cover\n raise ValueError(\"No layer names found.\")\n return self.get_activations(x, penultimate_layer, batch_size=self.batch_size, framework=False)\n\n def _prune_neuron_at_index(self, index: int) -> None:\n \"\"\"\n Set the weights (and biases) of a neuron at index in the penultimate layer of the neural network to zero\n\n :param index: An index of the penultimate layer\n \"\"\"\n if self.layer_names is not None:\n layer = self._model.layers[len(self.layer_names) - 2]\n else: # pragma: no cover\n raise ValueError(\"No layer names found.\")\n weights, biases = layer.get_weights()\n weights[:, index] = np.zeros_like(weights[:, index])\n biases[index] = 0\n layer.set_weights([weights, biases])\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction of the given classifier for a batch of inputs, potentially filtering suspicious input\n\n :param x: Input data to predict.\n :param batch_size: Batch size.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n return NeuralCleanseMixin.predict(self, x, batch_size=batch_size, training_mode=training_mode, **kwargs)\n\n def mitigate(self, x_val: np.ndarray, y_val: np.ndarray, mitigation_types: list[str]) -> None:\n \"\"\"\n Mitigates the effect of poison on a classifier\n\n :param x_val: Validation data to use to mitigate the effect of poison.\n :param y_val: Validation labels to use to mitigate the effect of poison.\n :param mitigation_types: The types of mitigation method, can include 'unlearning', 'pruning', or 'filtering'\n :return: Tuple of length 2 of the selected class and certified radius.\n \"\"\"\n return NeuralCleanseMixin.mitigate(self, x_val, y_val, mitigation_types)\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n return self.loss_gradient(x=x, y=y, training_mode=training_mode, **kwargs)\n\n def class_gradient(\n self,\n x: np.ndarray,\n label: int | list[int] | np.ndarray | None = None,\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives of the given classifier w.r.t. `x` of original classifier.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n return self.class_gradient(x=x, label=label, training_mode=training_mode, **kwargs)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/poison_mitigation/neural_cleanse/neural_cleanse.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Neural Cleanse on a classifier.\n\n| Paper link: https://people.cs.uchicago.edu/~ravenben/publications/pdf/backdoor-sp19.pdf\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\n\nfrom art.estimators.certification.abstain import AbstainPredictorMixin\nfrom art.utils import to_categorical\n\nlogger = logging.getLogger(__name__)\n\n\nclass NeuralCleanseMixin(AbstainPredictorMixin):\n \"\"\"\n Implementation of methods in Neural Cleanse: Identifying and Mitigating Backdoor Attacks in Neural Networks.\n Wang et al. (2019).\n\n | Paper link: https://people.cs.uchicago.edu/~ravenben/publications/pdf/backdoor-sp19.pdf\n \"\"\"\n\n def __init__(\n self,\n steps: int,\n *args,\n init_cost: float = 1e-3,\n norm: int | float = 2,\n learning_rate: float = 0.1,\n attack_success_threshold: float = 0.99,\n patience: int = 5,\n early_stop: bool = True,\n early_stop_threshold: float = 0.99,\n early_stop_patience: int = 10,\n cost_multiplier: float = 1.5,\n batch_size: int = 32,\n **kwargs,\n ) -> None:\n \"\"\"\n Create a neural cleanse wrapper.\n\n :param steps: The maximum number of steps to run the Neural Cleanse optimization\n :param init_cost: The initial value for the cost tensor in the Neural Cleanse optimization\n :param norm: The norm to use for the Neural Cleanse optimization, can be 1, 2, or np.inf\n :param learning_rate: The learning rate for the Neural Cleanse optimization\n :param attack_success_threshold: The threshold at which the generated backdoor is successful enough to stop the\n Neural Cleanse optimization\n :param patience: How long to wait for changing the cost multiplier in the Neural Cleanse optimization\n :param early_stop: Whether to allow early stopping in the Neural Cleanse optimization\n :param early_stop_threshold: How close values need to come to max value to start counting early stop\n :param early_stop_patience: How long to wait to determine early stopping in the Neural Cleanse optimization\n :param cost_multiplier: How much to change the cost in the Neural Cleanse optimization\n :param batch_size: The batch size for optimizations in the Neural Cleanse optimization\n \"\"\"\n super().__init__(*args, **kwargs)\n self.steps = steps\n self.init_cost = init_cost\n self.norm = norm\n self.learning_rate = learning_rate\n self.attack_success_threshold = attack_success_threshold\n self.patience = patience\n self.early_stop = early_stop\n self.early_stop_threshold = early_stop_threshold\n self.early_stop_patience = early_stop_patience\n self.cost_multiplier_up = cost_multiplier\n self.cost_multiplier_down = cost_multiplier**1.5\n self.batch_size = batch_size\n self.top_indices: list[int] = []\n self.activation_threshold = 0\n\n def _predict_classifier(\n self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs\n ) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n raise NotImplementedError\n\n def _fit_classifier(self, x: np.ndarray, y: np.ndarray, batch_size: int, nb_epochs: int, **kwargs) -> None:\n raise NotImplementedError\n\n def _get_penultimate_layer_activations(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Return the output of the second to last layer for input `x`.\n\n :param x: Input for computing the activations.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n raise NotImplementedError\n\n def _prune_neuron_at_index(self, index: int) -> None:\n \"\"\"\n Set the weights (and biases) of a neuron at index in the penultimate layer of the neural network to zero\n\n :param index: An index of the penultimate layer\n \"\"\"\n raise NotImplementedError\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction of the given classifier for a batch of inputs, potentially filtering suspicious input\n\n :param x: Input samples.\n :param batch_size: Batch size.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n predictions = self._predict_classifier(x=x, batch_size=batch_size, training_mode=training_mode, **kwargs)\n\n if len(self.top_indices) == 0:\n logger.warning(\"Filtering mitigation not activated, suspected backdoors may be triggered\")\n return predictions\n\n all_activations = self._get_penultimate_layer_activations(x)\n suspected_neuron_activations = all_activations[:, self.top_indices]\n predictions[np.any(suspected_neuron_activations > self.activation_threshold, axis=1)] = self.abstain()\n\n return predictions\n\n def mitigate(self, x_val: np.ndarray, y_val: np.ndarray, mitigation_types: list[str]) -> None:\n \"\"\"\n Mitigates the effect of poison on a classifier\n\n :param x_val: Validation data to use to mitigate the effect of poison.\n :param y_val: Validation labels to use to mitigate the effect of poison.\n :param mitigation_types: The types of mitigation method, can include 'unlearning', 'pruning', or 'filtering'\n :return: Tuple of length 2 of the selected class and certified radius.\n \"\"\"\n clean_data, backdoor_data, backdoor_labels = self.backdoor_examples(x_val, y_val)\n\n # If no backdoors detected from outlier detection, do nothing\n if len(backdoor_data) == 0:\n logger.info(\"No backdoor labels were detected\")\n return\n\n if \"pruning\" in mitigation_types or \"filtering\" in mitigation_types:\n # get activations from penultimate layer from clean and backdoor images\n clean_activations = self._get_penultimate_layer_activations(clean_data)\n backdoor_activations = self._get_penultimate_layer_activations(backdoor_data)\n\n # rank activations descending by difference in backdoor and clean inputs\n ranked_indices = np.argsort(np.sum(clean_activations - backdoor_activations, axis=0))\n\n for mitigation_type in mitigation_types:\n if mitigation_type == \"unlearning\":\n # Train one epoch on generated backdoors\n # This mitigation method works well for Trojan attacks\n\n self._fit_classifier(backdoor_data, backdoor_labels, batch_size=1, nb_epochs=1)\n\n elif mitigation_type == \"pruning\":\n # zero out activations from highly ranked neurons until backdoor is unresponsive\n # This mitigation method works well for backdoors.\n\n backdoor_effective = self.check_backdoor_effective(backdoor_data, backdoor_labels)\n num_neurons_pruned = 0\n total_neurons = clean_activations.shape[1]\n\n # starting from indices of high activation neurons, set weights (and biases) of high activation\n # neurons to zero, until backdoor ineffective or pruned 30% of neurons\n logger.info(\"Pruning model...\")\n while (\n backdoor_effective\n and num_neurons_pruned < 0.3 * total_neurons\n and num_neurons_pruned < len(ranked_indices)\n ):\n self._prune_neuron_at_index(ranked_indices[num_neurons_pruned])\n num_neurons_pruned += 1\n backdoor_effective = self.check_backdoor_effective(backdoor_data, backdoor_labels)\n logger.info(\"Pruning complete. Pruned %d neurons\", num_neurons_pruned)\n\n elif mitigation_type == \"filtering\":\n # using top 1% of ranked neurons by activation difference to adv vs. clean inputs\n # generate a profile of average activation, when above threshold, abstain\n\n # get indices of top 1% of ranked neurons\n num_top = int(np.ceil(len(ranked_indices) * 0.01))\n self.top_indices = ranked_indices[:num_top].tolist()\n\n # measure average activation for clean images and backdoor images\n avg_clean_activation = np.average(clean_activations[:, self.top_indices], axis=0)\n std_clean_activation = np.std(clean_activations[:, self.top_indices], axis=0)\n\n # if average activation for selected neurons is above a threshold, flag input and abstain\n # activation over threshold function can be called at predict\n # TODO: explore different values for threshold\n self.activation_threshold = avg_clean_activation + 1 * std_clean_activation\n\n else: # pragma: no cover\n raise TypeError(\"Mitigation type: `\" + mitigation_type + \"` not supported\")\n\n def check_backdoor_effective(self, backdoor_data: np.ndarray, backdoor_labels: np.ndarray) -> bool:\n \"\"\"\n Check if supposed backdoors are effective against the classifier\n\n :param backdoor_data: data with the backdoor added\n :param backdoor_labels: the correct label for the data\n :return: true if any of the backdoors are effective on the model\n \"\"\"\n backdoor_predictions = self._predict_classifier(backdoor_data)\n backdoor_effective = np.logical_not(np.all(backdoor_predictions == backdoor_labels, axis=1))\n return np.any(backdoor_effective) # type: ignore\n\n def backdoor_examples(self, x_val: np.ndarray, y_val: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Generate reverse-engineered backdoored examples using validation data\n\n :param x_val: validation data\n :param y_val: validation labels\n :return: a tuple containing (clean data, backdoored data, labels)\n \"\"\"\n clean_data_list = []\n example_data_list = []\n example_labels_list = []\n\n for backdoored_label, mask, pattern in self.outlier_detection(x_val, y_val):\n data_for_class = np.copy(x_val[np.argmax(y_val, axis=1) == backdoored_label])\n labels_for_class = np.copy(y_val[np.argmax(y_val, axis=1) == backdoored_label])\n\n if len(data_for_class) == 0:\n logger.warning(\"No validation data exists for infected class: %s\", str(backdoored_label))\n\n clean_data_list.append(np.copy(data_for_class))\n data_for_class = (1 - mask) * data_for_class + mask * pattern\n example_data_list.append(data_for_class)\n example_labels_list.append(labels_for_class)\n\n # If any backdoor examples were found, stack data into one array\n if example_data_list:\n clean_data = np.vstack(clean_data_list)\n example_data = np.vstack(example_data_list)\n example_labels = np.vstack(example_labels_list)\n else:\n clean_data = np.array(clean_data_list)\n example_data = np.array(example_data_list)\n example_labels = np.array(example_labels_list)\n\n return clean_data, example_data, example_labels\n\n def generate_backdoor(\n self, x_val: np.ndarray, y_val: np.ndarray, y_target: np.ndarray\n ) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Generates a possible backdoor for the model. Returns the pattern and the mask\n\n :return: A tuple of the pattern and mask for the model.\n \"\"\"\n raise NotImplementedError\n\n def outlier_detection(self, x_val: np.ndarray, y_val: np.ndarray) -> list[tuple[int, np.ndarray, np.ndarray]]:\n \"\"\"\n Returns a tuple of suspected poison labels and their mask and pattern\n\n :return: A list of tuples containing the class index, mask, and pattern for suspected labels\n \"\"\"\n l1_norms = []\n masks = []\n patterns = []\n num_classes = self.nb_classes\n for class_idx in range(num_classes):\n # Assuming classes are indexed\n target_label = to_categorical([class_idx], num_classes).flatten()\n mask, pattern = self.generate_backdoor(x_val, y_val, target_label)\n norm = np.sum(np.abs(mask))\n l1_norms.append(norm)\n masks.append(mask)\n patterns.append(pattern)\n\n # assuming l1 norms would naturally create a normal distribution\n consistency_constant = 1.4826\n\n median = np.median(l1_norms)\n mad = consistency_constant * np.median(np.abs(l1_norms - median))\n # min_mad = np.abs(np.min(l1_norms) - median) / mad\n flagged_labels = []\n\n for class_idx in range(num_classes):\n anomaly_index = np.abs(l1_norms[class_idx] - median) / mad\n # Points with anomaly_index > 2 have 95% probability of being an outlier\n # Backdoor outliers show up as masks with small l1 norms\n if l1_norms[class_idx] <= median and anomaly_index > 2:\n logger.warning(\"Detected potential backdoor in class: %s\", str(class_idx))\n flagged_labels.append(class_idx)\n\n return [(label, masks[label], patterns[label]) for label in flagged_labels]\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/poison_mitigation/strip/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nSTRIP estimators.\n\"\"\"\n\nfrom art.estimators.poison_mitigation.strip.strip import STRIPMixin\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/poison_mitigation/strip/strip.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements STRIP: A Defence Against Trojan Attacks on Deep Neural Networks.\n\n| Paper link: https://arxiv.org/abs/1902.06531\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\n\nimport numpy as np\nfrom scipy.stats import entropy, norm\nfrom tqdm.auto import tqdm\n\nfrom art.estimators.certification.abstain import AbstainPredictorMixin\n\nlogger = logging.getLogger(__name__)\n\n\nclass STRIPMixin(AbstainPredictorMixin):\n \"\"\"\n Implementation of STRIP: A Defence Against Trojan Attacks on Deep Neural Networks (Gao et. al. 2020)\n\n | Paper link: https://arxiv.org/abs/1902.06531\n \"\"\"\n\n def __init__(\n self,\n predict_fn: Callable[[np.ndarray], np.ndarray],\n num_samples: int = 20,\n false_acceptance_rate: float = 0.01,\n **kwargs,\n ) -> None: # pragma: no cover\n \"\"\"\n Create a STRIP defense\n\n :param predict_fn: The predict function of the original classifier\n :param num_samples: The number of samples to use to test entropy at inference time\n :param false_acceptance_rate: The percentage of acceptable false acceptance\n \"\"\"\n super().__init__(**kwargs)\n self.predict_fn = predict_fn\n self.num_samples = num_samples\n self.false_acceptance_rate = false_acceptance_rate\n self.entropy_threshold: float | None = None\n self.validation_data: np.ndarray | None = None\n\n def predict(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Perform prediction of the given classifier for a batch of inputs, potentially filtering suspicious input\n\n :param x: Input samples.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n raw_predictions = self.predict_fn(x)\n\n if self.entropy_threshold is None or self.validation_data is None: # pragma: no cover\n logger.warning(\"Mitigation has not been performed. Predictions may be unsafe.\")\n return raw_predictions\n\n x_val = self.validation_data\n final_predictions = []\n\n for i, img in enumerate(x):\n # Randomly select samples from test set\n selected_indices = np.random.choice(np.arange(len(x_val)), self.num_samples)\n\n # Perturb the images by combining them\n perturbed_images = np.array([combine_images(img, x_val[idx]) for idx in selected_indices])\n\n # Predict on the perturbed images\n perturbed_predictions = self.predict_fn(perturbed_images)\n\n # Calculate normalized entropy\n normalized_entropy = np.sum(entropy(perturbed_predictions, base=2, axis=0)) / float(self.num_samples)\n\n # Abstain if entropy is below threshold\n if normalized_entropy <= self.entropy_threshold:\n final_predictions.append(self.abstain())\n else:\n final_predictions.append(raw_predictions[i])\n\n return np.array(final_predictions)\n\n def mitigate(self, x_val: np.ndarray) -> None:\n \"\"\"\n Mitigates the effect of poison on a classifier\n\n :param x_val: Validation data to use to mitigate the effect of poison.\n \"\"\"\n self.validation_data = x_val\n entropies = []\n\n # Find normal entropy distribution\n for _, img in enumerate(tqdm(x_val)):\n selected_indices = np.random.choice(np.arange(len(x_val)), self.num_samples)\n perturbed_images = np.array([combine_images(img, x_val[idx]) for idx in selected_indices])\n perturbed_predictions = self.predict_fn(perturbed_images)\n normalized_entropy = np.sum(entropy(perturbed_predictions, base=2, axis=0)) / float(self.num_samples)\n entropies.append(normalized_entropy)\n\n mean_entropy, std_entropy = norm.fit(entropies)\n\n # Set threshold to FAR percentile\n self.entropy_threshold = norm.ppf(self.false_acceptance_rate, loc=mean_entropy, scale=std_entropy)\n if self.entropy_threshold is not None and self.entropy_threshold < 0: # pragma: no cover\n logger.warning(\"Entropy value is negative. Increase FAR for reasonable performance.\")\n\n\ndef combine_images(img1: np.ndarray, img2: np.ndarray, alpha=0.5) -> np.ndarray:\n \"\"\"\n Combine two Numpy arrays of the same shape\n\n :param img1: a Numpy array\n :param img2: a Numpy array\n :param alpha: percentage weight for the first image\n :return: The combined image\n \"\"\"\n return alpha * img1 + (1 - alpha) * img2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/regression/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module implements all regressors in ART.\n\"\"\"\n\nfrom art.estimators.regression.regressor import RegressorMixin, Regressor\n\nfrom art.estimators.regression.scikitlearn import ScikitlearnRegressor\n\nfrom art.estimators.regression.keras import KerasRegressor\n\nfrom art.estimators.regression.pytorch import PyTorchRegressor\n\nfrom art.estimators.regression.blackbox import BlackBoxRegressor\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/regression/blackbox.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `BlackBoxRegressor` for black-box regressors.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nfrom functools import total_ordering\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.regression.regressor import RegressorMixin, Regressor\nfrom art.estimators.classification import BlackBoxClassifier\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass BlackBoxRegressor(RegressorMixin, BaseEstimator):\n \"\"\"\n Class for black-box regressors.\n \"\"\"\n\n estimator_params = Regressor.estimator_params + [\"input_shape\", \"predict_fn\", \"loss_fn\"]\n\n def __init__(\n self,\n predict_fn: Callable | tuple[np.ndarray, np.ndarray],\n input_shape: tuple[int, ...],\n loss_fn: Callable | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n fuzzy_float_compare: bool = False,\n ):\n \"\"\"\n Create a `Regressor` instance for a black-box model.\n\n :param predict_fn: Function that takes in an `np.ndarray` of input data and returns the predicted value for\n each input or a tuple of the form `(inputs, values)` containing the predicted value for each input.\n :param input_shape: Size of input.\n :param loss_fn: Function that takes in two `np.ndarray`s, of true values and predicted values, and returns the\n loss value for each pair.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param fuzzy_float_compare: If `predict_fn` is a tuple mapping inputs to values, and this is True, looking up\n inputs in the table will be done using `numpy.isclose`. Only set to True if really needed, since this\n severely affects performance.\n \"\"\"\n super().__init__(\n model=None,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n if callable(predict_fn):\n self._predict_fn = predict_fn\n else:\n self._predict_fn = _make_lookup_predict_fn(predict_fn, fuzzy_float_compare)\n self._fuzzy_float_compare = fuzzy_float_compare\n self._input_shape = input_shape\n self._loss_fn = loss_fn\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def predict_fn(self) -> Callable:\n \"\"\"\n Return the prediction function.\n\n :return: The prediction function.\n \"\"\"\n return self._predict_fn # type: ignore\n\n def get_classifier(self, thresholds: list[float]) -> BlackBoxClassifier:\n \"\"\"\n Returns a classifier representation of the regressor. Maps real values to classes based on the provided\n thresholds.\n\n :param thresholds: The cutoff values for mapping real values to classes.\n :return: BlackBoxClassifier instance\n \"\"\"\n\n def predict_class(x):\n predictions = self.predict(x)\n binned = np.digitize(predictions, thresholds)\n return np.eye(len(thresholds) + 1)[binned]\n\n classifier = BlackBoxClassifier(\n predict_class,\n self.input_shape,\n len(thresholds) + 1,\n clip_values=self.clip_values,\n preprocessing_defences=self.preprocessing_defences,\n postprocessing_defences=self.postprocessing_defences,\n preprocessing=self.preprocessing,\n fuzzy_float_compare=self._fuzzy_float_compare,\n )\n return classifier\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n from art.config import ART_NUMPY_DTYPE\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n predictions = np.zeros((x_preprocessed.shape[0],), dtype=ART_NUMPY_DTYPE)\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = (\n batch_index * batch_size,\n min((batch_index + 1) * batch_size, x_preprocessed.shape[0]),\n )\n predictions[begin:end] = self.predict_fn(x_preprocessed[begin:end])\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=predictions, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Labels.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs or the number of steps per epoch as part of this argument will result in as error.\n :raises `NotImplementedException`: This method is not supported for black-box classifiers.\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. For Keras, .h5 format is used.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n :raises `NotImplementedException`: This method is not supported for black-box classifiers.\n \"\"\"\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the regressor for samples `x`. If loss_fn not provided at init, MSE loss is computed.\n\n :param x: Input samples.\n :param y: Target values.\n :return: Loss values.\n \"\"\"\n predicted = self.predict(x)\n return self.compute_loss_from_predictions(y, predicted)\n\n def compute_loss_from_predictions(self, pred: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the regressor for predictions `pred`. If loss_fn not provided at init, MSE loss is computed.\n\n :param pred: Model predictions.\n :param y: Target values.\n :return: Loss values.\n \"\"\"\n if self._loss_fn:\n return self._loss_fn(y, pred)\n # default MSE loss\n return (y - pred) ** 2\n\n\n@total_ordering\nclass FuzzyMapping:\n \"\"\"\n Class for a sample/label pair to be used in a `SortedList`.\n \"\"\"\n\n def __init__(self, key: np.ndarray, value=None):\n \"\"\"\n Create an instance of a key/value to pair to be used in a `SortedList`.\n\n :param key: The sample to be matched against.\n :param value: The mapped value.\n \"\"\"\n self.key = key\n self.value = value\n\n def __eq__(self, other):\n return np.all(np.isclose(self.key, other.key))\n\n def __ge__(self, other):\n # This implements >= comparison, so we can use this class in a `SortedList`. The `total_ordering` decorator\n # automatically generates the rest of the comparison magic functions based on this one\n\n close_cells = np.isclose(self.key, other.key)\n if np.all(close_cells):\n return True\n\n # If the keys are not exactly the same (up to floating-point inaccuracies), we compare the value of the first\n # index which is not the same to decide on an ordering\n\n compare_idx = np.unravel_index(np.argmin(close_cells), shape=self.key.shape)\n return self.key[compare_idx] >= other.key[compare_idx]\n\n\ndef _make_lookup_predict_fn(existing_predictions: tuple[np.ndarray, np.ndarray], fuzzy_float_compare: bool) -> Callable:\n \"\"\"\n Makes a predict_fn callback based on a table of existing predictions.\n\n :param existing_predictions: Tuple of (samples, labels).\n :param fuzzy_float_compare: Look up predictions using `np.isclose`, only set to True if really needed, since this\n severely affects performance.\n :return: Prediction function.\n \"\"\"\n\n samples, labels = existing_predictions\n\n if fuzzy_float_compare:\n from sortedcontainers import SortedList\n\n # Construct a search-tree of the predictions, using fuzzy float comparison\n sorted_predictions = SortedList([FuzzyMapping(key, value) for key, value in zip(samples, labels)])\n\n def fuzzy_predict_fn(batch):\n predictions = []\n for row in batch:\n try:\n match_idx = sorted_predictions.index(FuzzyMapping(row))\n except ValueError as err: # pragma: no cover\n raise ValueError(\"No existing prediction for queried input\") from err\n\n predictions.append(sorted_predictions[match_idx].value)\n\n return np.array(predictions)\n\n return fuzzy_predict_fn\n\n # Construct a dictionary to map from samples to predictions. We use the bytes of the `ndarray` as the key,\n # because the `ndarray` itself is not hashable\n mapping = {}\n for x, y in zip(samples, labels):\n mapping[x.tobytes()] = y\n\n def predict_fn(batch):\n predictions = []\n for row in batch:\n row_bytes = row.tobytes()\n if row.tobytes() not in mapping:\n raise ValueError(\"No existing prediction for queried input\")\n\n predictions.append(mapping[row_bytes])\n\n return np.array(predictions)\n\n return predict_fn\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/regression/keras.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the regressor `KerasRegressor` for Keras models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nimport os\nimport time\nfrom typing import (\n Any,\n Iterator,\n TYPE_CHECKING,\n Union,\n)\n\nimport numpy as np\nimport six\n\nfrom art import config\nfrom art.estimators.keras import KerasEstimator\nfrom art.estimators.regression.regressor import RegressorMixin\n\nif TYPE_CHECKING:\n\n import keras\n import tensorflow as tf\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\nKERAS_MODEL_TYPE = Union[\"keras.models.Model\", \"tf.keras.models.Model\"] # pylint: disable=C0103\n\n\nclass KerasRegressor(RegressorMixin, KerasEstimator):\n \"\"\"\n Wrapper class for importing Keras regression models.\n \"\"\"\n\n estimator_params = KerasEstimator.estimator_params + [\"input_layer\", \"output_layer\"]\n\n def __init__(\n self,\n model: KERAS_MODEL_TYPE,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n input_layer: int = 0,\n output_layer: int = 0,\n ) -> None:\n \"\"\"\n Create a `Regressor` instance from a Keras model. Assumes the `model` passed as argument is compiled.\n\n :param model: Keras model, neural network or other.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the regressor.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the regressor.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param input_layer: The index of the layer to consider as input for models with multiple input layers. The layer\n with this index will be considered for computing gradients. For models with only one input\n layer this values is not required.\n :param output_layer: Which layer to consider as the output when the models have multiple output layers. The\n layer with this index will be considered for computing gradients. For models with only one\n output layer this values is not required.\n \"\"\"\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n channels_first=channels_first,\n )\n\n self._input_layer = input_layer\n self._output_layer = output_layer\n\n if \" tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def input_layer(self) -> int:\n \"\"\"\n The index of the layer considered as input for models with multiple input layers.\n For models with only one input layer the index is 0.\n\n :return: The index of the layer considered as input for models with multiple input layers.\n \"\"\"\n return self._input_layer # type: ignore\n\n @property\n def output_layer(self) -> int:\n \"\"\"\n The index of the layer considered as output for models with multiple output layers.\n For models with only one output layer the index is 0.\n\n :return: The index of the layer considered as output for models with multiple output layers.\n \"\"\"\n return self._output_layer # type: ignore\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, reduction: str = \"none\", **kwargs) -> np.ndarray:\n \"\"\"\n Compute the loss of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Loss values.\n :rtype: Format as expected by the `model`\n \"\"\"\n if not self._losses:\n raise NotImplementedError(\"loss method is only supported for keras versions >= 2.3.1\")\n\n if self.is_tensorflow:\n import tensorflow.keras.backend as k\n else:\n import keras.backend as k\n\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n shape_match = [i is None or i == j for i, j in zip(self._input_shape, x_preprocessed.shape[1:])]\n if not all(shape_match): # pragma: no cover\n raise ValueError(\n f\"Error when checking x: expected preprocessed x to have shape {self._input_shape} but got array with \"\n f\"shape {x_preprocessed.shape[1:]}.\"\n )\n\n predictions = self._model.predict(x_preprocessed)\n\n if self._orig_loss and hasattr(self._orig_loss, \"reduction\"):\n prev_reduction = self._orig_loss.reduction\n if hasattr(self._losses, \"Reduction\"):\n self._orig_loss.reduction = self._losses.Reduction.NONE\n loss = self._orig_loss(y_preprocessed, predictions)\n self._orig_loss.reduction = prev_reduction\n else:\n prev_reduction = []\n predictions = k.constant(predictions)\n y_preprocessed = k.constant(y_preprocessed)\n for loss_function in self._model.loss_functions:\n prev_reduction.append(loss_function.reduction)\n if hasattr(self._losses, \"Reduction\"):\n loss_function.reduction = self._losses.Reduction.NONE\n loss = self._loss_function(y_preprocessed, predictions)\n for i, loss_function in enumerate(self._model.loss_functions):\n loss_function.reduction = prev_reduction[i]\n\n loss_value = k.eval(loss)\n\n if reduction == \"none\":\n pass\n elif reduction == \"mean\":\n loss_value = np.mean(loss_value, axis=0)\n elif reduction == \"sum\":\n loss_value = np.sum(loss_value, axis=0)\n\n return loss_value\n\n def compute_loss_from_predictions(\n self, pred: np.ndarray, y: np.ndarray, reduction: str = \"none\", **kwargs\n ) -> np.ndarray:\n \"\"\"\n Compute the MSE loss of the regressor for predictions `pred`. Does not apply preprocessing to the given `y`.\n\n :param pred: Model predictions.\n :param y: Target values.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Loss values.\n \"\"\"\n if not self._losses:\n raise NotImplementedError(\"loss method is only supported for keras versions >= 2.3.1\")\n\n if self.is_tensorflow:\n import tensorflow.keras.backend as k\n else:\n import keras.backend as k\n\n if self._orig_loss and hasattr(self._orig_loss, \"reduction\"):\n prev_reduction = self._orig_loss.reduction\n if hasattr(self._losses, \"Reduction\"):\n self._orig_loss.reduction = self._losses.Reduction.NONE\n loss = self._orig_loss(y, pred)\n self._orig_loss.reduction = prev_reduction\n else:\n prev_reduction = []\n predictions = k.constant(pred)\n y_preprocessed = k.constant(y)\n for loss_function in self._model.loss_functions:\n prev_reduction.append(loss_function.reduction)\n if hasattr(self._losses, \"Reduction\"):\n loss_function.reduction = self._losses.Reduction.NONE\n loss = self._loss_function(y_preprocessed, predictions)\n for i, loss_function in enumerate(self._model.loss_functions):\n loss_function.reduction = prev_reduction[i]\n\n loss_value = k.eval(loss)\n\n if reduction == \"none\":\n pass\n elif reduction == \"mean\":\n loss_value = np.mean(loss_value, axis=0)\n elif reduction == \"sum\":\n loss_value = np.sum(loss_value, axis=0)\n\n return loss_value\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n # Check shape of preprocessed `x` because of custom function for `_loss_gradients`\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n shape_match = [i is None or i == j for i, j in zip(self._input_shape, x_preprocessed.shape[1:])]\n if not all(shape_match): # pragma: no cover\n raise ValueError(\n f\"Error when checking x: expected preprocessed x to have shape {self._input_shape} but got array with \"\n f\"shape {x_preprocessed.shape[1:]}\"\n )\n\n # Compute gradients\n gradients = self._loss_gradients([x_preprocessed, y_preprocessed, int(training_mode)])[0]\n assert gradients.shape == x_preprocessed.shape\n gradients = self._apply_preprocessing_gradient(x, gradients)\n assert gradients.shape == x.shape\n\n return gradients\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n if training_mode:\n predictions = self._model(x_preprocessed, training=training_mode)\n else:\n predictions = self._model.predict(x_preprocessed, batch_size=batch_size)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=predictions, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the regressor on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs or the number of steps per epoch as part of this argument will result in as error.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n self._model.fit(x=x_preprocessed, y=y_preprocessed, batch_size=batch_size, epochs=nb_epochs, **kwargs)\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the regressor using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch. If the generator can be used for native\n training in Keras, it will.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs as part of this argument will result in as error.\n \"\"\"\n from art.data_generators import KerasDataGenerator\n\n # Try to use the generator as a Keras native generator, otherwise use it through the `DataGenerator` interface\n from art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\n\n if isinstance(generator, KerasDataGenerator) and (\n self.preprocessing is None\n or (\n isinstance(self.preprocessing, StandardisationMeanStd)\n and (\n self.preprocessing.mean,\n self.preprocessing.std,\n )\n == (0, 1)\n )\n ):\n try:\n self._model.fit_generator(generator.iterator, epochs=nb_epochs, **kwargs)\n except ValueError: # pragma: no cover\n logger.info(\"Unable to use data generator as Keras generator. Now treating as framework-independent.\")\n if \"verbose\" not in kwargs:\n kwargs[\"verbose\"] = 0\n super().fit_generator(generator, nb_epochs=nb_epochs, **kwargs)\n else: # pragma: no cover\n if \"verbose\" not in kwargs:\n kwargs[\"verbose\"] = 0\n super().fit_generator(generator, nb_epochs=nb_epochs, **kwargs)\n\n def get_activations(\n self, x: np.ndarray, layer: int | str, batch_size: int = 128, framework: bool = False\n ) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations.\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n\n if self.is_tensorflow:\n import tensorflow.keras.backend as k\n else:\n import keras.backend as k\n from art.config import ART_NUMPY_DTYPE\n\n if isinstance(layer, six.string_types):\n if layer not in self._layer_names: # pragma: no cover\n raise ValueError(f\"Layer name {layer} is not part of the graph.\")\n layer_name = layer\n elif isinstance(layer, int):\n if layer < 0 or layer >= len(self._layer_names): # pragma: no cover\n raise ValueError(\n f\"Layer index {layer} is outside of range (0 to {len(self._layer_names) - 1} included).\"\n )\n layer_name = self._layer_names[layer]\n else: # pragma: no cover\n raise TypeError(\"Layer must be of type `str` or `int`.\")\n\n if x.shape == self.input_shape:\n x_expanded = np.expand_dims(x, 0)\n else:\n x_expanded = x\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x=x_expanded, y=None, fit=False)\n\n if not hasattr(self, \"_activations_func\"):\n self._activations_func: dict[str, Callable] = {}\n\n keras_layer = self._model.get_layer(layer_name)\n if layer_name not in self._activations_func:\n num_inbound_nodes = len(getattr(keras_layer, \"_inbound_nodes\", []))\n if num_inbound_nodes > 1:\n layer_output = keras_layer.get_output_at(0)\n else:\n layer_output = keras_layer.output\n self._activations_func[layer_name] = k.function([self._input, k.learning_phase()], [layer_output])\n\n # Determine shape of expected output and prepare array\n output_shape = self._activations_func[layer_name]([x_preprocessed[0][None, ...], int(False)])[0].shape\n activations = np.zeros((x_preprocessed.shape[0],) + output_shape[1:], dtype=ART_NUMPY_DTYPE)\n\n # Get activations with batching\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = (\n batch_index * batch_size,\n min((batch_index + 1) * batch_size, x_preprocessed.shape[0]),\n )\n activations[begin:end] = self._activations_func[layer_name]([x_preprocessed[begin:end], 0])[0]\n\n if framework:\n placeholder = k.placeholder(shape=x.shape)\n return placeholder, keras_layer(placeholder) # type: ignore\n\n return activations\n\n def custom_loss_gradient(self, nn_function, tensors, input_values, name=\"default\"):\n \"\"\"\n Returns the gradient of the nn_function with respect to model input\n\n :param nn_function: an intermediate tensor representation of the function to differentiate\n :type nn_function: a Keras tensor\n :param tensors: the tensors or variables to differentiate with respect to\n :type tensors: `list`\n :param input_values: the inputs to evaluate the gradient\n :type input_values: `list`\n :param name: The name of the function. Functions of the same name are cached\n :type name: `str`\n :return: the gradient of the function w.r.t vars\n :rtype: `np.ndarray`\n \"\"\"\n if self.is_tensorflow:\n import tensorflow.keras.backend as k\n else:\n import keras.backend as k\n\n if not hasattr(self, \"_custom_loss_func\"):\n self._custom_loss_func = {}\n\n if name not in self._custom_loss_func:\n grads = k.gradients(nn_function, tensors[0])[0]\n self._custom_loss_func[name] = k.function(tensors, [grads])\n\n outputs = self._custom_loss_func[name]\n return outputs(input_values)\n\n def _get_layers(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n \"\"\"\n\n if self.is_tensorflow:\n from tensorflow.keras.layers import InputLayer\n else:\n from keras.engine.topology import InputLayer\n\n layer_names = [layer.name for layer in self._model.layers[:-1] if not isinstance(layer, InputLayer)]\n logger.info(\"Inferred %i hidden layers on Keras regressor.\", len(layer_names))\n\n return layer_names\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework. For Keras, .h5 format is used.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n self._model.save(str(full_path))\n logger.info(\"Model saved in path: %s.\", full_path)\n\n def __getstate__(self) -> dict[str, Any]:\n \"\"\"\n Use to ensure `KerasRegressor` can be pickled.\n\n :return: State dictionary with instance parameters.\n \"\"\"\n state = self.__dict__.copy()\n\n # Remove the unpicklable entries\n del state[\"_model\"]\n del state[\"_input\"]\n del state[\"_output\"]\n del state[\"_predictions_op\"]\n del state[\"_loss\"]\n del state[\"_loss_gradients\"]\n del state[\"_layer_names\"]\n del state[\"_losses\"]\n del state[\"_loss_function\"]\n\n if \"_orig_loss\" in state:\n del state[\"_orig_loss\"]\n\n if \"_activations_func\" in state:\n del state[\"_activations_func\"]\n\n if \"_custom_loss_func\" in state:\n del state[\"_custom_loss_func\"]\n\n model_name = str(time.time()) + \".h5\"\n state[\"model_name\"] = model_name\n self.save(model_name)\n return state\n\n def __setstate__(self, state: dict[str, Any]) -> None:\n \"\"\"\n Use to ensure `KerasRegressor` can be unpickled.\n\n :param state: State dictionary with instance parameters to restore.\n \"\"\"\n self.__dict__.update(state)\n\n if self.is_tensorflow:\n from tensorflow.keras.models import load_model\n else:\n from keras.models import load_model\n\n full_path = os.path.join(config.ART_DATA_PATH, state[\"model_name\"])\n model = load_model(str(full_path))\n\n self._model = model\n self._initialize_params(model, state[\"_input_layer\"], state[\"_output_layer\"])\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(model={self._model}, \"\n f\"channels_first={self.channels_first}, clip_values={self.clip_values!r}, \"\n f\"preprocessing_defences={self.preprocessing_defences}, \"\n f\"postprocessing_defences={self.postprocessing_defences}, preprocessing={self.preprocessing}, \"\n f\"input_layer={self._input_layer}, output_layer={self._output_layer})\"\n )\n\n return repr_\n\n\ndef generator_fit(\n x: np.ndarray, y: np.ndarray, batch_size: int = 128\n) -> Iterator[tuple[np.ndarray, np.ndarray]]: # pragma: no cover\n \"\"\"\n Minimal data generator for randomly batching large datasets.\n\n :param x: The data sample to batch.\n :param y: The labels for `x`. The first dimension has to match the first dimension of `x`.\n :param batch_size: The size of the batches to produce.\n :return: A batch of size `batch_size` of random samples from `(x, y)`.\n \"\"\"\n while True:\n indices = np.random.randint(x.shape[0], size=batch_size)\n yield x[indices], y[indices]\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/regression/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the regressor `PyTorchRegressor` for PyTorch models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport copy\nimport logging\nimport os\nimport time\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nimport six\n\nfrom art import config\nfrom art.estimators.regression.regressor import RegressorMixin\nfrom art.estimators.pytorch import PyTorchEstimator\n\nif TYPE_CHECKING:\n\n import torch\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchRegressor(RegressorMixin, PyTorchEstimator):\n \"\"\"\n This class implements a regressor with the PyTorch framework.\n \"\"\"\n\n estimator_params = PyTorchEstimator.estimator_params + [\n \"loss\",\n \"input_shape\",\n \"optimizer\",\n \"use_amp\",\n \"opt_level\",\n \"loss_scale\",\n ]\n\n def __init__(\n self,\n model: \"torch.nn.Module\",\n loss: \"torch.nn.modules.loss._Loss\",\n input_shape: tuple[int, ...],\n optimizer: \"torch.optim.Optimizer\" | None = None, # type: ignore\n use_amp: bool = False,\n opt_level: str = \"O1\",\n loss_scale: float | str | None = \"dynamic\",\n channels_first: bool = True,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n device_type: str = \"gpu\",\n ) -> None:\n \"\"\"\n Initialization specifically for the PyTorch-based implementation.\n\n :param model: PyTorch model. The output of the model can be logits, probabilities or anything else. Logits\n output should be preferred where possible to ensure attack efficiency.\n :param loss: The loss function for which to compute gradients for training. The target label must be raw\n categorical, i.e. not converted to one-hot encoding.\n :param input_shape: The shape of one input instance.\n :param optimizer: The optimizer used to train the regressor.\n :param use_amp: Whether to use the automatic mixed precision tool to enable mixed precision training or\n gradient computation, e.g. with loss gradient computation. When set to True, this option is\n only triggered if there are GPUs available.\n :param opt_level: Specify a pure or mixed precision optimization level. Used when use_amp is True. Accepted\n values are `O0`, `O1`, `O2`, and `O3`.\n :param loss_scale: Loss scaling. Used when use_amp is True. If passed as a string, must be a string\n representing a number, e.g., \u201c1.0\u201d, or the string \u201cdynamic\u201d.\n :param optimizer: The optimizer used to train the regressor.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the regressor.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the regressor.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the regressor is run, either `gpu` or `cpu`.\n \"\"\"\n import torch\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n device_type=device_type,\n )\n self._input_shape = input_shape\n self._model = self._make_model_wrapper(model)\n self._loss = loss\n self._optimizer = optimizer\n self._use_amp = use_amp\n self._learning_phase: bool | None = None\n self._opt_level = opt_level\n self._loss_scale = loss_scale\n\n # Check if model is RNN-like to decide if freezing batch-norm and dropout layers might be required for loss and\n # class gradient calculation\n self.is_rnn = any((isinstance(m, torch.nn.modules.RNNBase) for m in self._model.modules()))\n\n # Get the internal layers\n self._layer_names: list[str] = self._model.get_layers # type: ignore\n\n self._model.to(self._device)\n\n # Index of layer at which the class gradients should be calculated\n self._layer_idx_gradients = -1\n\n # Setup for AMP use\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n if self._optimizer is None:\n logger.warning(\n \"An optimizer is needed to use the automatic mixed precision tool, but none for provided. \"\n \"A default optimizer is used.\"\n )\n\n # Create the optimizers\n parameters = self._model.parameters()\n self._optimizer = torch.optim.SGD(parameters, lr=0.01)\n\n if self.device.type == \"cpu\":\n enabled = False\n else:\n enabled = True\n\n self._model, self._optimizer = amp.initialize(\n models=self._model,\n optimizers=self._optimizer,\n enabled=enabled,\n opt_level=opt_level,\n loss_scale=loss_scale,\n )\n\n @property\n def device(self) -> \"torch.device\":\n \"\"\"\n Get current used device.\n\n :return: Current used device.\n \"\"\"\n return self._device\n\n @property\n def model(self) -> \"torch.nn.Module\":\n return self._model._model\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def loss(self) -> \"torch.nn.modules.loss._Loss\":\n \"\"\"\n Return the loss function.\n\n :return: The loss function.\n \"\"\"\n return self._loss # type: ignore\n\n @property\n def optimizer(self) -> \"torch.optim.Optimizer\":\n \"\"\"\n Return the optimizer.\n\n :return: The optimizer.\n \"\"\"\n return self._optimizer # type: ignore\n\n @property\n def use_amp(self) -> bool:\n \"\"\"\n Return a boolean indicating whether to use the automatic mixed precision tool.\n\n :return: Whether to use the automatic mixed precision tool.\n \"\"\"\n return self._use_amp # type: ignore\n\n @property\n def opt_level(self) -> str:\n \"\"\"\n Return a string specifying a pure or mixed precision optimization level.\n\n :return: A string specifying a pure or mixed precision optimization level. Possible\n values are `O0`, `O1`, `O2`, and `O3`.\n \"\"\"\n return self._opt_level # type: ignore\n\n @property\n def loss_scale(self) -> float | str:\n \"\"\"\n Return the loss scaling value.\n\n :return: Loss scaling. Possible values for string: a string representing a number, e.g., \u201c1.0\u201d,\n or the string \u201cdynamic\u201d.\n \"\"\"\n return self._loss_scale # type: ignore\n\n def predict(self, x: np.ndarray, batch_size: int = 128, training_mode: bool = False, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n dataset = TensorDataset(x_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=False)\n\n results_list = []\n for (x_batch,) in dataloader:\n # Move inputs to device\n x_batch = x_batch.to(self._device)\n\n # Run prediction\n with torch.no_grad():\n model_outputs = self._model(x_batch)\n output = model_outputs[-1]\n output = output.detach().cpu().numpy().astype(np.float32)\n if len(output.shape) == 1:\n output = np.expand_dims(output, axis=1).astype(np.float32)\n\n results_list.append(output)\n\n results = np.vstack(results_list)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=results, fit=False)\n\n return predictions\n\n def _predict_framework(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :return: Tensor of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y=y, fit=False, no_grad=False)\n\n # Put the model in the eval mode\n self._model.eval()\n\n model_outputs = self._model(x_preprocessed)\n output = model_outputs[-1]\n\n return output, y_preprocessed\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n batch_size: int = 128,\n nb_epochs: int = 10,\n training_mode: bool = True,\n drop_last: bool = False,\n scheduler: \"torch.optim.lr_scheduler._LRScheduler\" | None = None,\n **kwargs,\n ) -> None:\n \"\"\"\n Fit the regressor on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or index labels of\n shape (nb_samples,).\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param drop_last: Set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by\n the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then\n the last batch will be smaller. (default: ``False``)\n :param scheduler: Learning rate scheduler to run at the start of every epoch.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from torch.utils.data import TensorDataset, DataLoader\n\n # Set model mode\n self._model.train(mode=training_mode)\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Create dataloader\n x_tensor = torch.from_numpy(x_preprocessed)\n y_tensor = torch.from_numpy(y_preprocessed)\n dataset = TensorDataset(x_tensor, y_tensor)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)\n\n # Start training\n for _ in range(nb_epochs):\n # Train for one epoch\n for x_batch, y_batch in dataloader:\n # Move inputs to device\n x_batch = x_batch.to(self._device)\n y_batch = y_batch.to(self._device)\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Perform prediction\n model_outputs = self._model(x_batch)\n\n # Form the loss function\n loss = self._loss(model_outputs[-1].reshape(-1), y_batch)\n\n # Do training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n self._optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the regressor using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import torch\n from art.data_generators import PyTorchDataGenerator\n\n # Put the model in the training mode\n self._model.train()\n\n if self._optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is needed to train the model, but none for provided.\")\n\n # Train directly in PyTorch\n from art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\n\n if isinstance(generator, PyTorchDataGenerator) and (\n self.preprocessing is None\n or (\n isinstance(self.preprocessing, StandardisationMeanStdPyTorch)\n and (\n self.preprocessing.mean,\n self.preprocessing.std,\n )\n == (0, 1)\n )\n ):\n for _ in range(nb_epochs):\n for i_batch, o_batch in generator.iterator:\n if isinstance(i_batch, np.ndarray):\n i_batch = torch.from_numpy(i_batch).to(self._device)\n else:\n i_batch = i_batch.to(self._device)\n\n if isinstance(o_batch, np.ndarray):\n o_batch = torch.argmax(torch.from_numpy(o_batch).to(self._device), dim=1)\n else:\n o_batch = torch.argmax(o_batch.to(self._device), dim=1)\n\n # Zero the parameter gradients\n self._optimizer.zero_grad()\n\n # Perform prediction\n model_outputs = self._model(i_batch)\n\n # Form the loss function\n loss = self._loss(\n model_outputs[-1].reshape(\n -1,\n ),\n o_batch,\n )\n\n # Do training\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self._optimizer.step()\n\n else:\n # Fit a generic data generator through the API\n super().fit_generator(generator, nb_epochs=nb_epochs)\n\n def clone_for_refitting(self) -> \"PyTorchRegressor\":\n \"\"\"\n Create a copy of the regressor that can be refit from scratch. Will inherit same architecture, optimizer and\n initialization as cloned model, but without weights.\n\n :return: new estimator\n \"\"\"\n model = copy.deepcopy(self.model)\n clone = type(self)(model, self._loss, self.input_shape, optimizer=self._optimizer)\n # reset weights\n clone.reset()\n params = self.get_params()\n del params[\"model\"]\n clone.set_params(**params)\n return clone\n\n def reset(self) -> None:\n \"\"\"\n Resets the weights of the regressor so that it can be refit from scratch.\n\n \"\"\"\n\n def weight_reset(module):\n reset_parameters = getattr(module, \"reset_parameters\", None)\n if reset_parameters and callable(reset_parameters):\n module.reset_parameters()\n\n self.model.apply(weight_reset)\n\n def compute_loss( # type: ignore\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n reduction: str = \"none\",\n **kwargs,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the loss.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Array of losses of the same shape as `x`.\n \"\"\"\n import torch\n\n self._model.eval()\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n # Check label shape\n # y_preprocessed = self.reduce_labels(y_preprocessed)\n\n if isinstance(x, torch.Tensor):\n inputs_t = x_preprocessed\n labels_t = y_preprocessed\n else:\n # Convert the inputs to Tensors\n inputs_t = torch.from_numpy(x_preprocessed).to(self._device)\n # Convert the labels to Tensors\n labels_t = torch.from_numpy(y_preprocessed).to(self._device)\n\n # Compute the loss and return\n model_outputs = self._model(inputs_t)\n prev_reduction = self._loss.reduction\n\n # Return individual loss values\n self._loss.reduction = reduction\n loss = self._loss(\n model_outputs[-1].reshape(\n -1,\n ),\n labels_t,\n )\n self._loss.reduction = prev_reduction\n\n if isinstance(x, torch.Tensor):\n return loss\n\n return loss.detach().cpu().numpy()\n\n def compute_loss_from_predictions( # type: ignore\n self, pred: np.ndarray, y: np.ndarray, reduction: str = \"none\", **kwargs\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the loss of the regressor for predictions `pred`. Does not apply preprocessing to the given `y`.\n\n :param pred: Model predictions.\n :param y: Target values.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Loss values.\n \"\"\"\n import torch\n\n if isinstance(y, torch.Tensor):\n labels_t = y\n else:\n # Convert the labels to Tensors\n labels_t = torch.from_numpy(y).to(self._device)\n\n prev_reduction = self._loss.reduction\n\n # Return individual loss values\n self._loss.reduction = reduction\n loss = self._loss(\n pred[-1].reshape(\n -1,\n ),\n labels_t,\n )\n self._loss.reduction = prev_reduction\n\n if isinstance(y, torch.Tensor):\n return loss\n\n return loss.detach().cpu().numpy()\n\n def compute_losses(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n reduction: str = \"none\",\n ) -> dict[str, np.ndarray | \"torch.Tensor\"]:\n \"\"\"\n Compute all loss components.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices\n of shape `(nb_samples,)`.\n :param reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.\n 'none': no reduction will be applied\n 'mean': the sum of the output will be divided by the number of elements in the output,\n 'sum': the output will be summed.\n :return: Dictionary of loss components.\n \"\"\"\n return {\"total\": self.compute_loss(x=x, y=y, reduction=reduction)}\n\n def loss_gradient(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n training_mode: bool = False,\n **kwargs,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n `(nb_samples,)`.\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n Note on RNN-like models: Backpropagation through RNN modules in eval mode raises\n RuntimeError due to cudnn issues and require training mode, i.e. RuntimeError: cudnn RNN\n backward can only be called in training mode. Therefore, if the model is an RNN type we\n always use training mode but freeze batch-norm and dropout layers if\n `training_mode=False.`\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import torch\n\n self._model.train(mode=training_mode)\n\n # Backpropagation through RNN modules in eval mode raises RuntimeError due to cudnn issues and require training\n # mode, i.e. RuntimeError: cudnn RNN backward can only be called in training mode. Therefore, if the model is\n # an RNN type we always use training mode but freeze batch-norm and dropout layers if training_mode=False.\n if self.is_rnn:\n self._model.train(mode=True)\n if not training_mode:\n logger.debug(\n \"Freezing batch-norm and dropout layers for gradient calculation in train mode with eval parameters\"\n \"of batch-norm and dropout.\"\n )\n self.set_batchnorm(train=False)\n self.set_dropout(train=False)\n\n # Apply preprocessing\n if self.all_framework_preprocessing:\n if isinstance(x, torch.Tensor):\n x_grad = x.clone().detach().requires_grad_(True)\n else:\n x_grad = torch.tensor(x).to(self._device)\n x_grad.requires_grad = True\n if isinstance(y, torch.Tensor):\n y_grad = y.clone().detach()\n else:\n y_grad = torch.tensor(y).to(self._device)\n inputs_t, y_preprocessed = self._apply_preprocessing(x_grad, y=y_grad, fit=False, no_grad=False)\n elif isinstance(x, np.ndarray):\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y=y, fit=False, no_grad=True)\n x_grad = torch.from_numpy(x_preprocessed).to(self._device)\n x_grad.requires_grad = True\n inputs_t = x_grad\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n # Check label shape\n # y_preprocessed = self.reduce_labels(y_preprocessed)\n\n if isinstance(y_preprocessed, np.ndarray):\n labels_t = torch.from_numpy(y_preprocessed).to(self._device)\n else:\n labels_t = y_preprocessed\n\n # Compute the gradient and return\n model_outputs = self._model(inputs_t)\n loss = self._loss(\n model_outputs[-1].reshape(\n -1,\n ),\n labels_t,\n )\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n grads: torch.Tensor | np.ndarray\n\n if x_grad.grad is not None:\n if isinstance(x, torch.Tensor):\n grads = x_grad.grad\n else:\n grads = x_grad.grad.cpu().numpy().copy()\n else:\n raise ValueError(\"Gradient tensor in PyTorch model is `None`.\")\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n assert grads.shape == x.shape\n\n return grads\n\n def custom_loss_gradient(\n self,\n loss_fn,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | \"torch.Tensor\",\n layer_name,\n training_mode: bool = False,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param loss_fn: Loss function w.r.t to which gradient needs to be calculated.\n :param x: Sample input with shape as expected by the model(base image).\n :param y: Sample input with shape as expected by the model(target image).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.`\n :param layer_name: Name of the layer from which activation needs to be extracted/activation layer.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n import torch\n\n self._model.train(mode=training_mode)\n self._model.eval()\n if self.all_framework_preprocessing:\n if isinstance(x, torch.Tensor):\n x_grad = x.clone().detach().requires_grad_(True)\n else:\n x_grad = torch.tensor(x).to(self._device)\n x_grad.requires_grad = True\n if isinstance(y, torch.Tensor):\n y_grad = y.clone().detach()\n else:\n y_grad = torch.tensor(y).to(self._device)\n inputs_t, _ = self._apply_preprocessing(x_grad, y=None, fit=False, no_grad=False)\n targets_t, _ = self._apply_preprocessing(y_grad, y=None, fit=False, no_grad=False)\n if isinstance(x, np.ndarray):\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False, no_grad=True)\n y_preprocessed, _ = self._apply_preprocessing(y, y=None, fit=False, no_grad=True)\n x_grad = torch.from_numpy(x_preprocessed).to(self._device)\n y_grad = torch.from_numpy(y_preprocessed).to(self._device)\n x_grad.requires_grad = True\n y_grad.requires_grad = False\n inputs_t = x_grad\n targets_t = y_grad\n else:\n raise NotImplementedError(\"Combination of inputs and preprocessing not supported.\")\n\n # Compute the gradient and return\n model_outputs1 = self.get_activations(inputs_t, layer_name, 1, framework=True)\n model_outputs2 = self.get_activations(targets_t, layer_name, 1, framework=True)\n diff = model_outputs1 - model_outputs2\n loss = loss_fn(diff, p=2)\n\n # Clean gradients\n self._model.zero_grad()\n\n # Compute gradients\n if self._use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self._optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n if isinstance(x, torch.Tensor):\n grads = x_grad.grad\n else:\n grads = x_grad.grad.cpu().numpy().copy() # type: ignore\n\n if not self.all_framework_preprocessing:\n grads = self._apply_preprocessing_gradient(x, grads)\n\n assert grads.shape == x.shape\n\n return grads\n\n def get_activations( # type: ignore\n self,\n x: np.ndarray | \"torch.Tensor\",\n layer: int | str | None = None,\n batch_size: int = 128,\n framework: bool = False,\n ) -> np.ndarray | \"torch.Tensor\":\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n import torch\n\n self._model.eval()\n\n # Apply defences\n if framework:\n no_grad = False\n else:\n no_grad = True\n x_preprocessed, _ = self._apply_preprocessing(x=x, y=None, fit=False, no_grad=no_grad)\n\n # Get index of the extracted layer\n if isinstance(layer, six.string_types):\n if layer not in self._layer_names: # pragma: no cover\n raise ValueError(f\"Layer name {layer} not supported\")\n layer_index = self._layer_names.index(layer)\n\n elif isinstance(layer, int):\n layer_index = layer\n\n else: # pragma: no cover\n raise TypeError(\"Layer must be of type str or int\")\n\n def get_feature(name):\n # the hook signature\n def hook(model, input, output): # pylint: disable=redefined-builtin,unused-argument\n self._features[name] = output\n\n return hook\n\n if not hasattr(self, \"_features\"):\n self._features: dict[str, torch.Tensor] = {}\n # register forward hooks on the layers of choice\n\n if layer not in self._features:\n interim_layer = dict([*self._model._model.named_modules()])[self._layer_names[layer_index]]\n interim_layer.register_forward_hook(get_feature(self._layer_names[layer_index]))\n\n if framework:\n if isinstance(x_preprocessed, torch.Tensor):\n self._model(x_preprocessed)\n return self._features[self._layer_names[layer_index]]\n input_tensor = torch.from_numpy(x_preprocessed)\n self._model(input_tensor.to(self._device))\n return self._features[self._layer_names[layer_index]]\n\n # Run prediction with batch processing\n results = []\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Run prediction for the current batch\n self._model(torch.from_numpy(x_preprocessed[begin:end]).to(self._device))\n layer_output = self._features[self._layer_names[layer_index]]\n results.append(layer_output.detach().cpu().numpy())\n\n results_array = np.concatenate(results)\n\n return results_array\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n import torch\n\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # disable pylint because access to _modules required\n torch.save(self._model._model.state_dict(), full_path + \".model\")\n torch.save(self._optimizer.state_dict(), full_path + \".optimizer\") # type: ignore\n logger.info(\"Model state dict saved in path: %s.\", full_path + \".model\")\n logger.info(\"Optimizer state dict saved in path: %s.\", full_path + \".optimizer\")\n\n def __getstate__(self) -> dict[str, Any]:\n \"\"\"\n Use to ensure `PyTorchRegressor` can be pickled.\n\n :return: State dictionary with instance parameters.\n \"\"\"\n\n # disable pylint because access to _model required\n state = self.__dict__.copy()\n state[\"inner_model\"] = copy.copy(state[\"_model\"]._model)\n\n # Remove the unpicklable entries\n del state[\"_model_wrapper\"]\n del state[\"_device\"]\n del state[\"_model\"]\n\n model_name = str(time.time())\n state[\"model_name\"] = model_name\n self.save(model_name)\n\n return state\n\n def __setstate__(self, state: dict[str, Any]) -> None:\n \"\"\"\n Use to ensure `PyTorchRegressor` can be unpickled.\n\n :param state: State dictionary with instance parameters to restore.\n \"\"\"\n import torch\n\n # Recover model\n self.__dict__.update(state)\n full_path = os.path.join(config.ART_DATA_PATH, state[\"model_name\"])\n model = state[\"inner_model\"]\n model.load_state_dict(torch.load(str(full_path) + \".model\"))\n model.eval()\n self._model = self._make_model_wrapper(model)\n\n # Recover device\n self._device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self._model.to(self._device)\n\n # Recover optimizer\n self._optimizer.load_state_dict(torch.load(str(full_path) + \".optimizer\")) # type: ignore\n\n self.__dict__.pop(\"model_name\", None)\n self.__dict__.pop(\"inner_model\", None)\n\n def __repr__(self):\n repr_ = (\n f\"{self.__module__ + '.' + self.__class__.__name__}(model={self._model}, loss={self._loss}, \"\n f\"optimizer={self._optimizer}, input_shape={self._input_shape}, \"\n f\"channels_first={self.channels_first}, clip_values={self.clip_values!r}, \"\n f\"preprocessing_defences={self.preprocessing_defences}, \"\n f\"postprocessing_defences={self.postprocessing_defences}, preprocessing={self.preprocessing})\"\n )\n\n return repr_\n\n def _make_model_wrapper(self, model: \"torch.nn.Module\") -> \"torch.nn.Module\":\n # Try to import PyTorch and create an internal class that acts like a model wrapper extending torch.nn.Module\n try:\n import torch\n\n # Define model wrapping class only if not defined before\n if not hasattr(self, \"_model_wrapper\"):\n\n class ModelWrapper(torch.nn.Module):\n \"\"\"\n This is a wrapper for the input model.\n \"\"\"\n\n import torch\n\n def __init__(self, model: torch.nn.Module):\n \"\"\"\n Initialization by storing the input model.\n\n :param model: PyTorch model. The forward function of the model must return the logit output.\n \"\"\"\n super().__init__()\n self._model = model\n\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n This is where we get outputs from the input model.\n\n :param x: Input data.\n :type x: `torch.Tensor`\n :return: a list of output layers, where the last 2 layers are logit and final outputs.\n :rtype: `list`\n \"\"\"\n\n # disable pylint because access to _model required\n\n result = []\n if isinstance(self._model, torch.nn.Sequential):\n for _, module_ in self._model._modules.items():\n x = module_(x)\n result.append(x)\n\n elif isinstance(self._model, torch.nn.Module):\n x = self._model(x)\n result.append(x)\n\n else: # pragma: no cover\n raise TypeError(\"The input model must inherit from `nn.Module`.\")\n\n return result\n\n @property\n def get_layers(self) -> list[str]:\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n\n .. warning:: `get_layers` tries to infer the internal structure of the model.\n This feature comes with no guarantees on the correctness of the result.\n The intended order of the layers tries to match their order in the model, but this\n is not guaranteed either. In addition, the function can only infer the internal\n layers if the input model is of type `nn.Sequential`, otherwise, it will only\n return the logit layer.\n \"\"\"\n import torch\n\n result = []\n if isinstance(self._model, torch.nn.Module):\n for name, _ in self._model._modules.items():\n result.append(name)\n\n else: # pragma: no cover\n raise TypeError(\"The input model must inherit from `nn.Module`.\")\n logger.info(\n \"Inferred %i hidden layers on PyTorch regressor.\",\n len(result),\n )\n\n return result\n\n # Set newly created class as private attribute\n self._model_wrapper = ModelWrapper\n\n # Use model wrapping class to wrap the PyTorch model received as argument\n return self._model_wrapper(model)\n\n except ImportError: # pragma: no cover\n raise ImportError(\"Could not find PyTorch (`torch`) installation.\") from ImportError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/regression/regressor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements mixin abstract base class for all regressors in ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC\n\nfrom art.estimators.estimator import BaseEstimator\n\n\nclass RegressorMixin(ABC):\n \"\"\"\n Mixin abstract Base class for ART regressors.\n \"\"\"\n\n\nclass Regressor(RegressorMixin, BaseEstimator, ABC):\n \"\"\"\n Typing variable definition.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/regression/scikitlearn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the regressors for scikit-learn models.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport pickle\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.scikitlearn import ScikitlearnEstimator\nfrom art.estimators.regression.regressor import RegressorMixin\nfrom art import config\n\nif TYPE_CHECKING:\n\n import sklearn\n\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n from art.metrics.verification_decisions_trees import LeafNode\n\nlogger = logging.getLogger(__name__)\n\n\nclass ScikitlearnRegressor(RegressorMixin, ScikitlearnEstimator):\n \"\"\"\n Wrapper class for scikit-learn regression models.\n \"\"\"\n\n estimator_params = ScikitlearnEstimator.estimator_params\n\n def __init__(\n self,\n model: \"sklearn.base.BaseEstimator\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Regressor` instance from a scikit-learn regressor model.\n\n :param model: scikit-learn regressor model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._input_shape = self._get_input_shape(model)\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n def fit(self, x: np.ndarray, y: np.ndarray, **kwargs) -> None:\n \"\"\"\n Fit the regressor on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values.\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit` function in `sklearn` regressor and will be passed to this function as such.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n self.model.fit(x_preprocessed, y_preprocessed, **kwargs)\n self._input_shape = self._get_input_shape(self.model)\n\n def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :return: Array of predictions.\n :raises `ValueError`: If the regressor does not have the method `predict`\n \"\"\"\n # Apply defences\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n if callable(getattr(self.model, \"predict\", None)):\n y_pred = self.model.predict(x_preprocessed)\n else:\n raise ValueError(\"The provided model does not have the method `predict`.\")\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=y_pred, fit=False)\n\n return predictions\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n if path is None:\n full_path = os.path.join(config.ART_DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n with open(full_path + \".pickle\", \"wb\") as file_pickle:\n pickle.dump(self.model, file=file_pickle)\n\n def clone_for_refitting(self) -> \"ScikitlearnRegressor\":\n \"\"\"\n Create a copy of the classifier that can be refit from scratch.\n\n :return: new estimator\n \"\"\"\n import sklearn\n\n clone = type(self)(sklearn.base.clone(self.model))\n params = self.get_params()\n del params[\"model\"]\n clone.set_params(**params)\n return clone\n\n def reset(self) -> None:\n \"\"\"\n Resets the weights of the classifier so that it can be refit from scratch.\n\n \"\"\"\n # No need to do anything since scikitlearn models start from scratch each time fit() is called\n pass\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the MSE loss of the regressor for samples `x`.\n\n :param x: Input samples.\n :param y: Target values.\n :return: Loss values.\n \"\"\"\n\n return (y - self.predict(x)) ** 2\n\n def compute_loss_from_predictions(self, pred: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the MSE loss of the regressor for predictions `pred`.\n\n :param pred: Model predictions.\n :param y: Target values.\n :return: Loss values.\n \"\"\"\n\n return (y - pred) ** 2\n\n\nclass ScikitlearnDecisionTreeRegressor(ScikitlearnRegressor):\n \"\"\"\n Wrapper class for scikit-learn Decision Tree Regressor models.\n \"\"\"\n\n def __init__(\n self,\n model: \"sklearn.tree.DecisionTreeRegressor\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Create a `Regressor` instance from a scikit-learn Decision Tree Regressor model.\n\n :param model: scikit-learn Decision Tree Regressor model.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n\n import sklearn\n\n if not isinstance(model, sklearn.tree.DecisionTreeRegressor):\n raise TypeError(\"Model must be of type sklearn.tree.DecisionTreeRegressor.\")\n\n super().__init__(\n model=model,\n clip_values=clip_values,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self._model = model\n\n def get_values_at_node(self, node_id: int) -> np.ndarray:\n \"\"\"\n Returns the feature of given id for a node.\n\n :return: Normalized values at node node_id.\n \"\"\"\n return self.model.tree_.value[node_id]\n\n def get_left_child(self, node_id: int) -> int:\n \"\"\"\n Returns the id of the left child node of node_id.\n\n :return: The indices of the left child in the tree.\n \"\"\"\n return self.model.tree_.children_left[node_id]\n\n def get_right_child(self, node_id: int) -> int:\n \"\"\"\n Returns the id of the right child node of node_id.\n\n :return: The indices of the right child in the tree.\n \"\"\"\n return self.model.tree_.children_right[node_id]\n\n def get_decision_path(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the path through nodes in the tree when classifying x. Last one is leaf, first one root node.\n\n :return: The indices of the nodes in the array structure of the tree.\n \"\"\"\n if len(np.shape(x)) == 1:\n return self.model.decision_path(x.reshape(1, -1)).indices\n\n return self.model.decision_path(x).indices\n\n def get_threshold_at_node(self, node_id: int) -> float:\n \"\"\"\n Returns the threshold of given id for a node.\n\n :return: Threshold value of feature split in this node.\n \"\"\"\n return self.model.tree_.threshold[node_id]\n\n def get_feature_at_node(self, node_id: int) -> int:\n \"\"\"\n Returns the feature of given id for a node.\n\n :return: Feature index of feature split in this node.\n \"\"\"\n return self.model.tree_.feature[node_id]\n\n def get_samples_at_node(self, node_id: int) -> int:\n \"\"\"\n Returns the number of training samples mapped to a node.\n\n :return: Number of samples mapped this node.\n \"\"\"\n return self.model.tree_.n_node_samples[node_id]\n\n def _get_leaf_nodes(self, node_id, i_tree, class_label, box) -> list[\"LeafNode\"]:\n from art.metrics.verification_decisions_trees import LeafNode, Box, Interval\n\n leaf_nodes: list[LeafNode] = []\n\n if self.get_left_child(node_id) != self.get_right_child(node_id):\n\n node_left = self.get_left_child(node_id)\n node_right = self.get_right_child(node_id)\n\n box_left = deepcopy(box)\n box_right = deepcopy(box)\n\n feature = self.get_feature_at_node(node_id)\n box_split_left = Box(intervals={feature: Interval(-np.inf, self.get_threshold_at_node(node_id))})\n box_split_right = Box(intervals={feature: Interval(self.get_threshold_at_node(node_id), np.inf)})\n\n if box.intervals:\n box_left.intersect_with_box(box_split_left)\n box_right.intersect_with_box(box_split_right)\n else:\n box_left = box_split_left\n box_right = box_split_right\n\n leaf_nodes += self._get_leaf_nodes(node_left, i_tree, class_label, box_left)\n leaf_nodes += self._get_leaf_nodes(node_right, i_tree, class_label, box_right)\n\n else:\n leaf_nodes.append(\n LeafNode(\n tree_id=i_tree,\n class_label=class_label,\n node_id=node_id,\n box=box,\n value=self.get_values_at_node(node_id)[0, 0],\n )\n )\n\n return leaf_nodes\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/speech_recognition/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule containing estimators for speech recognition.\n\"\"\"\n\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin\n\nfrom art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\nfrom art.estimators.speech_recognition.pytorch_espresso import PyTorchEspresso\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/speech_recognition/pytorch_deep_speech.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for DeepSpeech, an end-to-end speech recognition in English and\nMandarin in PyTorch.\n\n| Paper link: https://arxiv.org/abs/1512.02595\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art import config\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin, PytorchSpeechRecognizerMixin\nfrom art.utils import get_file\n\nif TYPE_CHECKING:\n import torch\n from deepspeech_pytorch.model import DeepSpeech\n\n from art.defences.postprocessor.postprocessor import Postprocessor\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass PyTorchDeepSpeech(PytorchSpeechRecognizerMixin, SpeechRecognizerMixin, PyTorchEstimator):\n \"\"\"\n This class implements a model-specific automatic speech recognizer using the end-to-end speech recognizer\n DeepSpeech and PyTorch. It supports both version 2 and version 3 of DeepSpeech models as released at\n https://github.com/SeanNaren/deepspeech.pytorch.\n\n | Paper link: https://arxiv.org/abs/1512.02595\n \"\"\"\n\n estimator_params = PyTorchEstimator.estimator_params + [\"optimizer\", \"use_amp\", \"opt_level\", \"lm_config\", \"verbose\"]\n\n def __init__(\n self,\n model: \"DeepSpeech\" | None = None,\n pretrained_model: str | None = None,\n filename: str | None = None,\n url: str | None = None,\n use_half: bool = False,\n optimizer: \"torch.optim.Optimizer\" | None = None, # type: ignore\n use_amp: bool = False,\n opt_level: str = \"O1\",\n decoder_type: str = \"greedy\",\n lm_path: str = \"\",\n top_paths: int = 1,\n alpha: float = 0.0,\n beta: float = 0.0,\n cutoff_top_n: int = 40,\n cutoff_prob: float = 1.0,\n beam_width: int = 10,\n lm_workers: int = 4,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n device_type: str = \"gpu\",\n verbose: bool = True,\n ):\n \"\"\"\n Initialization of an instance PyTorchDeepSpeech.\n\n :param model: DeepSpeech model.\n :param pretrained_model: The choice of pretrained model if a pretrained model is required. Currently, this\n estimator supports 3 different pretrained models consisting of `an4`, `librispeech`\n and `tedlium`.\n :param filename: Name of the file.\n :param url: Download URL.\n :param use_half: Whether to use FP16 for pretrained model.\n :param optimizer: The optimizer used to train the estimator.\n :param use_amp: Whether to use the automatic mixed precision tool to enable mixed precision training or\n gradient computation, e.g. with loss gradient computation. When set to True, this option is\n only triggered if there are GPUs available.\n :param opt_level: Specify a pure or mixed precision optimization level. Used when use_amp is True. Accepted\n values are `O0`, `O1`, `O2`, and `O3`.\n :param decoder_type: Decoder type. Either `greedy` or `beam`. This parameter is only used when users want\n transcription outputs.\n :param lm_path: Path to an (optional) kenlm language model for use with beam search. This parameter is only\n used when users want transcription outputs.\n :param top_paths: Number of beams to be returned. This parameter is only used when users want transcription\n outputs.\n :param alpha: The weight used for the language model. This parameter is only used when users want transcription\n outputs.\n :param beta: Language model word bonus (all words). This parameter is only used when users want transcription\n outputs.\n :param cutoff_top_n: Cutoff_top_n characters with the highest probs in vocabulary will be used in beam search.\n This parameter is only used when users want transcription outputs.\n :param cutoff_prob: Cutoff probability in pruning. This parameter is only used when users want transcription\n outputs.\n :param beam_width: The width of beam to be used. This parameter is only used when users want transcription\n outputs.\n :param lm_workers: Number of language model processes to use. This parameter is only used when users want\n transcription outputs.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the estimator.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the estimator.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n \"\"\"\n import torch\n from deepspeech_pytorch.model import DeepSpeech\n from deepspeech_pytorch.configs.inference_config import LMConfig\n from deepspeech_pytorch.enums import DecoderType\n from deepspeech_pytorch.utils import load_decoder, load_model\n\n # Super initialization\n super().__init__(\n model=None,\n clip_values=clip_values,\n channels_first=None,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n # Check DeepSpeech version\n if str(DeepSpeech.__base__) == \"\":\n self._version = 2\n elif str(DeepSpeech.__base__) in [\n \"\",\n \"\",\n ]:\n self._version = 3\n else:\n raise NotImplementedError(\"Only DeepSpeech version 2 and DeepSpeech version 3 are currently supported.\")\n\n self.verbose = verbose\n\n # Check clip values\n if self.clip_values is not None:\n if not np.all(self.clip_values[0] == -1): # pragma: no cover\n raise ValueError(\"This estimator requires normalized input audios with clip_vales=(-1, 1).\")\n if not np.all(self.clip_values[1] == 1): # pragma: no cover\n raise ValueError(\"This estimator requires normalized input audios with clip_vales=(-1, 1).\")\n\n # Check postprocessing defences\n if self.postprocessing_defences is not None: # pragma: no cover\n raise ValueError(\"This estimator does not support `postprocessing_defences`.\")\n\n # Set cpu/gpu device\n self._device: torch.device\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self._device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self._device = torch.device(f\"cuda:{cuda_idx}\")\n\n self._input_shape = None\n\n # Load model\n if model is None:\n if self._version == 2:\n if pretrained_model == \"an4\": # pragma: no cover\n filename, url = (\n \"an4_pretrained_v2.pth\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/v2.0/an4_pretrained_v2.pth\",\n )\n\n elif pretrained_model == \"librispeech\":\n filename, url = (\n \"librispeech_pretrained_v2.pth\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/v2.0/\"\n \"librispeech_pretrained_v2.pth\",\n )\n\n elif pretrained_model == \"tedlium\": # pragma: no cover\n filename, url = (\n \"ted_pretrained_v2.pth\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/v2.0/ted_pretrained_v2.pth\",\n )\n\n elif pretrained_model is None: # pragma: no cover\n # If model is None and no pretrained model is selected, then we need to have parameters filename\n # and url to download, extract and load the automatic speech recognition model\n if filename is None or url is None:\n filename, url = (\n \"librispeech_pretrained_v2.pth\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/v2.0/\"\n \"librispeech_pretrained_v2.pth\",\n )\n\n else: # pragma: no cover\n raise ValueError(f\"The input pretrained model {pretrained_model} is not supported.\")\n\n # Download model\n model_path = get_file(\n filename=filename, path=config.ART_DATA_PATH, url=url, extract=False, verbose=self.verbose\n )\n\n # Then load model\n self._model = load_model(device=self._device, model_path=model_path, use_half=use_half)\n\n else:\n if pretrained_model == \"an4\": # pragma: no cover\n filename, url = (\n \"an4_pretrained_v3.ckpt\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/V3.0/an4_pretrained_v3.ckpt\",\n )\n\n elif pretrained_model == \"librispeech\":\n filename, url = (\n \"librispeech_pretrained_v3.ckpt\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/V3.0/\"\n \"librispeech_pretrained_v3.ckpt\",\n )\n\n elif pretrained_model == \"tedlium\": # pragma: no cover\n filename, url = (\n \"ted_pretrained_v3.ckpt\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/V3.0/ted_pretrained_v3.ckpt\",\n )\n\n elif pretrained_model is None: # pragma: no cover\n # If model is None and no pretrained model is selected, then we need to have parameters filename and\n # url to download, extract and load the automatic speech recognition model\n if filename is None or url is None:\n filename, url = (\n \"librispeech_pretrained_v3.ckpt\",\n \"https://github.com/SeanNaren/deepspeech.pytorch/releases/download/V3.0/\"\n \"librispeech_pretrained_v3.ckpt\",\n )\n\n else: # pragma: no cover\n raise ValueError(f\"The input pretrained model {pretrained_model} is not supported.\")\n\n # Download model\n model_path = get_file(\n filename=filename, path=config.ART_DATA_PATH, url=url, extract=False, verbose=self.verbose\n )\n\n # Then load model\n self._model = load_model(device=self._device, model_path=model_path)\n\n else:\n self._model = model\n\n # Push model to the corresponding device\n self._model.to(self._device)\n\n # Set the loss function\n if self._version == 2:\n from warpctc_pytorch import CTCLoss\n\n self.criterion = CTCLoss()\n else:\n self.criterion = self._model.criterion\n\n # Save first version of the optimizer\n self._optimizer = optimizer\n self._use_amp = use_amp\n self._opt_level = opt_level\n\n # Now create a decoder\n # Create the language model config first\n lm_config = LMConfig()\n\n # Then set up the config\n if decoder_type == \"greedy\":\n lm_config.decoder_type = DecoderType.greedy\n elif decoder_type == \"beam\":\n lm_config.decoder_type = DecoderType.beam\n else:\n raise ValueError(f\"Decoder type {decoder_type} currently not supported.\")\n\n lm_config.lm_path = lm_path\n lm_config.top_paths = top_paths\n lm_config.alpha = alpha\n lm_config.beta = beta\n lm_config.cutoff_top_n = cutoff_top_n\n lm_config.cutoff_prob = cutoff_prob\n lm_config.beam_width = beam_width\n lm_config.lm_workers = lm_workers\n self.lm_config = lm_config\n\n # Create the decoder with the lm config\n self.decoder = load_decoder(labels=self._model.labels, cfg=lm_config)\n\n # Setup for AMP use\n if self.use_amp: # pragma: no cover\n from apex import amp\n\n if self.optimizer is None:\n logger.warning(\n \"An optimizer is needed to use the automatic mixed precision tool, but none for provided. \"\n \"A default optimizer is used.\"\n )\n\n # Create the optimizers\n parameters = self._model.parameters()\n self._optimizer = torch.optim.SGD(parameters, lr=0.01)\n\n if self._device.type == \"cpu\":\n enabled = False\n else:\n enabled = True\n\n self._model, self._optimizer = amp.initialize(\n models=self._model,\n optimizers=self._optimizer,\n enabled=enabled,\n opt_level=opt_level,\n loss_scale=1.0,\n )\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> tuple[np.ndarray, np.ndarray] | np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param batch_size: Batch size.\n :param transcription_output: Indicate whether the function will produce probability or transcription as\n prediction output. If transcription_output is not available, then probability\n output is returned. Default: True\n :return: Predicted probability (if transcription_output False) or transcription (default, if\n transcription_output is True):\n - Probability return is a tuple of (probs, sizes), where `probs` is the probability of characters of\n shape (nb_samples, seq_length, nb_classes) and `sizes` is the real sequence length of shape\n (nb_samples,).\n - Transcription return is a numpy array of characters. A possible example of a transcription return\n is `np.array(['SIXTY ONE', 'HELLO'])`.\n \"\"\"\n import torch\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n x_in = np.empty(len(x_preprocessed), dtype=object)\n x_in[:] = list(x_preprocessed)\n\n # Put the model in the eval mode\n self._model.eval()\n\n # Transform x into the model input space\n inputs, _, input_rates, _, batch_idx = self._transform_model_input(x=x_in)\n\n # Compute real input sizes\n input_sizes = input_rates.mul_(inputs.size()[-1]).int()\n\n # Run prediction with batch processing\n results = []\n result_output_sizes = np.zeros(x_preprocessed.shape[0], dtype=int)\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Call to DeepSpeech model for prediction\n with torch.no_grad():\n outputs, output_sizes, _ = self._model(\n inputs[begin:end].to(self._device), input_sizes[begin:end].to(self._device)\n )\n\n results.append(outputs)\n result_output_sizes[begin:end] = output_sizes.detach().cpu().numpy()\n\n # Aggregate results\n result_outputs = np.zeros(\n shape=(x_preprocessed.shape[0], result_output_sizes.max(), results[0].shape[-1]),\n dtype=config.ART_NUMPY_DTYPE,\n )\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Overwrite results\n result_outputs[begin:end, : results[m].shape[1], : results[m].shape[-1]] = results[m].cpu().numpy()\n\n # Rearrange to the original order\n result_output_sizes_ = result_output_sizes.copy()\n result_outputs_ = result_outputs.copy()\n result_output_sizes[batch_idx] = result_output_sizes_\n result_outputs[batch_idx] = result_outputs_\n\n # Check if users want transcription outputs\n transcription_output = kwargs.get(\"transcription_output\", True)\n\n if transcription_output is False:\n return result_outputs, result_output_sizes\n\n # Now users want transcription outputs\n # Compute transcription\n decoded_output, _ = self.decoder.decode(\n torch.tensor(result_outputs, device=self._device), torch.tensor(result_output_sizes, device=self._device)\n )\n decoded_output = [do[0] for do in decoded_output]\n decoded_output = np.array(decoded_output)\n\n return decoded_output\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: Loss gradients of the same shape as `x`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, None, fit=False)\n\n x_in = np.empty(len(x_preprocessed), dtype=object)\n x_in[:] = list(x_preprocessed)\n\n # Put the model in the training mode, otherwise CUDA can't backpropagate through the model.\n # However, model uses batch norm layers which need to be frozen\n self._model.train()\n self.set_batchnorm(train=False)\n\n # Transform data into the model input space\n inputs, targets, input_rates, target_sizes, _ = self._transform_model_input(x=x_in, y=y, compute_gradient=True)\n\n # Compute real input sizes\n input_sizes = input_rates.mul_(inputs.size()[-1]).int()\n\n # Call to DeepSpeech model for prediction\n outputs, output_sizes, _ = self._model(inputs.to(self._device), input_sizes.to(self._device))\n outputs = outputs.transpose(0, 1)\n\n if self._version == 2:\n outputs = outputs.float()\n else:\n outputs = outputs.log_softmax(-1)\n\n # Compute the loss\n loss = self.criterion(outputs, targets, output_sizes, target_sizes).to(self._device)\n\n # Average the loss by mini batch if version 2 of DeepSpeech is used\n if self._version == 2:\n loss = loss / inputs.size(0)\n\n # Compute gradients\n if self.use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n # Get results\n results_list = []\n for i, _ in enumerate(x_in):\n results_list.append(x_in[i].grad.cpu().numpy().copy())\n\n results = np.array(results_list)\n\n if results.shape[0] == 1:\n results_ = np.empty(len(results), dtype=object)\n results_[:] = list(results)\n results = results_\n\n results = self._apply_preprocessing_gradient(x, results)\n\n if x.dtype != object:\n results = np.array([i for i in results], dtype=x.dtype) # pylint: disable=unnecessary-comprehension\n assert results.shape == x.shape and results.dtype == x.dtype\n\n # Unfreeze batch norm layers again\n self.set_batchnorm(train=True)\n\n return results\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, **kwargs) -> None:\n \"\"\"\n Fit the estimator on the training set `(x, y)`.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n import random\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, None, fit=True)\n y_preprocessed = y\n\n x_in = np.empty(len(x_preprocessed), dtype=object)\n x_in[:] = list(x_preprocessed)\n\n # Put the model in the training mode\n self._model.train()\n\n if self.optimizer is None: # pragma: no cover\n raise ValueError(\"An optimizer is required to train the model, but none was provided.\")\n\n # Train with batch processing\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n ind = np.arange(len(x_preprocessed)).tolist()\n\n # Start training\n for _ in range(nb_epochs):\n # Shuffle the examples\n random.shuffle(ind)\n\n # Train for one epoch\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Extract random batch\n i_batch = np.empty(len(x_preprocessed[ind[begin:end]]), dtype=object)\n i_batch[:] = list(x_preprocessed[ind[begin:end]])\n o_batch = y_preprocessed[ind[begin:end]]\n\n # Transform data into the model input space\n inputs, targets, input_rates, target_sizes, _ = self._transform_model_input(\n x=i_batch, y=o_batch, compute_gradient=False\n )\n\n # Compute real input sizes\n input_sizes = input_rates.mul_(inputs.size(-1)).int()\n\n # Zero the parameter gradients\n self.optimizer.zero_grad()\n\n # Call to DeepSpeech model for prediction\n outputs, output_sizes, _ = self._model(inputs.to(self._device), input_sizes.to(self._device))\n outputs = outputs.transpose(0, 1)\n\n if self._version == 2:\n outputs = outputs.float()\n else:\n outputs = outputs.log_softmax(-1)\n\n # Compute the loss\n loss = self.criterion(outputs, targets, output_sizes, target_sizes).to(self._device)\n\n # Average the loss by mini batch if version 2 of DeepSpeech is used\n if self._version == 2:\n loss = loss / inputs.size(0)\n\n # Actual training\n if self.use_amp: # pragma: no cover\n from apex import amp\n\n with amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n\n else:\n loss.backward()\n\n self.optimizer.step()\n\n def compute_loss_and_decoded_output(\n self, masked_adv_input: \"torch.Tensor\", original_output: np.ndarray, **kwargs\n ) -> tuple[\"torch.Tensor\", np.ndarray]:\n \"\"\"\n Compute loss function and decoded output.\n\n :param masked_adv_input: The perturbed inputs.\n :param original_output: Target values of shape (nb_samples). Each sample in `original_output` is a string, and\n it may possess different lengths. A possible example of `original_output` could be:\n `original_output = np.array(['SIXTY ONE', 'HELLO'])`.\n :param real_lengths: Real lengths of original sequences.\n :return: The loss and the decoded output.\n \"\"\"\n # This estimator needs to have real lengths for loss computation\n real_lengths = kwargs.get(\"real_lengths\")\n if real_lengths is None: # pragma: no cover\n raise ValueError(\n \"The PyTorchDeepSpeech estimator needs information about the real lengths of input sequences to \"\n \"compute loss and decoded output.\"\n )\n\n # Transform data into the model input space\n inputs, targets, input_rates, target_sizes, batch_idx = self._preprocess_transform_model_input(\n x=masked_adv_input.to(self.device),\n y=original_output,\n real_lengths=real_lengths,\n )\n\n # Compute real input sizes\n input_sizes = input_rates.mul_(inputs.size()[-1]).int()\n\n # Call to DeepSpeech model for prediction\n outputs, output_sizes, _ = self.model(inputs.to(self.device), input_sizes.to(self.device))\n outputs_ = outputs.transpose(0, 1)\n\n if self._version == 2:\n outputs_ = outputs_.float()\n else:\n outputs_ = outputs_.log_softmax(-1)\n\n # Compute the loss\n loss = self.criterion(outputs_, targets, output_sizes, target_sizes).to(self._device)\n\n # Average the loss by mini batch if version 2 of DeepSpeech is used\n if self._version == 2:\n loss = loss / inputs.size(0)\n\n # Compute transcription\n decoded_output, _ = self.decoder.decode(outputs, output_sizes)\n decoded_output = [do[0] for do in decoded_output]\n decoded_output = np.array(decoded_output)\n\n # Rearrange to the original order\n decoded_output_ = decoded_output.copy()\n decoded_output[batch_idx] = decoded_output_\n\n return loss, decoded_output\n\n def _preprocess_transform_model_input(\n self,\n x: \"torch.Tensor\",\n y: np.ndarray,\n real_lengths: np.ndarray,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", list]:\n \"\"\"\n Apply preprocessing and then transform the user input space into the model input space. This function is used\n by the ASR attack to attack into the PyTorchDeepSpeech estimator whose defences are called with the\n `_apply_preprocessing` function.\n\n :param x: Samples of shape (nb_samples, seq_length).\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :param real_lengths: Real lengths of original sequences.\n :return: A tuple of inputs and targets in the model space with the original index\n `(inputs, targets, input_percentages, target_sizes, batch_idx)`, where:\n - inputs: model inputs of shape (nb_samples, nb_frequencies, seq_length).\n - targets: ground truth targets of shape (sum over nb_samples of real seq_lengths).\n - input_percentages: percentages of real inputs in inputs.\n - target_sizes: list of real seq_lengths.\n - batch_idx: original index of inputs.\n \"\"\"\n import torch\n\n # Apply preprocessing\n x_batch = []\n for i, _ in enumerate(x):\n preprocessed_x_i, _ = self._apply_preprocessing(x=x[i], y=None, no_grad=False)\n x_batch.append(preprocessed_x_i)\n\n x = torch.stack(x_batch)\n\n # Transform the input space\n inputs, targets, input_rates, target_sizes, batch_idx = self._transform_model_input(\n x=x,\n y=y,\n compute_gradient=False,\n tensor_input=True,\n real_lengths=real_lengths,\n )\n\n return inputs, targets, input_rates, target_sizes, batch_idx\n\n def _transform_model_input(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | None = None,\n compute_gradient: bool = False,\n tensor_input: bool = False,\n real_lengths: np.ndarray | None = None,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", \"torch.Tensor\", list]:\n \"\"\"\n Transform the user input space into the model input space.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.ndarray([[0.1, 0.2, 0.1, 0.4], [0.3, 0.1]])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :param compute_gradient: Indicate whether to compute gradients for the input `x`.\n :param tensor_input: Indicate whether input is tensor.\n :param real_lengths: Real lengths of original sequences.\n :return: A tuple of inputs and targets in the model space with the original index\n `(inputs, targets, input_percentages, target_sizes, batch_idx)`, where:\n - inputs: model inputs of shape (nb_samples, nb_frequencies, seq_length).\n - targets: ground truth targets of shape (sum over nb_samples of real seq_lengths).\n - input_percentages: percentages of real inputs in inputs.\n - target_sizes: list of real seq_lengths.\n - batch_idx: original index of inputs.\n \"\"\"\n import torch\n import torchaudio\n from deepspeech_pytorch.loader.data_loader import _collate_fn\n\n # Get parameters needed for the transformation\n if self._version == 2:\n window_name = self.model.audio_conf.window.value\n sample_rate = self.model.audio_conf.sample_rate\n window_size = self.model.audio_conf.window_size\n window_stride = self.model.audio_conf.window_stride\n\n else:\n window_name = self.model.spect_cfg[\"window\"].value\n sample_rate = self.model.spect_cfg[\"sample_rate\"]\n window_size = self.model.spect_cfg[\"window_size\"]\n window_stride = self.model.spect_cfg[\"window_stride\"]\n\n n_fft = int(sample_rate * window_size)\n hop_length = int(sample_rate * window_stride)\n win_length = n_fft\n\n # Get window for the transformation\n if window_name == \"hamming\": # pragma: no cover\n window_fn = torch.hamming_window # type: ignore\n elif window_name == \"hann\": # pragma: no cover\n window_fn = torch.hann_window # type: ignore\n elif window_name == \"blackman\": # pragma: no cover\n window_fn = torch.blackman_window # type: ignore\n elif window_name == \"bartlett\": # pragma: no cover\n window_fn = torch.bartlett_window # type: ignore\n else: # pragma: no cover\n raise NotImplementedError(f\"Spectrogram window {window_name} not supported.\")\n\n # Create a transformer to transform between the two spaces\n transformer = torchaudio.transforms.Spectrogram(\n n_fft=n_fft, hop_length=hop_length, win_length=win_length, window_fn=window_fn, power=None\n )\n transformer.to(self._device)\n\n # Create a label map\n label_map = {self._model.labels[i]: i for i in range(len(self._model.labels))}\n\n # We must process each sequence separately due to the diversity of their length\n batch = []\n for i, _ in enumerate(x):\n # First process the target\n if y is None:\n target = []\n else:\n target = list(filter(None, [label_map.get(letter) for letter in list(y[i])]))\n\n # Push the sequence to device\n if isinstance(x, np.ndarray) and not tensor_input:\n x[i] = x[i].astype(config.ART_NUMPY_DTYPE)\n x[i] = torch.tensor(x[i]).to(self._device)\n\n # Set gradient computation permission\n if compute_gradient:\n x[i].requires_grad = True\n\n # Transform the sequence into the frequency space\n if tensor_input and real_lengths is not None:\n transformed_input = transformer(x[i][: real_lengths[i]])\n else:\n transformed_input = transformer(x[i])\n\n if self._version == 3:\n spectrogram = torch.abs(transformed_input)\n else:\n spectrogram, _ = torchaudio.functional.magphase(transformed_input)\n spectrogram = torch.log1p(spectrogram)\n\n # Normalize data\n mean = spectrogram.mean()\n std = spectrogram.std()\n spectrogram = spectrogram - mean\n spectrogram = spectrogram / std\n\n # Then form the batch\n batch.append((spectrogram, target))\n\n # We must keep the order of the batch for later use as the following function will change its order\n batch_idx = sorted(range(len(batch)), key=lambda i: batch[i][0].size(1), reverse=True)\n\n # The collate function is important to convert input into model space\n inputs, targets, input_percentages, target_sizes = _collate_fn(batch)\n\n return inputs, targets, input_percentages, target_sizes, batch_idx\n\n def to_training_mode(self) -> None:\n \"\"\"\n Put the estimator in the training mode.\n \"\"\"\n self.model.train()\n\n @property\n def sample_rate(self) -> int:\n \"\"\"\n Get the sampling rate.\n\n :return: The audio sampling rate.\n \"\"\"\n if self._version == 2:\n sample_rate = self.model.audio_conf.sample_rate\n else:\n sample_rate = self.model.spect_cfg[\"sample_rate\"]\n\n return sample_rate\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def model(self) -> \"DeepSpeech\":\n \"\"\"\n Get current model.\n\n :return: Current model.\n \"\"\"\n return self._model\n\n @property\n def device(self) -> \"torch.device\":\n \"\"\"\n Get current used device.\n\n :return: Current used device.\n \"\"\"\n return self._device\n\n @property\n def use_amp(self) -> bool:\n \"\"\"\n Return a boolean indicating whether to use the automatic mixed precision tool.\n\n :return: Whether to use the automatic mixed precision tool.\n \"\"\"\n return self._use_amp # type: ignore\n\n @property\n def optimizer(self) -> \"torch.optim.Optimizer\":\n \"\"\"\n Return the optimizer.\n\n :return: The optimizer.\n \"\"\"\n return self._optimizer # type: ignore\n\n @property\n def opt_level(self) -> str:\n \"\"\"\n Return a string specifying a pure or mixed precision optimization level.\n\n :return: A string specifying a pure or mixed precision optimization level. Possible\n values are `O0`, `O1`, `O2`, and `O3`.\n \"\"\"\n return self._opt_level # type: ignore\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/speech_recognition/pytorch_espresso.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the task specific estimator for Espresso, an end-to-end speech recognition toolkit based on\nfairseq.\n\n| Paper link: https://arxiv.org/abs/1909.08723\n\"\"\"\nfrom __future__ import annotations\n\nimport ast\nfrom argparse import Namespace\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art import config\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin, PytorchSpeechRecognizerMixin\nfrom art.utils import get_file\n\nif TYPE_CHECKING:\n\n import torch\n from espresso.models import SpeechTransformerModel\n\n from art.defences.preprocessor.preprocessor import Preprocessor\n from art.defences.postprocessor.postprocessor import Postprocessor\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n\nlogger = logging.getLogger(__name__)\n\nINT16MAX = 32767\n\n\nclass PyTorchEspresso(PytorchSpeechRecognizerMixin, SpeechRecognizerMixin, PyTorchEstimator):\n \"\"\"\n This class implements a model-specific automatic speech recognizer using the end-to-end speech recognizer in\n Espresso.\n\n | Paper link: https://arxiv.org/abs/1909.08723\n \"\"\"\n\n estimator_params = PyTorchEstimator.estimator_params + [\"espresso_config_filepath\"]\n\n def __init__(\n self,\n espresso_config_filepath: str | None = None,\n model: str | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = None,\n device_type: str = \"gpu\",\n verbose: bool = True,\n ):\n \"\"\"\n Initialization of an instance PyTorchEspresso\n\n :param espresso_config_filepath: The path of the espresso config file (yaml)\n :param model: The choice of pretrained model if a pretrained model is required.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the estimator.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the estimator.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device to be used for model and tensors, if `cpu` run on CPU, if `gpu` run on GPU\n if available otherwise run on CPU.\n \"\"\"\n import torch\n import yaml\n from fairseq import checkpoint_utils, tasks, utils\n from fairseq.data import encoders\n import sentencepiece as spm\n\n # Super initialization\n super().__init__(\n model=None,\n clip_values=clip_values,\n channels_first=None,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n self.verbose = verbose\n\n # Check clip values\n if self.clip_values is not None:\n if not np.all(self.clip_values[0] == -1): # pragma: no cover\n raise ValueError(\"This estimator requires normalized input audios with clip_vales=(-1, 1).\")\n if not np.all(self.clip_values[1] == 1): # pragma: no cover\n raise ValueError(\"This estimator requires normalized input audios with clip_vales=(-1, 1).\")\n\n # Check postprocessing defences\n if self.postprocessing_defences is not None: # pragma: no cover\n raise ValueError(\"This estimator does not support `postprocessing_defences`.\")\n\n # Set cpu/gpu device\n self._device: torch.device\n if device_type == \"cpu\" or not torch.cuda.is_available():\n self._device = torch.device(\"cpu\")\n else: # pragma: no cover\n cuda_idx = torch.cuda.current_device()\n self._device = torch.device(f\"cuda:{cuda_idx}\")\n\n # Load config/model\n if espresso_config_filepath is None:\n if model == \"librispeech_transformer\":\n config_filename, config_url = (\n \"libri960_transformer.yaml\",\n \"https://github.com/YiwenShaoStephen/espresso/releases/download/v0.1-alpha/\"\n \"libri960_transformer.yaml\",\n )\n model_filename, model_url = (\n \"checkpoint_best.pt\",\n \"https://github.com/YiwenShaoStephen/espresso/releases/download/v0.1-alpha/checkpoint_best.pt\",\n )\n sp_filename, sp_url = (\n \"train_960_unigram5000.model\",\n \"https://github.com/YiwenShaoStephen/espresso/releases/download/v0.1-alpha/\"\n \"train_960_unigram5000.model\",\n )\n dict_filename, dict_url = (\n \"train_960_unigram5000_units.txt\",\n \"https://github.com/YiwenShaoStephen/espresso/releases/download/v0.1-alpha/\"\n \"train_960_unigram5000_units.txt\",\n )\n else: # pragma: no cover\n raise ValueError(\"Model not recognised.\")\n\n # Download files\n config_path = get_file(\n filename=config_filename, path=config.ART_DATA_PATH, url=config_url, extract=False, verbose=self.verbose\n )\n model_path = get_file(\n filename=model_filename, path=config.ART_DATA_PATH, url=model_url, extract=False, verbose=self.verbose\n )\n sp_path = get_file(\n filename=sp_filename, path=config.ART_DATA_PATH, url=sp_url, extract=False, verbose=self.verbose\n )\n dict_path = get_file(\n filename=dict_filename, path=config.ART_DATA_PATH, url=dict_url, extract=False, verbose=self.verbose\n )\n else:\n raise ValueError(\"Value for `espresso_config_filepath` has to `None` for now.\")\n\n # construct espresso args\n with open(config_path, encoding=\"utf8\") as file:\n esp_args_dict = yaml.load(file, Loader=yaml.FullLoader)\n esp_args = Namespace(**esp_args_dict)\n if espresso_config_filepath is None: # overwrite paths in downloaded config with the actual ones\n esp_args.path = model_path\n esp_args.sentencepiece_model = sp_path\n esp_args.dict = dict_path\n self.esp_args = esp_args\n\n # setup espresso/fairseq task\n self.task = tasks.setup_task(self.esp_args)\n self.task.feat_dim = self.esp_args.feat_dim\n\n # load_model_ensemble\n self._models, self._model_args = checkpoint_utils.load_model_ensemble(\n utils.split_paths(self.esp_args.path),\n arg_overrides=ast.literal_eval(self.esp_args.model_overrides),\n task=self.task,\n suffix=getattr(self.esp_args, \"checkpoint_suffix\", \"\"),\n )\n for m in self._models:\n m.to(self._device)\n\n self._model = self._models[0]\n\n self.dictionary = self.task.target_dictionary\n self.generator = self.task.build_generator(self._models, self.esp_args)\n self.tokenizer = encoders.build_tokenizer(self.esp_args)\n self.bpe = encoders.build_bpe(self.esp_args) # bpe encoder\n self.spp = spm.SentencePieceProcessor() # sentence piece model\n self.spp.Load(self.esp_args.sentencepiece_model)\n\n self.criterion = self.task.build_criterion(self.esp_args)\n self._sampling_rate = self.esp_args.sampling_rate\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param batch_size: Batch size.\n :return: Transcription as a numpy array of characters. A possible example of a transcription return\n is `np.array(['SIXTY ONE', 'HELLO'])`.\n \"\"\"\n\n def get_symbols_to_strip_from_output(generator):\n if hasattr(generator, \"symbols_to_strip_from_output\"):\n return generator.symbols_to_strip_from_output\n\n return {generator.eos, generator.pad}\n\n x_in = np.empty(len(x), dtype=object)\n x_in[:] = list(x)\n\n # Put the model in the eval mode\n self.model.eval()\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x_in, y=None, fit=False)\n\n # Run prediction with batch processing\n decoded_output = []\n # result_output_sizes = np.zeros(x_preprocessed.shape[0], dtype=int)\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n # Transform x into the model input space\n # Note that batch is re-ordered during transformation\n batch, batch_idx = self._transform_model_input(x=x_preprocessed[begin:end])\n\n hypos = self.task.inference_step(self.generator, self._models, batch)\n\n decoded_output_batch = []\n\n for _, hypos_i in enumerate(hypos):\n # Process top predictions\n for _, hypo in enumerate(hypos_i[: self.esp_args.nbest]):\n hypo_str = self.dictionary.string(\n hypo[\"tokens\"].int().cpu(),\n bpe_symbol=None,\n extra_symbols_to_ignore=get_symbols_to_strip_from_output(self.generator),\n ) # not removing bpe at this point\n detok_hypo_str = self.bpe.decode(hypo_str)\n decoded_output_batch.append(detok_hypo_str)\n\n decoded_output_array = np.array(decoded_output_batch)\n\n decoded_output_copy = decoded_output_array.copy()\n decoded_output_array[batch_idx] = decoded_output_copy # revert decoded output to its original order\n decoded_output.append(decoded_output_array)\n\n return np.concatenate(decoded_output)\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: Loss gradients of the same shape as `x`.\n \"\"\"\n x_in = np.empty(len(x), dtype=object)\n x_in[:] = list(x)\n\n # Put the model in the training mode, otherwise CUDA can't backpropagate through the model.\n # However, model uses batch norm layers which need to be frozen\n self.model.train()\n self.set_batchnorm(train=False)\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x_in, y, fit=False)\n\n # Transform data into the model input space\n batch_dict, batch_idx = self._transform_model_input(x=x_preprocessed, y=y_preprocessed, compute_gradient=True)\n\n loss, _, _ = self.criterion(self.model, batch_dict)\n loss.backward()\n\n # Get results\n results_list = []\n src_frames = batch_dict[\"net_input\"][\"src_tokens\"].grad.cpu().numpy().copy()\n src_lengths = batch_dict[\"net_input\"][\"src_lengths\"].cpu().numpy().copy()\n for i, _ in enumerate(x_preprocessed):\n results_list.append(src_frames[i, : src_lengths[i], :])\n\n results = np.array(results_list)\n\n if results.shape[0] == 1:\n results_ = np.empty(len(results), dtype=object)\n results_[:] = list(results)\n results = results_\n\n # Rearrange to the original order\n results_ = results.copy()\n results[batch_idx] = results_\n\n results = self._apply_preprocessing_gradient(x_in, results)\n\n if x.dtype != object:\n results = np.array([i for i in results], dtype=x.dtype) # pylint: disable=unnecessary-comprehension\n assert results.shape == x.shape and results.dtype == x.dtype\n else:\n results = np.array([np.squeeze(res) for res in results], dtype=object)\n\n # Unfreeze batch norm layers again\n self.set_batchnorm(train=True)\n\n return results\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, **kwargs) -> None:\n \"\"\"\n Fit the estimator on the training set `(x, y)`.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n raise NotImplementedError\n\n def _transform_model_input(\n self,\n x: np.ndarray | \"torch.Tensor\",\n y: np.ndarray | None = None,\n compute_gradient: bool = False,\n ) -> tuple[dict, list]:\n \"\"\"\n Transform the user input space into the model input space.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.ndarray([[0.1, 0.2, 0.1, 0.4], [0.3, 0.1]])`.\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :param compute_gradient: Indicate whether to compute gradients for the input `x`.\n :return: A tuple of a dictionary of batch and a list representing the original order of the batch\n \"\"\"\n import torch\n from fairseq.data import data_utils\n\n def _collate_fn(batch: list) -> dict:\n \"\"\"\n Collate function that transforms a list of numpy array or torch tensor representing a batch into a\n dictionary that Espresso takes as input.\n \"\"\"\n # sort by seq length in descending order\n batch = sorted(batch, key=lambda t: t[0].size(0), reverse=True)\n batch_size = len(batch)\n max_seqlength = batch[0][0].size(0)\n src_frames = torch.zeros(batch_size, max_seqlength, 1)\n src_lengths = torch.zeros(batch_size, dtype=torch.long)\n\n for i, (sample, _) in enumerate(batch):\n seq_length = sample.size(0)\n src_frames[i, :seq_length, :] = sample.unsqueeze(1)\n src_lengths[i] = seq_length\n\n if compute_gradient:\n src_frames = torch.tensor(src_frames, requires_grad=True)\n src_frames.requires_grad = True\n\n # for input feeding in training\n if batch[0][1] is not None:\n pad_idx = self.dictionary.pad()\n eos_idx = self.dictionary.eos()\n target = data_utils.collate_tokens(\n [s[1] for s in batch],\n pad_idx,\n eos_idx,\n False,\n False,\n pad_to_length=None,\n pad_to_multiple=1,\n )\n prev_output_tokens = data_utils.collate_tokens(\n [s[1] for s in batch],\n pad_idx,\n eos_idx,\n False,\n True,\n pad_to_length=None,\n pad_to_multiple=1,\n )\n target = target.long().to(self._device)\n prev_output_tokens = prev_output_tokens.long().to(self._device)\n ntokens = sum(s[1].ne(pad_idx).int().sum().item() for s in batch)\n\n else:\n target = None\n prev_output_tokens = None\n ntokens = None\n\n batch_dict = {\n \"ntokens\": ntokens,\n \"net_input\": {\n \"src_tokens\": src_frames.to(self._device),\n \"src_lengths\": src_lengths.to(self._device),\n \"prev_output_tokens\": prev_output_tokens,\n },\n \"target\": target,\n }\n\n return batch_dict\n\n # We must process each sequence separately due to the diversity of their length\n batch = []\n for i, _ in enumerate(x):\n # First process the target\n if y is None:\n target = None\n else:\n eap = self.spp.EncodeAsPieces(y[i])\n sp_string = \" \".join(eap)\n target = self.dictionary.encode_line(sp_string, add_if_not_exist=False) # target is a long tensor\n\n # Push the sequence to device\n if isinstance(x, np.ndarray):\n x[i] = x[i].astype(config.ART_NUMPY_DTYPE)\n x[i] = torch.tensor(x[i]).to(self._device)\n\n # Set gradient computation permission\n if compute_gradient:\n x[i].requires_grad = True\n\n # Re-scale the input audio to the magnitude used to train Espresso model\n x[i] = x[i] * 32767\n\n # Form the batch\n batch.append((x[i], target))\n\n # We must keep the order of the batch for later use as the following function will change its order\n batch_idx = sorted(range(len(batch)), key=lambda i: batch[i][0].size(0), reverse=True)\n\n # The collate function is important to convert input into model space\n batch_dict = _collate_fn(batch)\n\n # return inputs, targets, input_percentages, target_sizes, batch_idx\n return batch_dict, batch_idx\n\n def _preprocess_transform_model_input(\n self,\n x: \"torch.Tensor\",\n y: np.ndarray,\n ) -> tuple[dict, list]:\n \"\"\"\n Apply preprocessing and then transform the user input space into the model input space. This function is used\n by the ASR attack to attack into the PyTorchDeepSpeech estimator whose defences are called with the\n `_apply_preprocessing` function.\n\n :param x: Samples of shape (nb_samples, seq_length).\n :param y: Target values of shape (nb_samples). Each sample in `y` is a string, and it may possess different\n lengths. A possible example of `y` could be: `y = np.array(['SIXTY ONE', 'HELLO'])`.\n :param real_lengths: Real lengths of original sequences.\n :return: A tuple of inputs and targets in the model space with the original index\n `(inputs, targets, input_percentages, target_sizes, batch_idx)`, where:\n - inputs: model inputs of shape (nb_samples, nb_frequencies, seq_length).\n - targets: ground truth targets of shape (sum over nb_samples of real seq_lengths).\n - input_percentages: percentages of real inputs in inputs.\n - target_sizes: list of real seq_lengths.\n - batch_idx: original index of inputs.\n \"\"\"\n import torch\n\n # Apply preprocessing\n x_batch = []\n for i, _ in enumerate(x):\n preprocessed_x_i, _ = self._apply_preprocessing(x=x[i], y=None, no_grad=False)\n x_batch.append(preprocessed_x_i)\n\n x = torch.stack(x_batch)\n\n # Transform the input space\n batch_dict, batch_idx = self._transform_model_input(\n x=x,\n y=y,\n compute_gradient=False,\n )\n\n return batch_dict, batch_idx\n\n def compute_loss_and_decoded_output(\n self, masked_adv_input: \"torch.Tensor\", original_output: np.ndarray, **kwargs\n ) -> tuple[\"torch.Tensor\", np.ndarray]:\n \"\"\"\n Compute loss function and decoded output.\n\n :param masked_adv_input: The perturbed inputs.\n :param original_output: Target values of shape (nb_samples). Each sample in `original_output` is a string, and\n it may possess different lengths. A possible example of `original_output` could be:\n `original_output = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: The loss and the decoded output.\n \"\"\"\n # Transform data into the model input space\n batch_dict, batch_idx = self._preprocess_transform_model_input(\n x=masked_adv_input.to(self.device),\n y=original_output,\n )\n\n # Compute the loss\n self.model.train()\n loss, _, _ = self.criterion(self.model, batch_dict)\n\n # Compute transcription\n def get_symbols_to_strip_from_output(generator):\n if hasattr(generator, \"symbols_to_strip_from_output\"):\n return generator.symbols_to_strip_from_output\n\n return {generator.eos, generator.pad}\n\n # Put the model in the eval mode\n self.model.eval()\n\n # Get decoded output\n decoded_output = []\n hypos = self.task.inference_step(self.generator, self._models, batch_dict)\n\n for _, hypos_i in enumerate(hypos):\n # Process top predictions\n for _, hypo in enumerate(hypos_i[: self.esp_args.nbest]):\n hypo_str = self.dictionary.string(\n hypo[\"tokens\"].int().cpu(),\n bpe_symbol=None,\n extra_symbols_to_ignore=get_symbols_to_strip_from_output(self.generator),\n ) # not removing bpe at this point\n detok_hypo_str = self.bpe.decode(hypo_str)\n decoded_output.append(detok_hypo_str)\n\n decoded_output_array = np.array(decoded_output)\n decoded_output_copy = decoded_output_array.copy()\n decoded_output_array[batch_idx] = decoded_output_copy # revert decoded output to its original order\n\n return loss, decoded_output_array\n\n def to_training_mode(self) -> None:\n \"\"\"\n Put the estimator in the training mode.\n \"\"\"\n self.model.train()\n\n @property\n def sample_rate(self) -> int:\n \"\"\"\n Get the sampling rate.\n\n :return: The audio sampling rate.\n \"\"\"\n return self._sampling_rate\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def model(self) -> \"SpeechTransformerModel\":\n \"\"\"\n Get current model.\n\n :return: Current model.\n \"\"\"\n return self._model\n\n @property\n def device(self) -> \"torch.device\":\n \"\"\"\n Get current used device.\n\n :return: Current used device.\n \"\"\"\n return self._device\n\n def get_activations(self, x: np.ndarray, layer: int | str, batch_size: int, framework: bool = False) -> np.ndarray:\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/estimators/speech_recognition/speech_recognizer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements mixin abstract base class and mixin abstract framework-specific classes for all speech\nrecognizers in ART.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n import torch\n\n\nclass SpeechRecognizerMixin(ABC):\n \"\"\"\n Mix-in base class for ART speech recognizers.\n \"\"\"\n\n\nclass PytorchSpeechRecognizerMixin(ABC):\n \"\"\"\n Pytorch class for ART speech recognizers. This class is used to define common methods for using inside pytorch\n imperceptible asr attack.\n \"\"\"\n\n @abstractmethod\n def compute_loss_and_decoded_output(\n self, masked_adv_input: \"torch.Tensor\", original_output: np.ndarray, **kwargs\n ) -> tuple[\"torch.Tensor\", np.ndarray]:\n \"\"\"\n Compute loss function and decoded output.\n\n :param masked_adv_input: The perturbed inputs.\n :param original_output: Target values of shape (nb_samples). Each sample in `original_output` is a string, and\n it may possess different lengths. A possible example of `original_output` could be:\n `original_output = np.array(['SIXTY ONE', 'HELLO'])`.\n :return: The loss and the decoded output.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def to_training_mode(self) -> None:\n \"\"\"\n Put the estimator in the training mode.\n \"\"\"\n raise NotImplementedError\n\n @property\n @abstractmethod\n def sample_rate(self) -> int:\n \"\"\"\n Get the sampling rate.\n\n :return: The audio sampling rate.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/evaluations/evaluation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module contains the abstract base class for evaluations.\n\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Any\n\n\nclass Evaluation(ABC):\n \"\"\"\n This class defines the abstract base class for evaluations.\n \"\"\"\n\n @abstractmethod\n def evaluate(self, *args, **kwargs) -> Any:\n \"\"\"\n Abstract method running the evaluation.\n \"\"\"\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/evaluations/great_score/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module implements the evaluation of GREAT Score.\n\"\"\"\n\nfrom art.evaluations.great_score.great_score import GreatScorePyTorch\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/evaluations/great_score/great_score.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport numpy as np\n\nfrom art.evaluations.evaluation import Evaluation\n\n\nclass GreatScorePyTorch(Evaluation):\n\n def __init__(self, classifier):\n \"\"\"\n Calculate the GREAT score and accuracy for given samples using the specified classifier.\n\n :param classifier: ART Classifier of the model to evaluate.\n \"\"\"\n self.classifier = classifier\n super().__init__()\n\n def evaluate(self, x: np.ndarray, y: np.ndarray) -> tuple[list[float], float]:\n \"\"\"\n Calculate the GREAT score and accuracy for given samples using the specified model.\n\n :param x: Input samples (images) as a numpy array.\n :param y: True labels for the samples.\n\n :return: great_score, accuracy\n \"\"\"\n # Calculate accuracy\n y_pred: np.ndarray = self.classifier.predict(x=x)\n correct_predictions: np.ndarray = np.argmax(y_pred, axis=1) == np.argmax(y, axis=1)\n accuracy = np.mean(correct_predictions)\n\n # Calculate the GREAT score\n k = 2\n top2_indices = np.argpartition(y_pred, -k, axis=1)[:, -k:] # (batch_size, 2), unsorted\n top2_values = np.take_along_axis(y_pred, top2_indices, axis=1) # corresponding values\n # Now sort these top-2 values and indices in descending order\n sorted_order = np.argsort(top2_values, axis=1)[:, ::-1]\n top2_values_sorted = np.take_along_axis(top2_values, sorted_order, axis=1)\n great_scores = np.where(correct_predictions, top2_values_sorted[:, 0] - top2_values_sorted[:, 1], 0)\n average_great_score = np.mean(great_scores)\n\n return average_great_score, accuracy\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/evaluations/security_curve/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module implements the evaluation of Security Curves.\n\"\"\"\n\nfrom art.evaluations.security_curve.security_curve import SecurityCurve\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/evaluations/security_curve/security_curve.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the evaluation of Security Curves.\n\nExamples of Security Curves can be found in Figure 6 of Madry et al., 2017 (https://arxiv.org/abs/1706.06083).\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.evaluations.evaluation import Evaluation\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE\n\n\nclass SecurityCurve(Evaluation):\n \"\"\"\n This class implements the evaluation of Security Curves.\n\n Examples of Security Curves can be found in Figure 6 of Madry et al., 2017 (https://arxiv.org/abs/1706.06083).\n \"\"\"\n\n def __init__(self, eps: int | list[float] | list[int]):\n \"\"\"\n Create an instance of a Security Curve evaluation.\n\n :param eps: Defines the attack budgets `eps` for Projected Gradient Descent used for evaluation.\n \"\"\"\n\n self.eps = eps\n self.eps_list: list[float] = []\n self.accuracy_adv_list: list[float] = []\n self.accuracy: float | None = None\n\n def evaluate( # type: ignore\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n x: np.ndarray,\n y: np.ndarray,\n **kwargs: str | bool | int | float,\n ) -> tuple[list[float], list[float], float]:\n \"\"\"\n Evaluate the Security Curve of a classifier using Projected Gradient Descent.\n\n :param classifier: A trained classifier that provides loss gradients.\n :param x: Input data to classifier for evaluation.\n :param y: True labels for input data `x`.\n :param kwargs: Keyword arguments for the Projected Gradient Descent attack used for evaluation, except keywords\n `classifier` and `eps`.\n :return: List of evaluated `eps` values, list of adversarial accuracies, and benign accuracy.\n \"\"\"\n\n kwargs.pop(\"classifier\", None)\n kwargs.pop(\"eps\", None)\n self.eps_list.clear()\n self.accuracy_adv_list.clear()\n self.accuracy = None\n\n # Check type of eps\n if isinstance(self.eps, int):\n if classifier.clip_values is not None:\n eps_increment = (classifier.clip_values[1] - classifier.clip_values[0]) / self.eps\n else:\n eps_increment = (np.max(x) - np.min(x)) / self.eps\n\n for i in range(1, self.eps + 1):\n self.eps_list.append(float(i * eps_increment))\n\n else:\n self.eps_list = [float(eps) for eps in self.eps]\n\n # Determine benign accuracy\n y_pred = classifier.predict(x=x, y=y)\n self.accuracy = self._get_accuracy(y=y, y_pred=y_pred)\n\n # Determine adversarial accuracy for each eps\n for eps in self.eps_list:\n attack_pgd = ProjectedGradientDescent(estimator=classifier, eps=eps, **kwargs) # type: ignore\n\n x_adv = attack_pgd.generate(x=x, y=y)\n\n y_pred_adv = classifier.predict(x=x_adv, y=y)\n accuracy_adv = self._get_accuracy(y=y, y_pred=y_pred_adv)\n self.accuracy_adv_list.append(accuracy_adv)\n\n # Check gradients for potential obfuscation\n self._check_gradient(classifier=classifier, x=x, y=y, **kwargs)\n\n return self.eps_list, self.accuracy_adv_list, self.accuracy\n\n @property\n def detected_obfuscating_gradients(self) -> bool:\n \"\"\"\n This property describes if the previous call to method `evaluate` identified potential gradient obfuscation.\n \"\"\"\n return self._detected_obfuscating_gradients\n\n def _check_gradient(\n self,\n classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\",\n x: np.ndarray,\n y: np.ndarray,\n **kwargs: str | bool | int | float,\n ) -> None:\n \"\"\"\n Check if potential gradient obfuscation can be detected. Projected Gradient Descent with 100 iterations is run\n with maximum attack budget `eps` being equal to upper clip value of input data and `eps_step` of\n `eps / (max_iter / 2)`.\n\n :param classifier: A trained classifier that provides loss gradients.\n :param x: Input data to classifier for evaluation.\n :param y: True labels for input data `x`.\n :param kwargs: Keyword arguments for the Projected Gradient Descent attack used for evaluation, except keywords\n `classifier` and `eps`.\n \"\"\"\n # Define parameters for Projected Gradient Descent\n max_iter = 100\n kwargs[\"max_iter\"] = max_iter\n if classifier.clip_values is not None:\n clip_value_max = classifier.clip_values[1]\n else:\n clip_value_max = np.max(x)\n kwargs[\"eps\"] = float(clip_value_max)\n kwargs[\"eps_step\"] = float(clip_value_max / (max_iter / 2))\n\n # Create attack\n attack_pgd = ProjectedGradientDescent(estimator=classifier, **kwargs) # type: ignore\n\n # Evaluate accuracy with maximal attack budget\n x_adv = attack_pgd.generate(x=x, y=y)\n y_pred_adv = classifier.predict(x=x_adv, y=y)\n accuracy_adv = self._get_accuracy(y=y, y_pred=y_pred_adv)\n\n # Decide of obfuscated gradients likely\n if accuracy_adv > 1 / classifier.nb_classes:\n self._detected_obfuscating_gradients = True\n else:\n self._detected_obfuscating_gradients = False\n\n def plot(self) -> None: # pragma: no cover\n \"\"\"\n Plot the Security Curve of adversarial accuracy as function opf attack budget `eps` together with the accuracy\n on benign samples.\n \"\"\"\n from matplotlib import pyplot as plt\n\n plt.plot(self.eps_list, self.accuracy_adv_list, label=\"adversarial\", marker=\"o\")\n plt.plot(\n [self.eps_list[0], self.eps_list[-1]], # type: ignore\n [self.accuracy, self.accuracy], # type: ignore\n linestyle=\"--\",\n label=\"benign\",\n )\n plt.legend()\n plt.xlabel(\"Attack budget eps\")\n plt.ylabel(\"Accuracy\")\n if self.detected_obfuscating_gradients:\n plt.title(\"Potential gradient obfuscation detected.\")\n else:\n plt.title(\"No gradient obfuscation detected\")\n plt.ylim([0, 1.05])\n plt.show()\n\n @staticmethod\n def _get_accuracy(y: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate accuracy of predicted labels.\n\n :param y: True labels.\n :param y_pred: Predicted labels.\n :return: Accuracy.\n \"\"\"\n return np.mean(np.argmax(y, axis=1) == np.argmax(y_pred, axis=1)).item()\n\n def __repr__(self):\n repr_ = f\"{self.__module__ + '.' + self.__class__.__name__}(eps={self.eps})\"\n return repr_\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/experimental/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains the experimental Estimator API.\n\"\"\"\n\nfrom art.experimental.estimators.jax import JaxEstimator\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/experimental/estimators/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nExperimental Estimator API\n\"\"\"\n\nfrom art.experimental.estimators.jax import JaxEstimator\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/experimental/estimators/jax.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the abstract estimator `JaxEstimator` for Jax models.\n\"\"\"\nimport logging\n\nimport numpy as np\n\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin, NeuralNetworkMixin\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass JaxEstimator(NeuralNetworkMixin, LossGradientsMixin, BaseEstimator):\n \"\"\"\n Estimator class for Jax models.\n \"\"\"\n\n estimator_params = BaseEstimator.estimator_params + NeuralNetworkMixin.estimator_params\n\n def __init__(self, **kwargs) -> None:\n \"\"\"\n Estimator class for Jax models.\n\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n super().__init__(**kwargs)\n\n JaxEstimator._check_params(self)\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs):\n \"\"\"\n Perform prediction of the neural network for samples `x`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param batch_size: Batch size.\n :return: Predictions.\n :rtype: Format as expected by the `model`\n \"\"\"\n return NeuralNetworkMixin.predict(self, x, batch_size=batch_size, **kwargs)\n\n def fit(self, x: np.ndarray, y, batch_size: int = 128, nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the model of the estimator on the training data `x` and `y`.\n\n :param x: Samples of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,\n nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2).\n :param y: Target values.\n :type y: Format as expected by the `model`\n :param batch_size: Batch size.\n :param nb_epochs: Number of training epochs.\n \"\"\"\n NeuralNetworkMixin.fit(self, x, y, batch_size=batch_size, nb_epochs=nb_epochs, **kwargs)\n\n def set_params(self, **kwargs) -> None:\n \"\"\"\n Take a dictionary of parameters and apply checks before setting them as attributes.\n\n :param kwargs: A dictionary of attributes.\n \"\"\"\n super().set_params(**kwargs)\n self._check_params()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/experimental/estimators/classification/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nExperimental classifiers.\n\"\"\"\n\nfrom art.experimental.estimators.classification.jax import JaxClassifier\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/experimental/estimators/classification/jax.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `JaxClassifier` for Jax models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom collections.abc import Callable\nimport logging\nimport random\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import (\n ClassGradientsMixin,\n ClassifierMixin,\n)\nfrom art.experimental.estimators.jax import JaxEstimator\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE, PREPROCESSING_TYPE\n from art.data_generators import DataGenerator\n from art.defences.preprocessor import Preprocessor\n from art.defences.postprocessor import Postprocessor\n\nlogger = logging.getLogger(__name__)\n\n\nclass JaxClassifier(ClassGradientsMixin, ClassifierMixin, JaxEstimator):\n \"\"\"\n This class implements a classifier with the Jax framework.\n \"\"\"\n\n estimator_params = (\n JaxEstimator.estimator_params\n + ClassifierMixin.estimator_params\n + [\n \"predict_func\",\n \"loss_func\",\n \"update_func\",\n ]\n )\n\n def __init__(\n self,\n model: list,\n predict_func: Callable,\n loss_func: Callable,\n update_func: Callable,\n input_shape: tuple[int, ...],\n nb_classes: int,\n channels_first: bool = False,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n preprocessing_defences: \"Preprocessor\" | list[\"Preprocessor\"] | None = None,\n postprocessing_defences: \"Postprocessor\" | list[\"Postprocessor\"] | None = None,\n preprocessing: \"PREPROCESSING_TYPE\" = (0.0, 1.0),\n ) -> None:\n \"\"\"\n Initialization specifically for the Jax-based implementation.\n\n :param model: Jax model, represented as a list of model parameters.\n :param predict_func: A function used to predict model output given the model and the input.\n :param loss_func: The loss function for which to compute gradients for training.\n :param update_func: The update function for which to train the model.\n :param input_shape: The shape of one input instance.\n :param nb_classes: The number of classes of the model.\n :param channels_first: Set channels first or last.\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :param preprocessing_defences: Preprocessing defence(s) to be applied by the classifier.\n :param postprocessing_defences: Postprocessing defence(s) to be applied by the classifier.\n :param preprocessing: Tuple of the form `(subtrahend, divisor)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be subtracted from the input. The input will then\n be divided by the second one.\n \"\"\"\n super().__init__(\n model=model,\n clip_values=clip_values,\n channels_first=channels_first,\n preprocessing_defences=preprocessing_defences,\n postprocessing_defences=postprocessing_defences,\n preprocessing=preprocessing,\n )\n\n self._predict_func = predict_func\n self._loss_func = loss_func\n self._update_func = update_func\n self._nb_classes = nb_classes\n self._input_shape = input_shape\n\n @property\n def model(self) -> list:\n return self._model\n\n @property\n def input_shape(self) -> tuple[int, ...]:\n \"\"\"\n Return the shape of one input sample.\n\n :return: Shape of one input sample.\n \"\"\"\n return self._input_shape # type: ignore\n\n @property\n def predict_func(self) -> Callable:\n \"\"\"\n Return the predict function.\n\n :return: The predict function.\n \"\"\"\n return self._predict_func\n\n @property\n def loss_func(self) -> Callable:\n \"\"\"\n Return the loss function.\n\n :return: The loss function.\n \"\"\"\n return self._loss_func\n\n @property\n def update_func(self) -> Callable:\n \"\"\"\n Return the update function.\n\n :return: The update function.\n \"\"\"\n return self._update_func\n\n def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Input samples.\n :param batch_size: Size of batches.\n :return: Array of predictions of shape `(nb_inputs, nb_classes)`.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n results_list = []\n\n # Run prediction with batch processing\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n for m in range(num_batch):\n # Batch indexes\n begin, end = (\n m * batch_size,\n min((m + 1) * batch_size, x_preprocessed.shape[0]),\n )\n\n output = self.predict_func(self.model, x_preprocessed[begin:end])\n results_list.append(output)\n\n results = np.vstack(results_list)\n\n # Apply postprocessing\n predictions = self._apply_postprocessing(preds=results, fit=False)\n\n return predictions\n\n def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, **kwargs) -> None:\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :param y: Target values.\n :param batch_size: Size of batches.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch\n and providing it takes no effect.\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n num_batch = int(np.ceil(len(x_preprocessed) / float(batch_size)))\n ind = np.arange(len(x_preprocessed)).tolist()\n\n # Start training\n for _ in range(nb_epochs):\n # Shuffle the examples\n random.shuffle(ind)\n\n # Train for one epoch\n for m in range(num_batch):\n i_batch = x_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]\n o_batch = y_preprocessed[ind[m * batch_size : (m + 1) * batch_size]]\n self._model = self.update_func(self.model, i_batch, o_batch)\n\n def loss_gradient(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param y: Target values.\n :return: Array of gradients of the same shape as `x`.\n \"\"\"\n from jax import grad\n\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n # Compute gradients\n grads = grad(self.loss_func, argnums=(0, 1))(self.model, x_preprocessed, y_preprocessed)[1]\n\n assert grads.shape == x.shape\n\n return grads.copy()\n\n def fit_generator(self, generator: \"DataGenerator\", nb_epochs: int = 20, **kwargs) -> None:\n \"\"\"\n Fit the classifier using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch.\n :param nb_epochs: Number of epochs to use for training.\n :param kwargs: Dictionary of framework-specific arguments.\n \"\"\"\n raise NotImplementedError\n\n def class_gradient(self, x: np.ndarray, label: int | list[int] | np.ndarray | None = None, **kwargs) -> np.ndarray:\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n \"\"\"\n raise NotImplementedError\n\n def get_activations(\n self,\n x: np.ndarray,\n layer: int | str | None = None,\n batch_size: int = 128,\n framework: bool = False,\n ) -> np.ndarray:\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :param layer: Layer for computing the activations\n :param batch_size: Size of batches.\n :param framework: If true, return the intermediate tensor representation of the activation.\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n \"\"\"\n raise NotImplementedError\n\n def save(self, filename: str, path: str | None = None) -> None:\n \"\"\"\n Save a model to file in the format specific to the backend framework.\n\n :param filename: Name of the file where to store the model.\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `ART_DATA_PATH`.\n \"\"\"\n raise NotImplementedError\n\n def __getstate__(self) -> dict[str, Any]:\n \"\"\"\n Use to ensure `JaxClassifier` can be pickled.\n\n :return: State dictionary with instance parameters.\n \"\"\"\n raise NotImplementedError\n\n def __setstate__(self, state: dict[str, Any]) -> None:\n \"\"\"\n Use to ensure `JaxClassifier` can be unpickled.\n\n :param state: State dictionary with instance parameters to restore.\n \"\"\"\n raise NotImplementedError\n\n def compute_loss(self, x: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:\n raise NotImplementedError\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing metrics and verifications.\n\"\"\"\n\nfrom art.metrics.metrics import adversarial_accuracy\nfrom art.metrics.metrics import empirical_robustness\nfrom art.metrics.metrics import loss_sensitivity\nfrom art.metrics.metrics import clever\nfrom art.metrics.metrics import clever_u\nfrom art.metrics.metrics import clever_t\nfrom art.metrics.metrics import wasserstein_distance\nfrom art.metrics.verification_decisions_trees import RobustnessVerificationTreeModelsCliqueMethod\nfrom art.metrics.gradient_check import loss_gradient_check\nfrom art.metrics.privacy import PDTP, SHAPr, ComparisonType\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/gradient_check.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements gradient check functions for estimators\n\"\"\"\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nif TYPE_CHECKING:\n from art.estimators.estimator import LossGradientsMixin\n\n\ndef loss_gradient_check(\n estimator: \"LossGradientsMixin\",\n x: np.ndarray,\n y: np.ndarray,\n training_mode: bool = False,\n verbose: bool = True,\n **kwargs\n) -> np.ndarray:\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x` and identify points where the gradient is zero, nan, or inf\n\n :param estimator: The classifier to be analyzed.\n :param x: Input with shape as expected by the classifier's model.\n :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape\n (nb_samples,).\n :param training_mode: `True` for model set to training mode and `False` for model set to evaluation mode.\n :param verbose: Show progress bars.\n :return: Array of booleans with the shape (len(x), 3). If true means the gradient of the loss w.r.t. the\n particular `x` was bad (zero, nan, inf).\n \"\"\"\n assert len(x) == len(y), \"x and y must be the same length\"\n\n is_bad = []\n for i in trange(len(x), desc=\"Gradient check\", disable=not verbose):\n grad = estimator.loss_gradient(x=x[[i]], y=y[[i]], training_mode=training_mode, **kwargs)\n is_bad.append(\n [\n (np.min(grad) == 0 and np.max(grad) == 0),\n np.any(np.isnan(grad)),\n np.any(np.isinf(grad)),\n ]\n )\n\n return np.array(is_bad, dtype=bool)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/metrics.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule implementing varying metrics for assessing model robustness. These fall mainly under two categories:\nattack-dependent and attack-independent.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nfrom functools import reduce\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nimport numpy.linalg as la\nfrom scipy.optimize import fmin as scipy_optimizer\nfrom scipy.stats import weibull_min\nfrom tqdm.auto import tqdm\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.auto_attack import AutoAttack\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.attacks.evasion.hop_skip_jump import HopSkipJump\nfrom art.utils import random_sphere\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE, CLASSIFIER_LOSS_GRADIENTS_TYPE, CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\n\nlogger = logging.getLogger(__name__)\n\nSUPPORTED_METHODS: dict[str, dict[str, Any]] = {\n \"auto\": {\n \"class\": AutoAttack,\n \"params\": {\"eps_step\": 0.1},\n },\n \"fgsm\": {\n \"class\": FastGradientMethod,\n \"params\": {\"eps_step\": 0.1},\n },\n \"hsj\": {\n \"class\": HopSkipJump,\n \"params\": {\n \"max_iter\": 50,\n \"max_eval\": 10000,\n \"init_eval\": 100,\n \"init_size\": 100,\n },\n },\n}\n\n\ndef get_crafter(classifier: \"CLASSIFIER_TYPE\", attack: str, params: dict[str, Any] | None = None) -> \"EvasionAttack\":\n \"\"\"\n Create an attack instance to craft adversarial samples.\n\n :param classifier: A trained model.\n :param attack: adversarial attack name.\n :param params: Parameters specific to the adversarial attack.\n :return: An attack instance.\n \"\"\"\n try:\n crafter = SUPPORTED_METHODS[attack][\"class\"](classifier)\n except Exception: # pragma: no cover\n logger.warning(\"Available attacks include %s.\", \", \".join(SUPPORTED_METHODS.keys()))\n raise NotImplementedError(f\"{attack} crafting method not supported.\") from Exception\n\n if \"params\" in SUPPORTED_METHODS[attack]:\n crafter.set_params(**SUPPORTED_METHODS[attack][\"params\"])\n if params:\n crafter.set_params(**params)\n\n return crafter\n\n\ndef adversarial_accuracy(\n classifier: \"CLASSIFIER_TYPE\",\n x: np.ndarray,\n y: np.ndarray | None = None,\n attack_name: str | None = None,\n attack_params: dict[str, Any] | None = None,\n attack_crafter: EvasionAttack | None = None,\n) -> float:\n \"\"\"\n Compute the adversarial accuracy of a classifier object over the sample `x` for a given adversarial crafting\n method `attack`, with optional true labels `y`. `attack_name` can be specified\n to use a preset attack, or `attack_crafter` for wider choices\n and customized parameters.\n Note that if `y` is not specified, the score does not exclude wrong predictions by the classifier.\n\n :param classifier: A trained model.\n :param x: Input samples of shape that can be fed into `classifier`.\n :param y: True labels of `x`.\n :param attack_name: A string specifying the attack to be used as a key to `art.metrics.metrics.SUPPORTED_METHODS`.\n :param attack_params: A dictionary with attack-specific parameters. If the attack has a norm attribute, then it will\n be used as the norm for calculating the robustness; otherwise the standard Euclidean distance\n is used (norm=2).\n :param attack_crafter: EvasionAttack instance with `generate` method to apply on `x` to create adversarial examples.\n :return: The adversarial accuracy of the classifier computed on `x`.\n \"\"\"\n\n if attack_crafter is None:\n if attack_name is None:\n supported_methods = \", \".join(SUPPORTED_METHODS.keys())\n raise ValueError(\n \"At least one of `attack_name` or `attack_crafter` must be specified.\"\n + f\"Available values for `attack_name' include {supported_methods}.\"\n )\n\n if x.max() > 1.0 or x.min() < 0:\n logger.warning(\"The input range is outside [0,1]. Please consider using `attack_crafter` instead.\")\n\n attack_crafter = get_crafter(classifier, attack_name, attack_params)\n attack_crafter.set_params(**{\"minimal\": True})\n\n adv_x = attack_crafter.generate(x)\n\n # Predict the labels for adversarial examples\n y_orig = np.argmax(classifier.predict(x), axis=1)\n y_pred = np.argmax(classifier.predict(adv_x), axis=1)\n\n if y is None:\n idxs = y_pred == y_orig\n return np.sum(idxs) / len(y_orig)\n\n if len(y.shape) > 1:\n y = np.argmax(y, axis=1)\n y_corr = y_orig == y\n return np.sum((y_pred == y_orig) & y_corr) / np.sum(y_corr)\n\n\ndef empirical_robustness(\n classifier: \"CLASSIFIER_TYPE\",\n x: np.ndarray,\n attack_name: str,\n attack_params: dict[str, Any] | None = None,\n) -> float | np.ndarray:\n \"\"\"\n Compute the Empirical Robustness of a classifier object over the sample `x` for a given adversarial crafting\n method `attack`. This is equivalent to computing the minimal perturbation that the attacker must introduce for a\n successful attack.\n\n | Paper link: https://arxiv.org/abs/1511.04599\n\n :param classifier: A trained model.\n :param x: Data sample of shape that can be fed into `classifier`.\n :param attack_name: A string specifying the attack to be used as a key to `art.metrics.metrics.SUPPORTED_METHODS`.\n :param attack_params: A dictionary with attack-specific parameters. If the attack has a norm attribute, then it will\n be used as the norm for calculating the robustness; otherwise the standard Euclidean distance\n is used (norm=2).\n :return: The average empirical robustness computed on `x`.\n \"\"\"\n crafter = get_crafter(classifier, attack_name, attack_params)\n crafter.set_params(**{\"minimal\": True})\n adv_x = crafter.generate(x)\n\n # Predict the labels for adversarial examples\n y = classifier.predict(x)\n y_pred = classifier.predict(adv_x)\n\n idxs = np.argmax(y_pred, axis=1) != np.argmax(y, axis=1)\n if np.sum(idxs) == 0.0:\n return 0.0\n\n norm_type = 2\n if hasattr(crafter, \"norm\"):\n norm_type = crafter.norm # type: ignore\n perts_norm = la.norm((adv_x - x).reshape(x.shape[0], -1), ord=norm_type, axis=1)\n perts_norm = perts_norm[idxs]\n\n return np.mean(perts_norm / la.norm(x[idxs].reshape(np.sum(idxs), -1), ord=norm_type, axis=1))\n\n\n# def nearest_neighbour_dist(classifier, x, x_ref, attack_name, attack_params=None):\n# \"\"\"\n# Compute the (average) nearest neighbour distance between the sets `x` and `x_train`: for each point in `x`,\n# measure the Euclidean distance to its closest point in `x_train`, then average over all points.\n#\n# :param classifier: A trained model\n# :type classifier: :class:`.Classifier`\n# :param x: Data sample of shape that can be fed into `classifier`\n# :type x: `np.ndarray`\n# :param x_ref: Reference data sample to be considered as neighbors\n# :type x_ref: `np.ndarray`\n# :param attack_name: adversarial attack name\n# :type attack_name: `str`\n# :param attack_params: Parameters specific to the adversarial attack\n# :type attack_params: `dict`\n# :return: The average nearest neighbors distance\n# :rtype: `float`\n# \"\"\"\n# # Craft the adversarial examples\n# crafter = get_crafter(classifier, attack_name, attack_params)\n# adv_x = crafter.generate(x, minimal=True)\n#\n# # Predict the labels for adversarial examples\n# y = classifier.predict(x)\n# y_pred = classifier.predict(adv_x)\n#\n# adv_x_ = adv_x.reshape(adv_x.shape[0], np.prod(adv_x.shape[1:]))\n# x_ = x_ref.reshape(x_ref.shape[0], np.prod(x_ref.shape[1:]))\n# dists = la.norm(adv_x_ - x_, axis=1)\n#\n# # TODO check if following computation is correct ?\n# dists = np.min(dists, axis=1) / la.norm(x.reshape(x.shape[0], -1), ord=2, axis=1)\n# idxs = (np.argmax(y_pred, axis=1) != np.argmax(y, axis=1))\n# avg_nn_dist = np.mean(dists[idxs])\n#\n# return avg_nn_dist\n\n\ndef loss_sensitivity(classifier: \"CLASSIFIER_LOSS_GRADIENTS_TYPE\", x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Local loss sensitivity estimated through the gradients of the prediction at points in `x`.\n\n | Paper link: https://arxiv.org/abs/1706.05394\n\n :param classifier: A trained model.\n :param x: Data sample of shape that can be fed into `classifier`.\n :param y: Labels for sample `x`, one-hot encoded.\n :return: The average loss sensitivity of the model.\n \"\"\"\n grads = classifier.loss_gradient(x, y)\n norm = la.norm(grads.reshape(grads.shape[0], -1), ord=2, axis=1)\n\n return np.mean(norm)\n\n\ndef clever(\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n x: np.ndarray,\n nb_batches: int,\n batch_size: int,\n radius: float,\n norm: int,\n target: int | list[int] | None = None,\n target_sort: bool = False,\n c_init: float = 1.0,\n pool_factor: int = 10,\n verbose: bool = True,\n) -> np.ndarray | None:\n \"\"\"\n Compute CLEVER score for an untargeted attack.\n\n | Paper link: https://arxiv.org/abs/1801.10578\n\n :param classifier: A trained model.\n :param x: One input sample.\n :param nb_batches: Number of repetitions of the estimate.\n :param batch_size: Number of random examples to sample per batch.\n :param radius: Radius of the maximum perturbation.\n :param norm: Current support: 1, 2, np.inf.\n :param target: Class or classes to target. If `None`, targets all classes.\n :param target_sort: Should the target classes be sorted in prediction order. When `True` and `target` is `None`,\n sort results.\n :param c_init: initialization of Weibull distribution.\n :param pool_factor: The factor to create a pool of random samples with size pool_factor x n_s.\n :param verbose: Show progress bars.\n :return: CLEVER score.\n \"\"\"\n # Find the predicted class first\n y_pred = classifier.predict(np.array([x]))\n pred_class = np.argmax(y_pred, axis=1)[0]\n if target is None:\n # Get a list of untargeted classes\n if target_sort:\n target_classes = np.argsort(y_pred)[0][:-1]\n else:\n target_classes = [i for i in range(classifier.nb_classes) if i != pred_class]\n elif isinstance(target, (int, np.integer)):\n target_classes = [target]\n else:\n # Assume it's iterable\n target_classes = target\n score_list: list[float | None] = []\n for j in tqdm(target_classes, desc=\"CLEVER untargeted\", disable=not verbose):\n if j == pred_class:\n score_list.append(None)\n continue\n score = clever_t(classifier, x, j, nb_batches, batch_size, radius, norm, c_init, pool_factor)\n score_list.append(score)\n return np.array(score_list)\n\n\ndef clever_u(\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n x: np.ndarray,\n nb_batches: int,\n batch_size: int,\n radius: float,\n norm: int,\n c_init: float = 1.0,\n pool_factor: int = 10,\n verbose: bool = True,\n) -> float:\n \"\"\"\n Compute CLEVER score for an untargeted attack.\n\n | Paper link: https://arxiv.org/abs/1801.10578\n\n :param classifier: A trained model.\n :param x: One input sample.\n :param nb_batches: Number of repetitions of the estimate.\n :param batch_size: Number of random examples to sample per batch.\n :param radius: Radius of the maximum perturbation.\n :param norm: Current support: 1, 2, np.inf.\n :param c_init: initialization of Weibull distribution.\n :param pool_factor: The factor to create a pool of random samples with size pool_factor x n_s.\n :param verbose: Show progress bars.\n :return: CLEVER score.\n \"\"\"\n # Get a list of untargeted classes\n y_pred = classifier.predict(np.array([x]))\n pred_class = np.argmax(y_pred, axis=1)[0]\n untarget_classes = [i for i in range(classifier.nb_classes) if i != pred_class]\n\n # Compute CLEVER score for each untargeted class\n score_list = []\n for j in tqdm(untarget_classes, desc=\"CLEVER untargeted\", disable=not verbose):\n score = clever_t(classifier, x, j, nb_batches, batch_size, radius, norm, c_init, pool_factor)\n score_list.append(score)\n\n return np.min(score_list)\n\n\ndef clever_t(\n classifier: \"CLASSIFIER_CLASS_LOSS_GRADIENTS_TYPE\",\n x: np.ndarray,\n target_class: int,\n nb_batches: int,\n batch_size: int,\n radius: float,\n norm: float,\n c_init: float = 1.0,\n pool_factor: int = 10,\n) -> float:\n \"\"\"\n Compute CLEVER score for a targeted attack.\n\n | Paper link: https://arxiv.org/abs/1801.10578\n\n :param classifier: A trained model.\n :param x: One input sample.\n :param target_class: Targeted class.\n :param nb_batches: Number of repetitions of the estimate.\n :param batch_size: Number of random examples to sample per batch.\n :param radius: Radius of the maximum perturbation.\n :param norm: Current support: 1, 2, np.inf.\n :param c_init: Initialization of Weibull distribution.\n :param pool_factor: The factor to create a pool of random samples with size pool_factor x n_s.\n :return: CLEVER score.\n \"\"\"\n # Check if the targeted class is different from the predicted class\n y_pred = classifier.predict(np.array([x]))\n pred_class = np.argmax(y_pred, axis=1)[0]\n if target_class == pred_class: # pragma: no cover\n raise ValueError(\"The targeted class is the predicted class.\")\n\n # Check if pool_factor is smaller than 1\n if pool_factor < 1: # pragma: no cover\n raise ValueError(\"The `pool_factor` must be larger than 1.\")\n\n # Some auxiliary vars\n rand_pool_grad_set = []\n grad_norm_set = []\n dim = reduce(lambda x_, y: x_ * y, x.shape, 1)\n shape = [pool_factor * batch_size]\n shape.extend(x.shape)\n\n # Generate a pool of samples\n rand_pool = np.reshape(\n random_sphere(nb_points=pool_factor * batch_size, nb_dims=dim, radius=radius, norm=norm),\n shape,\n )\n rand_pool += np.repeat(np.array([x]), pool_factor * batch_size, 0)\n rand_pool = rand_pool.astype(ART_NUMPY_DTYPE)\n if hasattr(classifier, \"clip_values\") and classifier.clip_values is not None:\n np.clip(rand_pool, classifier.clip_values[0], classifier.clip_values[1], out=rand_pool)\n\n # Change norm since q = p / (p-1)\n if norm == 1:\n norm = np.inf\n elif norm == np.inf:\n norm = 1\n elif norm != 2: # pragma: no cover\n raise ValueError(f\"Norm {norm} not supported\")\n\n # Compute gradients for all samples in rand_pool\n for i in range(batch_size):\n rand_pool_batch = rand_pool[i * pool_factor : (i + 1) * pool_factor]\n\n # Compute gradients\n grad_pred_class = classifier.class_gradient(rand_pool_batch, label=pred_class)\n grad_target_class = classifier.class_gradient(rand_pool_batch, label=target_class)\n\n if np.isnan(grad_pred_class).any() or np.isnan(grad_target_class).any(): # pragma: no cover\n raise Exception(\"The classifier results NaN gradients.\")\n\n grad = grad_pred_class - grad_target_class\n grad = np.reshape(grad, (pool_factor, -1))\n grad = np.linalg.norm(grad, ord=norm, axis=1)\n rand_pool_grad_set.extend(grad)\n\n rand_pool_grads = np.array(rand_pool_grad_set)\n\n # Loop over the batches\n for _ in range(nb_batches):\n # Random selection of gradients\n grad_norm = rand_pool_grads[np.random.choice(pool_factor * batch_size, batch_size)]\n grad_norm = np.max(grad_norm)\n grad_norm_set.append(grad_norm)\n\n # Maximum likelihood estimation for max gradient norms\n [_, loc, _] = weibull_min.fit(-np.array(grad_norm_set), c_init, optimizer=scipy_optimizer)\n\n # Compute function value\n values = classifier.predict(np.array([x]))\n value = values[:, pred_class] - values[:, target_class]\n\n # Compute scores\n score = np.min([-value[0] / loc, radius])\n\n return score\n\n\ndef wasserstein_distance(\n u_values: np.ndarray,\n v_values: np.ndarray,\n u_weights: np.ndarray | None = None,\n v_weights: np.ndarray | None = None,\n) -> np.ndarray:\n \"\"\"\n Compute the first Wasserstein distance between two 1D distributions.\n\n :param u_values: Values of first distribution with shape (nb_samples, feature_dim_1, ..., feature_dim_n).\n :param v_values: Values of second distribution with shape (nb_samples, feature_dim_1, ..., feature_dim_n).\n :param u_weights: Weight for each value. If None, equal weights will be used.\n :param v_weights: Weight for each value. If None, equal weights will be used.\n :return: The Wasserstein distance between the two distributions.\n \"\"\"\n import scipy\n\n assert u_values.shape == v_values.shape\n if u_weights is not None:\n assert v_weights is not None\n if u_weights is None:\n assert v_weights is None\n if u_weights is not None and v_weights is not None:\n assert u_weights.shape == v_weights.shape\n if u_weights is not None:\n assert u_values.shape[0] == u_weights.shape[0]\n\n u_values = u_values.flatten().reshape(u_values.shape[0], -1)\n v_values = v_values.flatten().reshape(v_values.shape[0], -1)\n\n if u_weights is not None and v_weights is not None:\n u_weights = u_weights.flatten().reshape(u_weights.shape[0], -1)\n v_weights = v_weights.flatten().reshape(v_weights.shape[0], -1)\n\n w_d = np.zeros(u_values.shape[0])\n\n for i in range(u_values.shape[0]):\n if u_weights is None and v_weights is None:\n w_d[i] = scipy.stats.wasserstein_distance(u_values[i], v_values[i])\n elif u_weights is not None and v_weights is not None:\n w_d[i] = scipy.stats.wasserstein_distance(u_values[i], v_values[i], u_weights[i], v_weights[i])\n\n return w_d\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/verification_decisions_trees.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements robustness verifications for decision-tree-based models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import trange\n\nfrom art.utils import check_and_transform_label_format\n\nif TYPE_CHECKING:\n from art.estimators.classification.classifier import ClassifierDecisionTree\n\nlogger = logging.getLogger(__name__)\n\n\nclass Interval:\n \"\"\"\n Representation of an intervals bound.\n \"\"\"\n\n def __init__(self, lower_bound: float, upper_bound: float) -> None:\n \"\"\"\n An interval of a feature.\n\n :param lower_bound: The lower boundary of the feature.\n :param upper_bound: The upper boundary of the feature.\n \"\"\"\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n\n\nclass Box:\n \"\"\"\n Representation of a box of intervals bounds.\n \"\"\"\n\n def __init__(self, intervals: dict[int, Interval] | None = None) -> None:\n \"\"\"\n A box of intervals.\n\n :param intervals: A dictionary of intervals with features as keys.\n \"\"\"\n if intervals is None:\n self.intervals = {}\n else:\n self.intervals = intervals\n\n def intersect_with_box(self, box: \"Box\") -> None:\n \"\"\"\n Get the intersection of two interval boxes. This function modifies this box instance.\n\n :param box: Interval box to intersect with this box.\n \"\"\"\n for key, value in box.intervals.items():\n if key not in self.intervals:\n self.intervals[key] = value\n else:\n lower_bound = max(self.intervals[key].lower_bound, value.lower_bound)\n upper_bound = min(self.intervals[key].upper_bound, value.upper_bound)\n\n if lower_bound >= upper_bound: # pragma: no cover\n self.intervals.clear()\n break\n\n self.intervals[key] = Interval(lower_bound, upper_bound)\n\n def get_intersection(self, box: \"Box\") -> \"Box\":\n \"\"\"\n Get the intersection of two interval boxes. This function creates a new box instance.\n\n :param box: Interval box to intersect with this box.\n \"\"\"\n box_new = Box(intervals=self.intervals.copy())\n\n for key, value in box.intervals.items():\n if key not in box_new.intervals:\n box_new.intervals[key] = value\n else:\n lower_bound = max(box_new.intervals[key].lower_bound, value.lower_bound)\n upper_bound = min(box_new.intervals[key].upper_bound, value.upper_bound)\n\n if lower_bound >= upper_bound:\n box_new.intervals.clear()\n return box_new\n\n box_new.intervals[key] = Interval(lower_bound, upper_bound)\n\n return box_new\n\n def __repr__(self):\n return self.__class__.__name__ + f\"({self.intervals})\"\n\n\nclass LeafNode:\n \"\"\"\n Representation of a leaf node of a decision tree.\n \"\"\"\n\n def __init__(\n self,\n tree_id: int | None,\n class_label: int,\n node_id: int | None,\n box: Box,\n value: float,\n ) -> None:\n \"\"\"\n Create a leaf node representation.\n\n :param tree_id: ID of the decision tree.\n :param class_label: ID of class to which this leaf node is contributing.\n :param box: A box representing the n_feature-dimensional bounding intervals that reach this leaf node.\n :param value: Prediction value at this leaf node.\n \"\"\"\n self.tree_id = tree_id\n self.class_label = class_label\n self.node_id = node_id\n self.box = box\n self.value = value\n\n def __repr__(self):\n return (\n self.__class__.__name__ + f\"({self.tree_id}, {self.class_label}, {self.node_id}, {self.box}, {self.value})\"\n )\n\n\nclass Tree:\n \"\"\"\n Representation of a decision tree.\n \"\"\"\n\n def __init__(self, class_id: int | None, leaf_nodes: list[LeafNode]) -> None:\n \"\"\"\n Create a decision tree representation.\n\n :param class_id: ID of the class to which this decision tree contributes.\n :param leaf_nodes: A list of leaf nodes of this decision tree.\n \"\"\"\n self.class_id = class_id\n self.leaf_nodes = leaf_nodes\n\n\nclass RobustnessVerificationTreeModelsCliqueMethod:\n \"\"\"\n Robustness verification for decision-tree-based models.\n Following the implementation in https://github.com/chenhongge/treeVerification (MIT License, 9 August 2019)\n\n | Paper link: https://arxiv.org/abs/1906.03849\n \"\"\"\n\n def __init__(self, classifier: \"ClassifierDecisionTree\", verbose: bool = True) -> None:\n \"\"\"\n Create robustness verification for a decision-tree-based classifier.\n\n :param classifier: A trained decision-tree-based classifier.\n :param verbose: Show progress bars.\n \"\"\"\n self._classifier = classifier\n self.verbose = verbose\n self._trees = self._classifier.get_trees()\n\n def verify(\n self,\n x: np.ndarray,\n y: np.ndarray,\n eps_init: float,\n norm: float = np.inf,\n nb_search_steps: int = 10,\n max_clique: int = 2,\n max_level: int = 2,\n ) -> tuple[float, float]:\n \"\"\"\n Verify the robustness of the classifier on the dataset `(x, y)`.\n\n :param x: Feature data of shape `(nb_samples, nb_features)`.\n :param y: Labels, one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape\n (nb_samples,)`.\n :param eps_init: Attack budget for the first search step.\n :param norm: The norm to apply epsilon.\n :param nb_search_steps: The number of search steps.\n :param max_clique: The maximum number of nodes in a clique.\n :param max_level: The maximum number of clique search levels.\n :return: A tuple of the average robustness bound and the verification error at `eps`.\n \"\"\"\n if np.min(x) < 0 or np.max(x) > 1:\n raise ValueError(\n \"There are features not in the range [0, 1]. The current implementation only supports normalized input\"\n \"values in range [0 1].\"\n )\n\n self.x: np.ndarray = x\n self.y: np.ndarray = check_and_transform_label_format(\n y, nb_classes=self._classifier.nb_classes, return_one_hot=False\n )\n self.max_clique: int = max_clique\n self.max_level: int = max_level\n\n average_bound: float = 0.0\n num_initial_successes: int = 0\n num_samples: int = x.shape[0]\n\n # pylint: disable=too-many-nested-blocks\n pbar = trange(num_samples, desc=\"Decision tree verification\", disable=not self.verbose)\n for i_sample in pbar:\n\n eps: float = eps_init\n robust_log: list[bool] = []\n i_robust = None\n i_not_robust = None\n eps_robust: float = 0.0\n eps_not_robust: float = 0.0\n best_score: float | None\n\n for i_step in range(nb_search_steps):\n logger.info(\"Search step %d: eps = %.4g\", i_step, eps)\n\n is_robust = True\n\n if self._classifier.nb_classes <= 2:\n best_score = self._get_best_score(i_sample, eps, norm, target_label=None)\n is_robust = (self.y[i_sample] < 0.5 and best_score < 0) or (\n self.y[i_sample] > 0.5 and best_score > 0.0\n )\n else:\n for i_class in range(self._classifier.nb_classes):\n if i_class != self.y[i_sample]:\n best_score = self._get_best_score(i_sample, eps, norm, target_label=i_class)\n is_robust = is_robust and (best_score > 0.0)\n if not is_robust:\n break\n\n robust_log.append(is_robust)\n\n if is_robust:\n if i_step == 0:\n num_initial_successes += 1\n logger.info(\"Model is robust at eps = %.4g\", eps)\n i_robust = i_step\n eps_robust = eps\n else:\n logger.info(\"Model is not robust at eps = %.4g\", eps)\n i_not_robust = i_step\n eps_not_robust = eps\n\n if i_robust is None:\n eps /= 2.0\n else:\n if i_not_robust is None:\n if eps >= 1.0: # pragma: no cover\n logger.info(\"Abort binary search because eps increased above 1.0\")\n break\n eps = min(eps * 2.0, 1.0)\n else:\n eps = (eps_robust + eps_not_robust) / 2.0\n\n if i_robust is not None:\n clique_bound = eps_robust\n average_bound += clique_bound\n else:\n logger.info(\n \"point %s: WARNING! no robust eps found, verification bound is set as 0 !\",\n i_sample,\n )\n\n verified_error = 1.0 - num_initial_successes / num_samples\n average_bound = average_bound / num_samples\n\n logger.info(\"The average interval bound is: %.4g\", average_bound)\n logger.info(\"The verified error at eps = %.4g is: %.4g\", eps_init, verified_error)\n\n return average_bound, verified_error\n\n def _get_k_partite_clique(\n self,\n accessible_leaves: list[list[LeafNode]],\n label: int,\n target_label: int | None,\n ) -> tuple[float, list]:\n \"\"\"\n Find the K partite cliques among the accessible leaf nodes.\n\n :param accessible_leaves: list of lists of accessible leaf nodes.\n :param label: The try label of the current sample.\n :param target_label: The target label.\n :return: The best score and a list of new cliques.\n \"\"\"\n new_nodes_list = []\n best_scores_sum = 0.0\n\n # pylint: disable=too-many-nested-blocks\n for start_tree in range(0, len(accessible_leaves), self.max_clique):\n cliques_old: list[dict[str, Box | float]] = []\n cliques_new: list[dict[str, Box | float]] = []\n\n # Start searching for cliques\n for accessible_leaf in accessible_leaves[start_tree]:\n if (\n self._classifier.nb_classes > 2\n and target_label is not None\n and target_label == accessible_leaf.class_label\n ):\n new_leaf_value = -accessible_leaf.value\n else:\n new_leaf_value = accessible_leaf.value\n cliques_old.append({\"box\": accessible_leaf.box, \"value\": new_leaf_value})\n\n # Loop over all trees\n for i_tree in range(\n start_tree + 1,\n min(len(accessible_leaves), start_tree + self.max_clique),\n ):\n cliques_new.clear()\n # Loop over all existing cliques\n for clique in cliques_old:\n # Loop over leaf nodes in tree\n for accessible_leaf in accessible_leaves[i_tree]:\n leaf_box = accessible_leaf.box.get_intersection(clique[\"box\"]) # type: ignore\n if leaf_box.intervals:\n if (\n self._classifier.nb_classes > 2\n and target_label is not None\n and target_label == accessible_leaf.class_label\n ):\n new_leaf_value = -accessible_leaf.value\n else:\n new_leaf_value = accessible_leaf.value\n cliques_new.append(\n {\n \"box\": leaf_box,\n \"value\": new_leaf_value + clique[\"value\"], # type: ignore\n }\n )\n\n cliques_old = cliques_new.copy()\n\n new_nodes = []\n best_score = 0.0\n for i, clique in enumerate(cliques_old):\n # Create a new node without tree_id and node_id to represent clique\n new_nodes.append(\n LeafNode(\n tree_id=None,\n class_label=label,\n node_id=None,\n box=clique[\"box\"], # type: ignore\n value=clique[\"value\"], # type: ignore\n )\n )\n\n if i == 0:\n best_score = clique[\"value\"] # type: ignore\n else:\n if label < 0.5 and self._classifier.nb_classes <= 2:\n best_score = max(best_score, clique[\"value\"]) # type: ignore\n else:\n best_score = min(best_score, clique[\"value\"]) # type: ignore\n\n new_nodes_list.append(new_nodes)\n best_scores_sum += best_score\n\n return best_scores_sum, new_nodes_list\n\n def _get_best_score(self, i_sample: int, eps: float, norm: float, target_label: int | None) -> float:\n \"\"\"\n Get the list of best scores.\n\n :param i_sample: Index of training sample in `x`.\n :param eps: Attack budget epsilon.\n :param norm: The norm to apply epsilon.\n :param target_label: The target label.\n :return: The best scores.\n \"\"\"\n nodes = self._get_accessible_leaves(i_sample, eps, norm, target_label)\n best_score: float = 0.0\n\n for i_level in range(self.max_level):\n if self._classifier.nb_classes > 2 and i_level > 0:\n target_label = None\n best_score, nodes = self._get_k_partite_clique(nodes, label=self.y[i_sample], target_label=target_label)\n\n # Stop if the root node has been reached\n if len(nodes) <= 1:\n break\n\n return best_score\n\n def _get_distance(self, box: Box, i_sample: int, norm: float) -> float:\n \"\"\"\n Determine the distance between sample and interval box.\n\n :param box: Interval box.\n :param i_sample: Index of training sample in `x`.\n :param norm: The norm to apply epsilon.\n :return: The distance.\n \"\"\"\n resulting_distance = 0.0\n\n for feature, interval in box.intervals.items():\n feature_value = self.x[i_sample, feature]\n\n if interval.lower_bound < feature_value < interval.upper_bound:\n distance = 0.0\n else:\n difference = max(\n feature_value - interval.upper_bound,\n interval.lower_bound - feature_value,\n )\n if norm == 0:\n distance = 1.0\n elif norm == np.inf:\n distance = difference\n else:\n distance = pow(difference, norm)\n\n if norm == np.inf:\n resulting_distance = max(resulting_distance, distance)\n else:\n resulting_distance += distance\n\n if norm not in [0, np.inf]:\n resulting_distance = pow(resulting_distance, 1.0 / norm)\n\n return resulting_distance\n\n def _get_accessible_leaves(\n self, i_sample: int, eps: float, norm: float, target_label: int | None\n ) -> list[list[LeafNode]]:\n \"\"\"\n Determine the leaf nodes accessible within the attack budget.\n\n :param i_sample: Index of training sample in `x`.\n :param eps: Attack budget epsilon.\n :param norm: The norm to apply epsilon.\n :param target_label: The target label.\n :return: A list of lists of leaf nodes.\n \"\"\"\n accessible_leaves = []\n\n for tree in self._trees:\n if (\n self._classifier.nb_classes <= 2\n or target_label is None\n or tree.class_id in [self.y[i_sample], target_label]\n ):\n\n leaves = []\n\n for leaf_node in tree.leaf_nodes:\n distance = self._get_distance(leaf_node.box, i_sample, norm)\n if leaf_node.box and distance <= eps:\n leaves.append(leaf_node)\n\n if not leaves: # pragma: no cover\n raise ValueError(\"No accessible leaves found.\")\n\n accessible_leaves.append(leaves)\n\n return accessible_leaves\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/privacy/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing metrics and verifications.\n\"\"\"\n\nfrom art.metrics.privacy.membership_leakage import PDTP, SHAPr, ComparisonType\nfrom art.metrics.privacy.worst_case_mia_score import get_roc_for_fpr, get_roc_for_multi_fprs\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/privacy/membership_leakage.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements membership leakage metrics.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\nfrom typing import TYPE_CHECKING\nfrom enum import Enum, auto\n\nimport numpy as np\nimport scipy\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom art.utils import check_and_transform_label_format, is_probability_array\n\nif TYPE_CHECKING:\n from art.utils import CLASSIFIER_TYPE\n\n\nclass ComparisonType(Enum):\n \"\"\"\n An Enum type for different kinds of comparisons between model outputs.\n \"\"\"\n\n RATIO = auto()\n DIFFERENCE = auto()\n\n\ndef PDTP( # pylint: disable=invalid-name\n target_estimator: \"CLASSIFIER_TYPE\",\n extra_estimator: \"CLASSIFIER_TYPE\",\n x: np.ndarray,\n y: np.ndarray,\n indexes: np.ndarray | None = None,\n num_iter: int = 10,\n comparison_type: ComparisonType | None = ComparisonType.RATIO,\n) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Compute the pointwise differential training privacy metric for the given classifier and training set.\n\n | Paper link: https://arxiv.org/abs/1712.09136\n\n :param target_estimator: The classifier to be analyzed.\n :param extra_estimator: Another classifier of the same type as the target classifier, but not yet fit.\n :param x: The training data of the classifier.\n :param y: Target values (class labels) of `x`, one-hot-encoded of shape (nb_samples, nb_classes) or indices of\n shape (nb_samples,).\n :param indexes: the subset of indexes of `x` to compute the PDTP metric on. If not supplied, PDTP will be\n computed for all samples in `x`.\n :param num_iter: the number of iterations of PDTP computation to run for each sample. If not supplied,\n defaults to 10. The result is the average across iterations.\n :param comparison_type: the way in which to compare the model outputs between models trained with and without\n a certain sample. Default is to compute the ratio.\n :return: A tuple of three arrays, containing the average (worse, standard deviation) PDTP value for each sample in\n the training set respectively. The higher the value, the higher the privacy leakage for that sample.\n \"\"\"\n from art.estimators.classification.pytorch import PyTorchClassifier\n from art.estimators.classification.tensorflow import TensorFlowV2Classifier\n from art.estimators.classification.scikitlearn import ScikitlearnClassifier\n\n supported_classifiers = (PyTorchClassifier, TensorFlowV2Classifier, ScikitlearnClassifier)\n\n if not isinstance(target_estimator, supported_classifiers) or not isinstance(\n extra_estimator, supported_classifiers\n ):\n raise ValueError(\"PDTP metric only supports classifiers of type PyTorch, TensorFlowV2 and ScikitLearn.\")\n if target_estimator.input_shape[0] != x.shape[1]:\n raise ValueError(\"Shape of x does not match input_shape of classifier\")\n y = check_and_transform_label_format(y, nb_classes=target_estimator.nb_classes)\n if y.shape[0] != x.shape[0]:\n raise ValueError(\"Number of rows in x and y do not match\")\n\n results = []\n\n for _ in range(num_iter):\n iter_results = []\n # get probabilities from original model\n pred = target_estimator.predict(x)\n if not is_probability_array(pred):\n try:\n pred = scipy.special.softmax(pred, axis=1)\n except Exception as exc: # pragma: no cover\n raise ValueError(\"PDTP metric only supports classifiers that output logits or probabilities.\") from exc\n # divide into 100 bins and return center of bin\n bins = np.array(np.arange(0.0, 1.01, 0.01).round(decimals=2))\n pred_bin_indexes = np.digitize(pred, bins)\n pred_bin_indexes[pred_bin_indexes == 101] = 100\n pred_bin = bins[pred_bin_indexes] - 0.005\n\n if indexes is None:\n indexes = np.array(range(x.shape[0]))\n if indexes is not None:\n for row in indexes:\n # create new model without sample in training data\n alt_x = np.delete(x, row, 0)\n alt_y = np.delete(y, row, 0)\n try:\n extra_estimator.reset()\n except NotImplementedError as exc: # pragma: no cover\n raise ValueError(\n \"PDTP metric can only be applied to classifiers that implement the reset method.\"\n ) from exc\n extra_estimator.fit(alt_x, alt_y)\n # get probabilities from new model\n alt_pred = extra_estimator.predict(x)\n if not is_probability_array(alt_pred):\n alt_pred = scipy.special.softmax(alt_pred, axis=1)\n # divide into 100 bins and return center of bin\n alt_pred_bin_indexes = np.digitize(alt_pred, bins)\n alt_pred_bin_indexes[alt_pred_bin_indexes == 101] = 100\n alt_pred_bin = bins[alt_pred_bin_indexes] - 0.005\n if comparison_type == ComparisonType.RATIO:\n ratio_1 = pred_bin / alt_pred_bin\n ratio_2 = alt_pred_bin / pred_bin\n # get max value\n max_value: float = max(ratio_1.max(), ratio_2.max())\n elif comparison_type == ComparisonType.DIFFERENCE:\n max_value = float(np.max(abs(pred_bin - alt_pred_bin)))\n else:\n raise ValueError(\"Unsupported comparison type.\")\n iter_results.append(max_value)\n results.append(iter_results)\n\n # get average of iterations for each sample\n # We now have a list of lists, internal lists represent an iteration. We need to transpose and get averages.\n per_sample: list[list[float]] = list(map(list, zip(*results)))\n avg_per_sample = np.array([sum(val) / len(val) for val in per_sample])\n worse_per_sample = np.max(per_sample, axis=1)\n std_dev_per_sample = np.std(per_sample, axis=1)\n\n # return avg+worse leakage + standard deviation per sample\n return avg_per_sample, worse_per_sample, std_dev_per_sample\n\n\ndef SHAPr( # pylint: disable=invalid-name\n target_estimator: \"CLASSIFIER_TYPE\",\n x_train: np.ndarray,\n y_train: np.ndarray,\n x_test: np.ndarray,\n y_test: np.ndarray,\n knn_metric: str | None = None,\n) -> np.ndarray:\n \"\"\"\n Compute the SHAPr membership privacy risk metric for the given classifier and training set.\n\n | Paper link: http://arxiv.org/abs/2112.02230\n\n :param target_estimator: The classifier to be analyzed.\n :param x_train: The training data of the classifier.\n :param y_train: Target values (class labels) of `x_train`, one-hot-encoded of shape (nb_samples, nb_classes) or\n indices of shape (nb_samples,).\n :param x_test: The test data of the classifier.\n :param y_test: Target values (class labels) of `x_test`, one-hot-encoded of shape (nb_samples, nb_classes) or\n indices of shape (nb_samples,).\n :param knn_metric: The distance metric to use for the KNN classifier (default is 'minkowski', which represents\n Euclidean distance).\n :return: an array containing the SHAPr scores for each sample in the training set. The higher the value,\n the higher the privacy leakage for that sample. Any value above 0 should be considered a privacy leak.\n \"\"\"\n if target_estimator.input_shape[0] != x_train.shape[1]:\n raise ValueError(\"Shape of x_train does not match input_shape of classifier\")\n\n if x_test.shape[1] != x_train.shape[1]:\n raise ValueError(\"Shape of x_train does not match the shape of x_test\")\n\n y_train = check_and_transform_label_format(y_train, target_estimator.nb_classes)\n if y_train.shape[0] != x_train.shape[0]:\n raise ValueError(\"Number of rows in x_train and y_train do not match\")\n\n y_test = check_and_transform_label_format(y_test, target_estimator.nb_classes)\n if y_test.shape[0] != x_test.shape[0]:\n raise ValueError(\"Number of rows in x_test and y_test do not match\")\n\n n_train_samples = x_train.shape[0]\n pred_train = target_estimator.predict(x_train)\n pred_test = target_estimator.predict(x_test)\n\n if knn_metric:\n knn = KNeighborsClassifier(metric=knn_metric)\n else:\n knn = KNeighborsClassifier()\n knn.fit(pred_train, y_train)\n\n results = []\n\n n_test = pred_test.shape[0]\n for i_test in range(n_test):\n results_test = []\n pred = pred_test[i_test]\n y_0 = y_test[i_test]\n # returns sorted indexes, from closest to farthest\n n_indexes = knn.kneighbors([pred], n_neighbors=n_train_samples, return_distance=False)\n # reverse - from farthest to closest\n n_indexes = n_indexes.reshape(-1)[::-1]\n sorted_y_train = y_train[n_indexes]\n sorted_indexes = np.argsort(n_indexes)\n # compute partial contribution incrementally\n first = True\n phi_y_prev: float = 0.0\n y_indicator_prev = 0\n for i_train in range(sorted_y_train.shape[0]):\n y = sorted_y_train[i_train]\n y_indicator = 1 if np.all(y == y_0) else 0\n if first:\n phi_y = y_indicator / n_train_samples\n first = False\n else:\n phi_y = phi_y_prev + ((y_indicator - y_indicator_prev) / (n_train_samples - i_train))\n results_test.append(phi_y)\n phi_y_prev = phi_y\n y_indicator_prev = y_indicator\n # return to original order of training samples\n results_test_sorted = np.array(results_test)[sorted_indexes]\n results.append(results_test_sorted.tolist())\n\n # need to sum across test samples (outer list) for each train sample (inner list)\n per_sample = list(map(list, zip(*results)))\n # normalize so it's comparable across different sizes of train and test datasets\n sum_per_sample = np.array([sum(val) for val in per_sample], dtype=np.float32) * n_train_samples / n_test\n\n return sum_per_sample\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/metrics/privacy/worst_case_mia_score.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements a metric for inference attack worst case accuracy measurement.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\n\n\nimport numpy as np\nfrom sklearn.metrics import roc_curve\n\n\nTPR = float # True Positive Rate\nFPR = float # False Positive Rate\nTHR = float # Threshold of the binary decision\n\n\ndef _calculate_roc_for_fpr(y_true: np.ndarray, y_proba: np.ndarray, targeted_fpr: float) -> tuple[FPR, TPR, THR]:\n \"\"\"\n Get FPR, TPR and, THRESHOLD based on the targeted_fpr (such that FPR <= targeted_fpr)\n :param y_true: True attack labels.\n :param y_proba: Predicted attack probabilities.\n :param targeted_fpr: the targeted False Positive Rate, ROC will be calculated based on this FPR.\n :return: Tuple that contains (Achieved FPR, TPR, Threshold).\n \"\"\"\n\n fpr, tpr, thr = roc_curve(y_true=y_true, y_score=y_proba)\n # take the highest fpr and an appropriated threshold that achieve at least FPR=fpr\n if np.isnan(fpr).all() or np.isnan(tpr).all():\n logging.error(\"TPR or FPR values are NaN\")\n raise ValueError(\"The targeted FPR can't be achieved.\")\n\n targeted_fpr_idx = np.where(fpr <= targeted_fpr)[0][-1]\n return fpr[targeted_fpr_idx], tpr[targeted_fpr_idx], thr[targeted_fpr_idx]\n\n\ndef get_roc_for_fpr(\n attack_proba: np.ndarray,\n attack_true: np.ndarray,\n target_model_labels: np.ndarray | None = None,\n targeted_fpr: float = 0.001,\n) -> list[tuple[FPR, TPR, THR]] | list[tuple[int, FPR, TPR, THR]]:\n \"\"\"\n Compute the attack TPR, THRESHOLD and achieved FPR based on the targeted FPR. This implementation supports only\n binary attack prediction labels {0,1}. The returned THRESHOLD defines the decision threshold on the attack\n probabilities (meaning if p < THRESHOLD predict 0, otherwise predict 1)\n | Related paper link: https://arxiv.org/abs/2112.03570\n\n :param attack_proba: Predicted attack probabilities.\n :param attack_true: True attack labels.\n :param targeted_fpr: the targeted False Positive Rate, attack accuracy will be calculated based on this FPRs.\n If not supplied, get_roc_for_fpr will be computed for `0.001` FPR.\n :param target_model_labels: Original labels, if provided the Accuracy and threshold will be calculated per each\n class separately.\n :return: list of tuples the contains (original label (if target_model_labels is provided),\n Achieved FPR, TPR, Threshold).\n \"\"\"\n\n if attack_proba.shape[0] != attack_true.shape[0]:\n raise ValueError(\"Number of rows in attack_pred and attack_true do not match\")\n if target_model_labels is not None and attack_proba.shape[0] != target_model_labels.shape[0]:\n raise ValueError(\"Number of rows in target_model_labels and attack_pred do not match\")\n\n results = []\n\n if target_model_labels is not None:\n values, _ = np.unique(target_model_labels, return_counts=True)\n for value in values:\n idxs = np.where(target_model_labels == value)[0]\n fpr, tpr, thr = _calculate_roc_for_fpr(\n y_proba=attack_proba[idxs], y_true=attack_true[idxs], targeted_fpr=targeted_fpr\n )\n results.append((value, fpr, tpr, thr))\n return results\n\n fpr, tpr, thr = _calculate_roc_for_fpr(y_proba=attack_proba, y_true=attack_true, targeted_fpr=targeted_fpr)\n return [(fpr, tpr, thr)]\n\n\ndef get_roc_for_multi_fprs(\n attack_proba: np.ndarray,\n attack_true: np.ndarray,\n targeted_fprs: np.ndarray,\n) -> tuple[list[FPR], list[TPR], list[THR]]:\n \"\"\"\n Compute the attack ROC based on the targeted FPRs. This implementation supports only binary\n attack prediction labels. The returned list of THRESHOLDs defines the decision threshold on the attack\n probabilities (meaning if p < THRESHOLD predict 0, otherwise predict 1) for each provided fpr\n\n | Related paper link: https://arxiv.org/abs/2112.03570\n\n :param attack_proba: Predicted attack probabilities.\n :param attack_true: True attack labels.\n :param targeted_fprs: the set of targeted FPR (False Positive Rates), attack accuracy will be calculated based on\n these FPRs.\n :return: list of tuples that (TPR, Threshold, Achieved FPR).\n \"\"\"\n\n if attack_proba.shape[0] != attack_true.shape[0]:\n raise ValueError(\"Number of rows in attack_pred and attack_true do not match\")\n\n tpr = []\n thr = []\n fpr = []\n\n for t_fpr in targeted_fprs:\n res = _calculate_roc_for_fpr(y_proba=attack_proba, y_true=attack_true, targeted_fpr=t_fpr)\n\n fpr.append(res[0])\n tpr.append(res[1])\n thr.append(res[2])\n\n return fpr, tpr, thr\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule for preprocessing operations.\n\"\"\"\n\nfrom art.preprocessing.preprocessing import Preprocessor\nfrom art.preprocessing.preprocessing import PreprocessorPyTorch\nfrom art.preprocessing.preprocessing import PreprocessorTensorFlowV2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/preprocessing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module contains the Preprocessor API.\n\"\"\"\n# pylint: disable=unused-import\nfrom art.defences.preprocessor.preprocessor import Preprocessor\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\nfrom art.defences.preprocessor.preprocessor import PreprocessorTensorFlowV2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/audio/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains audio preprocessing tools.\n\"\"\"\n\nfrom art.preprocessing.audio.l_filter.numpy import LFilter\nfrom art.preprocessing.audio.l_filter.pytorch import LFilterPyTorch\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/audio/l_filter/numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the filter function for audio signals. It provides with an infinite impulse response (IIR) or\nfinite impulse response (FIR) filter. This implementation is a wrapper around the `scipy.signal.lfilter` function in\nthe `scipy` package.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom scipy.signal import lfilter\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass LFilter(Preprocessor):\n \"\"\"\n This module implements the filter function for audio signals. It provides with an infinite impulse response (IIR)\n or finite impulse response (FIR) filter. This implementation is a wrapper around the `scipy.signal.lfilter`\n function in the `scipy` package.\n \"\"\"\n\n params = [\"numerator_coef\", \"denominator_coef\", \"axis\", \"initial_cond\", \"verbose\"]\n\n def __init__(\n self,\n numerator_coef: np.ndarray = np.array([1.0]),\n denominator_coef: np.ndarray = np.array([1.0]),\n axis: int = -1,\n initial_cond: np.ndarray | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = False,\n apply_predict: bool = True,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of LFilter.\n\n :param numerator_coef: The numerator coefficient vector in a 1-D sequence.\n :param denominator_coef: The denominator coefficient vector in a 1-D sequence. By simply setting the array of\n denominator coefficients to np.array([1.0]), this preprocessor can be used to apply a\n FIR filter.\n :param axis: The axis of the input data array along which to apply the linear filter. The filter is applied to\n each subarray along this axis.\n :param initial_cond: Initial conditions for the filter delays.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n\n self.numerator_coef = numerator_coef\n self.denominator_coef = denominator_coef\n self.axis = axis\n self.initial_cond = initial_cond\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply filter to sample `x`.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Similar samples.\n \"\"\"\n x_preprocess = x.copy()\n\n # Filter one input at a time\n for i, x_preprocess_i in enumerate(tqdm(x_preprocess, desc=\"Apply audio filter\", disable=not self.verbose)):\n x_preprocess[i] = lfilter(\n b=self.numerator_coef, a=self.denominator_coef, x=x_preprocess_i, axis=self.axis, zi=self.initial_cond\n )\n\n if self.clip_values is not None:\n np.clip(x_preprocess, self.clip_values[0], self.clip_values[1], out=x_preprocess)\n\n return x_preprocess, y\n\n def estimate_gradient(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Provide an estimate of the gradients of the defence for the backward pass.\n\n :param x: Input data for which the gradient is estimated. First dimension is the batch size.\n :param grad: Gradient value so far.\n :return: The gradient (estimate) of the defence.\n \"\"\"\n if (grad.shape != x.shape) and ( # pragma: no cover\n (len(grad.shape) != len(x.shape) + 1) or (grad.shape[2:] != x.shape[1:]) or (grad.shape[0] != x.shape[0])\n ):\n raise ValueError(f\"The shape of `grad` {grad.shape} does not match the shape of input `x` {x.shape}\")\n\n if self.denominator_coef[0] != 1.0 or np.sum(self.denominator_coef) != 1.0:\n logger.warning(\n \"Accurate gradient estimation is currently only implemented for finite impulse response filtering, \"\n \"the coefficients indicate infinite response filtering, therefore Backward Pass Differentiable \"\n \"Approximation (BPDA) is applied instead.\"\n )\n return grad\n\n # We will compute gradient for one sample at a time\n x_grad_list = []\n\n for i, x_i in enumerate(x):\n # First compute the gradient matrix\n grad_matrix = self._compute_gradient_matrix(size=x_i.size)\n\n # Then combine with the input gradient\n if grad.shape == x.shape:\n grad_x_i = np.zeros(x_i.size)\n for j in range(x_i.size):\n grad_x_i[j] = np.sum(grad[i] * grad_matrix[:, j])\n\n else:\n grad_x_i = np.zeros_like(grad[i])\n for j in range(x_i.size):\n grad_x_i[:, j] = np.sum(grad[i, :, :] * grad_matrix[:, j], axis=1)\n\n # And store the result\n x_grad_list.append(grad_x_i)\n\n if x.dtype == object:\n x_grad = np.empty(x.shape[0], dtype=object)\n x_grad[:] = list(x_grad_list)\n\n else:\n x_grad = np.array(x_grad_list)\n\n return x_grad\n\n def _compute_gradient_matrix(self, size: int) -> np.ndarray:\n \"\"\"\n Compute the gradient of the FIR output with respect to the FIR input. The gradient computation result is stored\n as a matrix.\n\n :param size: The size of the FIR input or output.\n :return: A gradient matrix.\n \"\"\"\n # Initialize gradients redundantly\n grad_matrix = np.zeros(shape=(size, size + self.numerator_coef.size - 1))\n\n # Compute gradients\n flipped_numerator_coef = np.flip(self.numerator_coef)\n for i in range(size):\n grad_matrix[i, i : i + self.numerator_coef.size] = flipped_numerator_coef\n\n # Remove temporary gradients\n grad_matrix = grad_matrix[:, self.numerator_coef.size - 1 :]\n\n return grad_matrix\n\n def _check_params(self) -> None:\n if not isinstance(self.denominator_coef, np.ndarray) or self.denominator_coef[0] == 0:\n raise ValueError(\"The first element of the denominator coefficient vector must be non zero.\")\n\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n if not isinstance(self.numerator_coef, np.ndarray):\n raise ValueError(\"The numerator coefficient vector has to be of type `np.ndarray`.\")\n\n if not isinstance(self.axis, int):\n raise ValueError(\"The axis of the input data array has to be of type `int`.\")\n\n if self.initial_cond is not None and not isinstance(self.initial_cond, np.ndarray):\n raise ValueError(\"The initial conditions for the filter delays must be of type `np.ndarray`.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/audio/l_filter/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the filter function for audio signals in PyTorch. It provides with an infinite impulse response\n(IIR) or finite impulse response (FIR) filter. This implementation is a wrapper around the\n`torchaudio.functional.lfilter` function in the `torchaudio` package.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals, annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass LFilterPyTorch(PreprocessorPyTorch):\n \"\"\"\n This module implements the filter function for audio signals in PyTorch. It provides with an infinite impulse\n response (IIR) or finite impulse response (FIR) filter. This implementation is a wrapper around the\n `torchaudio.functional.lfilter` function in the `torchaudio` package.\n \"\"\"\n\n params = [\"numerator_coef\", \"denominator_coef\", \"verbose\"]\n\n def __init__(\n self,\n numerator_coef: np.ndarray = np.array([1.0]),\n denominator_coef: np.ndarray = np.array([1.0]),\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = False,\n apply_predict: bool = True,\n verbose: bool = False,\n device_type: str = \"gpu\",\n ) -> None:\n \"\"\"\n Create an instance of LFilterPyTorch.\n\n :param numerator_coef: The numerator coefficient vector in a 1-D sequence.\n :param denominator_coef: The denominator coefficient vector in a 1-D sequence. By simply setting the array of\n denominator coefficients to np.array([1.0]), this preprocessor can be used to apply a\n FIR filter.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n :param device_type: Type of device on which the classifier is run, either `gpu` or `cpu`.\n \"\"\"\n\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n\n self.numerator_coef = numerator_coef\n self.denominator_coef = denominator_coef\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply filter to a single sample `x`.\n\n :param x: A single audio sample.\n :param y: Label of the sample `x`. This function does not affect them in any way.\n :return: Similar sample.\n \"\"\"\n import torch\n import torchaudio\n\n if int(torchaudio.__version__.split(\".\")[1]) > 5:\n x_preprocess = torchaudio.functional.lfilter(\n b_coeffs=torch.tensor(self.numerator_coef, device=self._device, dtype=x.dtype),\n a_coeffs=torch.tensor(self.denominator_coef, device=self._device, dtype=x.dtype),\n waveform=x,\n clamp=False,\n )\n else:\n x_preprocess = torchaudio.functional.lfilter(\n b_coeffs=torch.tensor(self.numerator_coef, device=self._device, dtype=x.dtype),\n a_coeffs=torch.tensor(self.denominator_coef, device=self._device, dtype=x.dtype),\n waveform=x,\n )\n\n if self.clip_values is not None:\n x_preprocess = x_preprocess.clamp(min=self.clip_values[0], max=self.clip_values[1])\n\n return x_preprocess, y\n\n def __call__(self, x: np.ndarray, y: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply filter to sample `x`.\n\n :param x: Samples of shape (nb_samples, seq_length). Note that, it is allowable that sequences in the batch\n could have different lengths. A possible example of `x` could be:\n `x = np.array([np.array([0.1, 0.2, 0.1, 0.4]), np.array([0.3, 0.1])])`.\n :param y: Labels of the sample `x`. This function does not affect them in any way.\n :return: Similar samples.\n \"\"\"\n import torch\n\n x_preprocess = x.copy()\n\n # Filter one input at a time\n for i, x_preprocess_i in enumerate(tqdm(x_preprocess, desc=\"Apply audio filter\", disable=not self.verbose)):\n if np.min(x_preprocess_i) < -1.0 or np.max(x_preprocess_i) > 1.0: # pragma: no cover\n raise ValueError(\n \"Audio signals must be normalized to the range `[-1.0, 1.0]` to apply the audio filter function.\"\n )\n\n x_preprocess_i = torch.tensor(x_preprocess_i, device=self._device)\n\n with torch.no_grad():\n x_preprocess_i, _ = self.forward(x_preprocess_i)\n\n x_preprocess[i] = x_preprocess_i.cpu().numpy()\n\n return x_preprocess, y\n\n def _check_params(self) -> None:\n if not isinstance(self.denominator_coef, np.ndarray) or self.denominator_coef[0] == 0:\n raise ValueError(\"The first element of the denominator coefficient vector must be non zero.\")\n\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if np.array(self.clip_values[0] >= self.clip_values[1]).any():\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n if not isinstance(self.numerator_coef, np.ndarray):\n raise ValueError(\"The numerator coefficient vector has to be of type `np.ndarray`.\")\n\n if not isinstance(self.verbose, bool):\n raise ValueError(\"The argument `verbose` has to be of type bool.\")\n\n if len(self.denominator_coef) != len(self.numerator_coef):\n raise ValueError(\n \"The denominator coefficient vector and the numerator coefficient vector must have the same length.\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nModule providing expectation over transformations.\n\"\"\"\n\nfrom art.preprocessing.expectation_over_transformation.image_center_crop.pytorch import EoTImageCenterCropPyTorch\nfrom art.preprocessing.expectation_over_transformation.image_rotation.tensorflow import EoTImageRotationTensorFlow\nfrom art.preprocessing.expectation_over_transformation.image_rotation.pytorch import EoTImageRotationPyTorch\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.brightness.pytorch import (\n EoTBrightnessPyTorch,\n)\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.brightness.tensorflow import (\n EoTBrightnessTensorFlow,\n)\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.contrast.pytorch import EoTContrastPyTorch\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.contrast.tensorflow import (\n EoTContrastTensorFlow,\n)\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.gaussian_noise.pytorch import (\n EoTGaussianNoisePyTorch,\n)\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.gaussian_noise.tensorflow import (\n EoTGaussianNoiseTensorFlow,\n)\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.shot_noise.pytorch import EoTShotNoisePyTorch\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.shot_noise.tensorflow import (\n EoTShotNoiseTensorFlow,\n)\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.zoom_blur.pytorch import EoTZoomBlurPyTorch\nfrom art.preprocessing.expectation_over_transformation.natural_corruptions.zoom_blur.tensorflow import (\n EoTZoomBlurTensorFlow,\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module defines a base class for EoT in PyTorch.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom art.preprocessing.preprocessing import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTPyTorch(PreprocessorPyTorch):\n \"\"\"\n This module defines a base class for EoT in PyTorch.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n\n self.nb_samples = nb_samples\n self.clip_values = clip_values\n EoTPyTorch._check_params(self)\n\n @abstractmethod\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Internal method implementing the transformation per input sample.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n raise NotImplementedError\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Apply transformations to inputs `x` and labels `y`.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n x_preprocess_list = []\n y_preprocess_list_classification: list[torch.Tensor] = []\n y_preprocess_list_object_detection: list[list[dict[str, torch.Tensor]]] = []\n\n for i_image in range(x.shape[0]):\n for _ in range(self.nb_samples):\n x_i = x[[i_image]]\n y_i: torch.Tensor | list[dict[str, torch.Tensor]] | None\n if y is not None:\n if isinstance(y, list):\n y_i = [y[i_image]]\n else:\n y_i = y[[i_image]]\n else:\n y_i = None\n x_preprocess, y_preprocess_i = self._transform(x_i, y_i)\n x_preprocess_list.append(torch.squeeze(x_preprocess, dim=0))\n\n if y is not None and y_preprocess_i is not None:\n if isinstance(y_preprocess_i, torch.Tensor):\n y_preprocess_list_classification.append(torch.squeeze(y_preprocess_i, dim=0))\n else:\n y_preprocess_list_object_detection.append(y_preprocess_i)\n\n x_preprocess = torch.stack(x_preprocess_list, dim=0)\n y_preprocess: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None\n if y is None:\n y_preprocess = y\n else:\n if isinstance(y, torch.Tensor):\n y_preprocess = torch.stack(y_preprocess_list_classification, dim=0)\n else:\n y_preprocess = [item for sublist in y_preprocess_list_object_detection for item in sublist]\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n\n if not isinstance(self.nb_samples, int) or self.nb_samples < 1:\n raise ValueError(\"The number of samples needs to be an integer greater than or equal to 1.\")\n\n if not isinstance(self.clip_values, tuple) or (\n len(self.clip_values) != 2\n or not isinstance(self.clip_values[0], (int, float))\n or not isinstance(self.clip_values[1], (int, float))\n or self.clip_values[0] > self.clip_values[1]\n ):\n raise ValueError(\"The argument `clip_Values` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module defines a base class for EoT in TensorFlow v2.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.preprocessing import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n This module defines a base class for EoT in TensorFlow v2.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTTensorFlowV2.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n\n self.nb_samples = nb_samples\n self.clip_values = clip_values\n EoTTensorFlowV2._check_params(self)\n\n @abstractmethod\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Internal method implementing the transformation per input sample.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n raise NotImplementedError\n\n def forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Apply transformations to inputs `x` and labels `y`.\n\n :param x: Input samples.\n :param y: Label of the sample `x`. This function does not modify `y`.\n :return: Corrupted samples and labels.\n \"\"\"\n import tensorflow as tf\n\n x_preprocess_list = []\n y_preprocess_list = []\n\n for i_image in range(x.shape[0]):\n for _ in range(self.nb_samples):\n x_i = x[[i_image]]\n y_i: tf.Tensor | list[dict[str, tf.Tensor]] | None\n if y is not None:\n if isinstance(y, list):\n y_i = [y[i_image]]\n else:\n y_i = y[[i_image]]\n else:\n y_i = None\n x_preprocess, y_preprocess_i = self._transform(x_i, y_i)\n x_preprocess_list.append(tf.squeeze(x_preprocess, axis=0))\n\n if y is not None and y_preprocess_i is not None:\n y_preprocess_list.append(y_preprocess_i)\n\n x_preprocess = tf.stack(x_preprocess_list, axis=0)\n if y is None:\n y_preprocess = y\n else:\n if isinstance(y, (tf.Tensor, np.ndarray)):\n y_preprocess = tf.stack(y_preprocess_list, axis=0)\n else:\n y_preprocess = [item for sublist in y_preprocess_list for item in sublist]\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n\n if not isinstance(self.nb_samples, int) or self.nb_samples < 1:\n raise ValueError(\"The number of samples needs to be an integer greater than or equal to 1.\")\n\n if not isinstance(self.clip_values, tuple) or (\n len(self.clip_values) != 2\n or not isinstance(self.clip_values[0], (int, float))\n or not isinstance(self.clip_values[1], (int, float))\n or self.clip_values[0] > self.clip_values[1]\n ):\n raise ValueError(\"The argument `clip_Values` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/image_center_crop/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Expectation over Transformation preprocessing for image center crop in PyTorch.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTImageCenterCropPyTorch(EoTPyTorch):\n \"\"\"\n This module implements Expectation over Transformation preprocessing for image center crop in PyTorch.\n \"\"\"\n\n params = [\"nb_samples\", \"angles\", \"clip_values\", \"label_type\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n size: int = 5,\n label_type: str = \"classification\",\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTImageCenterCropPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param size: Maximal size of the crop on all sides of the image in pixels.\n :param label_type: String defining the type of labels. Currently supported: `classification`, `object_detection`\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.size = size\n self.size_range = (0, size)\n self.label_type = label_type\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Center crop an input image and its labels by randomly sampled crop size.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n import torchvision\n\n size = np.random.randint(low=self.size_range[0], high=self.size_range[1])\n\n # Ensure channels-first\n channels_first = True\n if x.shape[-1] in [1, 3]:\n x = torch.permute(x, (0, 3, 1, 2))\n channels_first = False\n\n x_preprocess = torchvision.transforms.functional.resized_crop(\n img=x,\n top=size,\n left=size,\n height=x.shape[-2] - 2 * size,\n width=x.shape[-1] - 2 * size,\n size=x.shape[-2:-1],\n interpolation=torchvision.transforms.functional.InterpolationMode.NEAREST,\n )\n\n x_preprocess = torch.clamp(\n input=x_preprocess,\n min=-self.clip_values[0],\n max=self.clip_values[1],\n )\n\n y_preprocess: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None\n\n if self.label_type == \"object_detection\" and y is not None:\n\n y_od: list[dict[str, \"torch.Tensor\"]] = [{}]\n\n if isinstance(y, list):\n if isinstance(y[0], dict):\n y_od[0][\"boxes\"] = torch.clone(y[0][\"boxes\"])\n y_od[0][\"labels\"] = torch.clone(y[0][\"labels\"])\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n ratio_h = x.shape[-2] / (x.shape[-2] - 2 * size)\n ratio_w = x.shape[-1] / (x.shape[-1] - 2 * size)\n\n # top-left corner\n\n y_od[0][\"boxes\"][:, 0] -= size\n y_od[0][\"boxes\"][:, 1] -= size\n\n y_od[0][\"boxes\"][:, 0] = y_od[0][\"boxes\"][:, 0] * ratio_h\n y_od[0][\"boxes\"][:, 1] = y_od[0][\"boxes\"][:, 1] * ratio_w\n\n y_od[0][\"boxes\"][:, 0] = torch.maximum(torch.tensor(0), y_od[0][\"boxes\"][:, 0]).int()\n y_od[0][\"boxes\"][:, 1] = torch.maximum(torch.tensor(0), y_od[0][\"boxes\"][:, 1]).int()\n\n # bottom-right corner\n\n y_od[0][\"boxes\"][:, 2] -= size\n y_od[0][\"boxes\"][:, 3] -= size\n\n y_od[0][\"boxes\"][:, 2] = y_od[0][\"boxes\"][:, 2] * ratio_h\n y_od[0][\"boxes\"][:, 3] = y_od[0][\"boxes\"][:, 3] * ratio_w\n\n y_od[0][\"boxes\"][:, 2] = torch.minimum(y_od[0][\"boxes\"][:, 2], torch.tensor(x.shape[-2])).int()\n y_od[0][\"boxes\"][:, 3] = torch.minimum(y_od[0][\"boxes\"][:, 3], torch.tensor(x.shape[-1])).int()\n\n y_preprocess = y_od\n\n else:\n\n y_preprocess = y\n\n if not channels_first:\n x_preprocess = torch.permute(x_preprocess, (0, 2, 3, 1))\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n\n if not isinstance(self.size, int) or self.size <= 0:\n raise ValueError(\"The size be a positive integer.\")\n\n if self.label_type not in self.label_types:\n raise ValueError(\n f\"The input for label_type needs to be one of {self.label_types},\"\n f\"currently receiving `{self.label_type}`.\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/image_rotation/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Expectation over Transformation preprocessing for image rotation in PyTorch.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTImageRotationPyTorch(EoTPyTorch):\n \"\"\"\n This module implements Expectation over Transformation preprocessing for image rotation in PyTorch.\n \"\"\"\n\n params = [\"nb_samples\", \"angles\", \"clip_values\", \"label_type\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n angles: float | tuple[float, float] | list[float] = 45.0,\n label_type: str = \"classification\",\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTImageRotationPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param angles: In degrees and counter-clockwise. If a positive scalar it defines the uniform sampling range from\n negative to positive value. If a tuple of two scalar angles it defines the uniform sampling\n range from minimum to maximum angles. If a list of scalar values it defines the discrete angles\n that will be sampled. For `label_type=\"object_detection\"` only a list of multiples of 90 degrees\n is supported.\n :param label_type: String defining the type of labels. Currently supported: `classification`, `object_detection`\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.angles = angles\n self.angles_range = (-angles, angles) if isinstance(angles, (int, float)) else angles\n self.label_type = label_type\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Transformation of an input image and its label by randomly sampled rotation.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n import torchvision\n\n if isinstance(self.angles, list):\n angles = np.random.choice(self.angles).item()\n else:\n angles = np.random.uniform(low=self.angles_range[0], high=self.angles_range[1])\n\n # Ensure channels-first\n channels_first = True\n if x.shape[-1] in [1, 3]:\n x = torch.permute(x, (0, 3, 1, 2))\n channels_first = False\n\n expand = self.label_type == \"object_detection\"\n\n x_preprocess = torchvision.transforms.functional.rotate(\n img=x,\n angle=angles,\n interpolation=torchvision.transforms.functional.InterpolationMode.NEAREST,\n expand=expand,\n )\n\n x_preprocess = torch.clamp(\n input=x_preprocess,\n min=-self.clip_values[0],\n max=self.clip_values[1],\n )\n\n y_preprocess: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None\n\n if self.label_type == \"object_detection\" and y is not None:\n\n y_od: list[dict[str, \"torch.Tensor\"]] = [{}]\n\n if isinstance(y, list):\n if isinstance(y[0], dict):\n y_od[0][\"boxes\"] = torch.clone(y[0][\"boxes\"])\n y_od[0][\"labels\"] = torch.clone(y[0][\"labels\"])\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n y_b = y[0][\"boxes\"]\n image_width = x.shape[2]\n image_height = x.shape[1]\n x_1_arr = y_b[:, 0]\n y_1_arr = y_b[:, 1]\n x_2_arr = y_b[:, 2]\n y_2_arr = y_b[:, 3]\n box_width = x_2_arr - x_1_arr\n box_height = y_2_arr - y_1_arr\n\n if angles == 0:\n x_1_new = x_1_arr\n y_1_new = y_1_arr\n x_2_new = x_2_arr\n y_2_new = y_2_arr\n\n elif angles == 90:\n x_1_new = y_1_arr\n y_1_new = image_width - x_1_arr - box_width\n x_2_new = y_1_arr + box_height\n y_2_new = image_width - x_1_arr\n\n elif angles == 180:\n x_1_new = image_width - x_2_arr\n y_1_new = image_height - y_2_arr\n x_2_new = x_1_new + box_width\n y_2_new = y_1_new + box_height\n\n elif angles == 270:\n x_1_new = image_height - y_1_arr - box_height\n y_1_new = x_1_arr\n x_2_new = image_height - y_1_arr\n y_2_new = x_1_arr + box_width\n\n else:\n raise ValueError(\"The angle is not supported for object detection.\")\n\n y_od[0][\"boxes\"][:, 0] = x_1_new\n y_od[0][\"boxes\"][:, 1] = y_1_new\n y_od[0][\"boxes\"][:, 2] = x_2_new\n y_od[0][\"boxes\"][:, 3] = y_2_new\n\n y_preprocess = y_od\n\n else:\n\n y_preprocess = y\n\n if not channels_first:\n x_preprocess = torch.permute(x_preprocess, (0, 2, 3, 1))\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if (\n self.label_type == \"classification\"\n and not isinstance(self.angles, (int, float, tuple, list))\n or (\n isinstance(self.angles, tuple)\n and (\n len(self.angles) != 2\n or not isinstance(self.angles[0], (int, float))\n or not isinstance(self.angles[1], (int, float))\n or self.angles[0] > self.angles[1]\n )\n )\n ):\n raise ValueError(\"The range of angles must be a float in the range (0.0, 180.0].\")\n\n if self.label_type not in self.label_types:\n raise ValueError(\n f\"The input for label_type needs to be one of {self.label_types},\"\n f\"currently receiving `{self.label_type}`.\"\n )\n\n if self.label_type == \"object_detection\":\n if not isinstance(self.angles, list):\n raise ValueError(\n \"\"\"For `label_type=\"object_detection\"` only a list of multiples of 90 degrees is supported.\"\"\"\n )\n if isinstance(self.angles, list):\n for angle in self.angles:\n if divmod(angle, 90)[1] != 0:\n raise ValueError(\n \"\"\"For `label_type=\"object_detection\"` only a list of multiples of 90 degrees is\n supported.\"\"\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/image_rotation/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements Expectation over Transformation preprocessing for image rotation in TensorFlow.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.tensorflow import EoTTensorFlowV2\n\nif TYPE_CHECKING:\n\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTImageRotationTensorFlow(EoTTensorFlowV2):\n \"\"\"\n This module implements Expectation over Transformation preprocessing for image rotation in TensorFlow.\n \"\"\"\n\n params = [\"nb_samples\", \"angles\", \"clip_values\", \"label_type\"]\n\n label_types = [\"classification\"]\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n angles: float | tuple[float, float] = 45.0,\n label_type: str = \"classification\",\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTImageRotationTensorFlow.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param angles: A positive scalar angle in degrees defining the uniform sampling range from negative to\n positive angles_range.\n :param label_type: String defining the type of labels. Currently supported: `classification`\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.angles = angles\n self.angles_range = (-angles, angles) if isinstance(angles, (int, float)) else angles\n self.label_type = label_type\n self._check_params()\n\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Transformation of an input image and its label by randomly sampled rotation.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n angles = tf.random.uniform(shape=(), minval=self.angles_range[0], maxval=self.angles_range[1])\n angles = angles / 360.0 * 2.0 * np.pi\n x_preprocess = rotate_images(images=x, angles=angles, interpolation=\"NEAREST\")\n x_preprocess = tf.clip_by_value(\n t=x_preprocess, clip_value_min=-self.clip_values[0], clip_value_max=self.clip_values[1], name=None\n )\n return x_preprocess, y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.angles, (int, float, tuple)) or (\n isinstance(self.angles, tuple)\n and (\n len(self.angles) != 2\n or not isinstance(self.angles[0], (int, float))\n or not isinstance(self.angles[1], (int, float))\n or self.angles[0] > self.angles[1]\n )\n ):\n raise ValueError(\"The range of angles must be a float in the range (0.0, 180.0].\")\n\n if self.label_type not in self.label_types:\n raise ValueError(\n f\"The input for label_type needs to be one of {self.label_types}, currently receiving \"\n f\"`{self.label_type}`.\"\n )\n\n\ndef rotate_images(images, angles, interpolation=\"NEAREST\"):\n \"\"\"\n Transformation of input images by a specified rotation angle.\n\n :param images: Input samples, a 4D tensor of shape `(batch_size, height, width, channels)`.\n :param angles: Rotation angles in radians for each image in the batch, a 1D tensor of shape `(batch_size,)`.\n :param interpolation: Interpolation method to use for rotating images. Can be `\"NEAREST\"` or `\"BILINEAR\"`.\n :return: Rotated images as a 4D tensor of the same shape as `images`.\n \"\"\"\n import tensorflow as tf\n\n # Ensure batch dimensions\n if tf.rank(angles) == 0:\n angles = tf.expand_dims(angles, 0)\n if tf.rank(images) == 3:\n images = tf.expand_dims(images, 0)\n\n height = tf.cast(tf.shape(images)[1], tf.float32)\n width = tf.cast(tf.shape(images)[2], tf.float32)\n\n cx = (width - 1) / 2.0\n cy = (height - 1) / 2.0\n\n cos_angles = tf.math.cos(angles)\n sin_angles = tf.math.sin(angles)\n\n tx = cx - (cx * cos_angles) + (cy * sin_angles)\n ty = cy - (cx * sin_angles) - (cy * cos_angles)\n\n transforms = tf.stack(\n [cos_angles, -sin_angles, tx, sin_angles, cos_angles, ty, tf.zeros_like(angles), tf.zeros_like(angles)], axis=1\n )\n\n rotated = tf.raw_ops.ImageProjectiveTransformV3(\n images=images,\n transforms=transforms,\n interpolation=interpolation,\n output_shape=tf.shape(images)[1:3],\n fill_mode=\"CONSTANT\",\n fill_value=0.0,\n )\n\n return rotated\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/brightness/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of changes in brightness by addition of uniformly sampled delta.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTBrightnessPyTorch(EoTPyTorch):\n \"\"\"\n This module implements EoT of changes in brightness by addition of uniformly sampled delta.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n delta: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTBrightnessPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param delta: Range to sample the delta (addition) to the pixel values to adjust the brightness. A single float\n is translated to range [-delta, delta] or a tuple of floats is used to create sampling range\n [delta[0], delta[1]]. The applied delta is sampled uniformly from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.delta = delta\n self.delta_range = (-delta, delta) if isinstance(delta, (int, float)) else delta\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Transformation of an image with randomly sampled brightness.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n delta_i = np.random.uniform(low=self.delta_range[0], high=self.delta_range[1])\n return torch.clamp(x + delta_i, min=self.clip_values[0], max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.delta, (int, float, tuple)) or (\n isinstance(self.delta, tuple)\n and (\n len(self.delta) != 2\n or not isinstance(self.delta[0], (int, float))\n or not isinstance(self.delta[1], (int, float))\n or self.delta[0] > self.delta[1]\n )\n ):\n raise ValueError(\"The argument `delta` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/brightness/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of changes in brightness by addition of uniformly sampled delta.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.tensorflow import EoTTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTBrightnessTensorFlow(EoTTensorFlowV2):\n \"\"\"\n This module implements EoT of changes in brightness by addition of uniformly sampled delta.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n delta: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTBrightnessTensorFlow.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param delta: Range to sample the delta (addition) to the pixel values to adjust the brightness. A single float\n is translated to range [-delta, delta] or a tuple of floats is used to create sampling range\n [delta[0], delta[1]]. The applied delta is sampled uniformly from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.delta = delta\n self.delta_range = (-delta, delta) if isinstance(delta, (int, float)) else delta\n self._check_params()\n\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Transformation of an image with randomly sampled brightness.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n delta_i = np.random.uniform(low=self.delta_range[0], high=self.delta_range[1])\n return tf.clip_by_value(x + delta_i, clip_value_min=self.clip_values[0], clip_value_max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.delta, (int, float, tuple)) or (\n isinstance(self.delta, tuple)\n and (\n len(self.delta) != 2\n or not isinstance(self.delta[0], (int, float))\n or not isinstance(self.delta[1], (int, float))\n or self.delta[0] > self.delta[1]\n )\n ):\n raise ValueError(\"The argument `delta` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/contrast/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of changes in contrast with uniformly sampled factor.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTContrastPyTorch(EoTPyTorch):\n \"\"\"\n This module implements EoT of changes in contrast with uniformly sampled factor.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n contrast_factor: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTContrastPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param contrast_factor: Range to sample the contrast factor adjust the contrast. A single float is translated to\n range [-delta, delta] or a tuple of floats is used to create sampling range [delta[0], delta[1]]. The\n applied delta is sampled uniformly from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.contrast_factor = contrast_factor\n self.contrast_factor_range = (\n (0, contrast_factor) if isinstance(contrast_factor, (int, float)) else contrast_factor\n )\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Transformation of an image with randomly sampled contrast.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n contrast_factor_i = np.random.uniform(low=self.contrast_factor_range[0], high=self.contrast_factor_range[1])\n if x.shape[3] == 3:\n red, green, blue = x[:, :, :, 0], x[:, :, :, 1], x[:, :, :, 2]\n x_gray = 0.2989 * red + 0.587 * green + 0.114 * blue\n elif x.shape[3] == 1:\n x_gray = x[:, :, :, 0]\n else: # pragma: no cover\n raise ValueError(\"Number of color channels is not 1 or 3 in input `x` of format HWC.\")\n mean = torch.mean(x_gray, dim=(-2, -1), keepdim=True)\n\n return (\n torch.clamp(\n contrast_factor_i * x + (1.0 - contrast_factor_i) * mean,\n min=self.clip_values[0],\n max=self.clip_values[1],\n ),\n y,\n )\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.contrast_factor, (int, float, tuple)) or (\n isinstance(self.contrast_factor, tuple)\n and (\n len(self.contrast_factor) != 2\n or not isinstance(self.contrast_factor[0], (int, float))\n or not isinstance(self.contrast_factor[1], (int, float))\n or self.contrast_factor[0] > self.contrast_factor[1]\n )\n ):\n raise ValueError(\n \"The argument `contrast_factor` has to be a float or tuple of two float values as (min, max).\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/contrast/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of changes in contrast with uniformly sampled factor.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.tensorflow import EoTTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTContrastTensorFlow(EoTTensorFlowV2):\n \"\"\"\n This module implements EoT of changes in contrast with uniformly sampled factor.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n contrast_factor: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTContrastTensorFlow.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param contrast_factor: Range to sample the contrast factor adjust the contrast. A single float is translated to\n range [-delta, delta] or a tuple of floats is used to create sampling range [delta[0], delta[1]]. The\n applied delta is sampled uniformly from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.contrast_factor = contrast_factor\n self.contrast_factor_range = (\n (0, contrast_factor) if isinstance(contrast_factor, (int, float)) else contrast_factor\n )\n self._check_params()\n\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Transformation of an image with randomly sampled contrast.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n contrast_factor_i = np.random.uniform(low=self.contrast_factor_range[0], high=self.contrast_factor_range[1])\n if x.shape[3] == 3:\n red, green, blue = x[:, :, :, 0], x[:, :, :, 1], x[:, :, :, 2]\n x_gray = 0.2989 * red + 0.587 * green + 0.114 * blue\n elif x.shape[3] == 1:\n x_gray = x[:, :, :, 0]\n else: # pragma: no cover\n raise ValueError(\"Number of color channels is not 1 or 3 in input `x` of format HWC.\")\n mean = tf.math.reduce_mean(x_gray, axis=None)\n\n return (\n tf.clip_by_value(\n contrast_factor_i * x + (1.0 - contrast_factor_i) * mean,\n clip_value_min=self.clip_values[0],\n clip_value_max=self.clip_values[1],\n ),\n y,\n )\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.contrast_factor, (int, float, tuple)) or (\n isinstance(self.contrast_factor, tuple)\n and (\n len(self.contrast_factor) != 2\n or not isinstance(self.contrast_factor[0], (int, float))\n or not isinstance(self.contrast_factor[1], (int, float))\n or self.contrast_factor[0] > self.contrast_factor[1]\n )\n ):\n raise ValueError(\n \"The argument `contrast_factor` has to be a float or tuple of two float values as (min, max).\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/gaussian_noise/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of adding Gaussian noise with uniformly sampled standard deviation.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTGaussianNoisePyTorch(EoTPyTorch):\n \"\"\"\n This module implements EoT of adding Gaussian noise with uniformly sampled standard deviation.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n std: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTBrightnessPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param std: Range to sample the standard deviation for the Gaussian distribution. A single float\n is translated to range [0, std]. The applied delta is sampled uniformly from this range for each\n image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.std = std\n self.std_range = (0.0, std) if isinstance(std, (int, float)) else std\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Transformation of an image with randomly sampled Gaussian noise.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n std_i = np.random.uniform(low=self.std_range[0], high=self.std_range[1])\n delta_i = torch.normal(mean=torch.zeros_like(x), std=torch.ones_like(x) * std_i)\n return torch.clamp(x + delta_i, min=self.clip_values[0], max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.std, (int, float, tuple)) or (\n isinstance(self.std, tuple)\n and (\n len(self.std) != 2\n or not isinstance(self.std[0], (int, float))\n or not isinstance(self.std[1], (int, float))\n or self.std[0] > self.std[1]\n or self.std[0] < 0.0\n )\n ):\n raise ValueError(\"The argument `std` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/gaussian_noise/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of adding Gaussian noise with uniformly sampled standard deviation.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.tensorflow import EoTTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTGaussianNoiseTensorFlow(EoTTensorFlowV2):\n \"\"\"\n This module implements EoT of adding Gaussian noise with uniformly sampled standard deviation.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n std: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTGaussianNoiseTensorFlow.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param std: Range to sample the standard deviation for the Gaussian distribution. A single float\n is translated to range [0, std]. The applied delta is sampled uniformly from this range for each\n image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.std = std\n self.std_range = (0.0, std) if isinstance(std, (int, float)) else std\n self._check_params()\n\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Transformation of an image with randomly sampled Gaussian noise.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n std_i = np.random.uniform(low=self.std_range[0], high=self.std_range[1])\n delta_i = tf.random.normal(shape=x.shape, mean=0.0, stddev=std_i, seed=None)\n return tf.clip_by_value(x + delta_i, clip_value_min=self.clip_values[0], clip_value_max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.std, (int, float, tuple)) or (\n isinstance(self.std, tuple)\n and (\n len(self.std) != 2\n or not isinstance(self.std[0], (int, float))\n or not isinstance(self.std[1], (int, float))\n or self.std[0] > self.std[1]\n or self.std[0] < 0.0\n )\n ):\n raise ValueError(\"The argument `std` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/shot_noise/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of adding shot noise (Poisson) with uniformly sampled rate parameter.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTShotNoisePyTorch(EoTPyTorch):\n \"\"\"\n This module implements EoT of adding shot noise (Poisson) with uniformly sampled rate parameter.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n lam: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTShotNoisePyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param lam: Range to sample the rate of the Poisson distribution. A single float\n is translated to range [0.0, lam] or a tuple of floats is used to create sampling range\n [lam[0], lam[1]]. The applied delta is sampled uniformly from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.lam = lam\n self.lam_range = (0.0, lam) if isinstance(lam, (int, float)) else lam\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Transformation of an image with randomly sampled shot (Poisson) noise.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n lam_i = np.random.uniform(low=self.lam_range[0], high=self.lam_range[1])\n delta_i = torch.poisson(input=torch.ones_like(x) * lam_i) / lam_i * self.clip_values[1]\n return torch.clamp(x + delta_i, min=self.clip_values[0], max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.lam, (int, float, tuple)) or (\n isinstance(self.lam, tuple)\n and (\n len(self.lam) != 2\n or not isinstance(self.lam[0], (int, float))\n or not isinstance(self.lam[1], (int, float))\n or self.lam[0] > self.lam[1]\n or self.lam[0] < 0.0\n )\n ):\n raise ValueError(\"The argument `lam` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/shot_noise/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of adding shot noise (Poisson) with uniformly sampled rate parameter.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.tensorflow import EoTTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTShotNoiseTensorFlow(EoTTensorFlowV2):\n \"\"\"\n This module implements EoT of adding shot noise (Poisson) with uniformly sampled rate parameter.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n lam: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTShotNoiseTensorFlow.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param lam: Range to sample the rate of the Poisson distribution. A single float\n is translated to range [0.0, lam] or a tuple of floats is used to create sampling range\n [lam[0], lam[1]]. The applied delta is sampled uniformly from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.lam = lam\n self.lam_range = (0.0, lam) if isinstance(lam, (int, float)) else lam\n self._check_params()\n\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Transformation of an image with randomly sampled shot (Poisson) noise.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n lam_i = np.random.uniform(low=self.lam_range[0], high=self.lam_range[1])\n\n delta_i = tf.random.poisson(shape=x.shape, lam=lam_i, seed=None) / lam_i * self.clip_values[1]\n return tf.clip_by_value(x + delta_i, clip_value_min=self.clip_values[0], clip_value_max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.lam, (int, float, tuple)) or (\n isinstance(self.lam, tuple)\n and (\n len(self.lam) != 2\n or not isinstance(self.lam[0], (int, float))\n or not isinstance(self.lam[1], (int, float))\n or self.lam[0] > self.lam[1]\n or self.lam[0] < 0.0\n )\n ):\n raise ValueError(\"The argument `lam` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/zoom_blur/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of zoom blur with uniformly sampled zoom factor.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.pytorch import EoTPyTorch\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTZoomBlurPyTorch(EoTPyTorch):\n \"\"\"\n This module implements EoT of zoom blur with uniformly sampled zoom factor.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n zoom: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTZoomBlurPyTorch.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param zoom: Range to sample the zoom factor. A single float is translated to range [1.0, zoom] or a tuple of\n floats is used to create sampling range [zoom[0], zoom[1]]. The applied zoom is sampled uniformly\n from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.zoom = zoom\n self.zoom_range = (1.0, zoom) if isinstance(zoom, (int, float)) else zoom\n self._check_params()\n\n def _transform(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None, **kwargs\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Transformation of an image with randomly sampled zoom blur.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n import torchvision\n\n nb_zooms = 10\n x_blur = torch.zeros_like(x)\n max_zoom_i = np.random.uniform(low=self.zoom_range[0], high=self.zoom_range[1])\n zooms = np.arange(start=1.0, stop=max_zoom_i, step=(max_zoom_i - 1.0) / nb_zooms)\n\n height = x.shape[1]\n width = x.shape[2]\n\n x_nchw = x.permute(0, 3, 1, 2)\n\n for zoom in zooms:\n size = [int(a * zoom) for a in x.shape[1:3]]\n x_resized = torchvision.transforms.functional.resize(\n img=x_nchw, size=size, interpolation=torchvision.transforms.InterpolationMode.BILINEAR\n ).permute(0, 2, 3, 1)\n\n trim_top = (x_resized.shape[1] - height) // 2\n trim_left = (x_resized.shape[2] - width) // 2\n\n x_blur += x_resized[0:1, trim_top : trim_top + height, trim_left : trim_left + width, :]\n\n x_out = (x + x_blur) / (nb_zooms + 1)\n return torch.clamp(x_out, min=self.clip_values[0], max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.zoom, (int, float, tuple)) or (\n isinstance(self.zoom, tuple)\n and (\n len(self.zoom) != 2\n or not isinstance(self.zoom[0], (int, float))\n or not isinstance(self.zoom[1], (int, float))\n or self.zoom[0] > self.zoom[1]\n or self.zoom[0] < 1.0\n )\n ):\n raise ValueError(\"The argument `lam` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/expectation_over_transformation/natural_corruptions/zoom_blur/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements EoT of zoom blur with uniformly sampled zoom factor.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.preprocessing.expectation_over_transformation.tensorflow import EoTTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass EoTZoomBlurTensorFlow(EoTTensorFlowV2):\n \"\"\"\n This module implements EoT of zoom blur with uniformly sampled zoom factor.\n \"\"\"\n\n def __init__(\n self,\n nb_samples: int,\n clip_values: tuple[float, float],\n zoom: float | tuple[float, float],\n apply_fit: bool = False,\n apply_predict: bool = True,\n ) -> None:\n \"\"\"\n Create an instance of EoTZoomBlurTensorFlow.\n\n :param nb_samples: Number of random samples per input sample.\n :param clip_values: Tuple of float representing minimum and maximum values of input `(min, max)`.\n :param zoom: Range to sample the zoom factor. A single float is translated to range [1.0, zoom] or a tuple of\n floats is used to create sampling range [zoom[0], zoom[1]]. The applied zoom is sampled uniformly\n from this range for each image.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n \"\"\"\n super().__init__(\n apply_fit=apply_fit, apply_predict=apply_predict, nb_samples=nb_samples, clip_values=clip_values\n )\n\n self.zoom = zoom\n self.zoom_range = (1.0, zoom) if isinstance(zoom, (int, float)) else zoom\n self._check_params()\n\n def _transform(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None, **kwargs) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Transformation of an image with randomly sampled zoom blur.\n\n :param x: Input samples.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n nb_zooms = 10\n x_blur = tf.zeros_like(x)\n max_zoom_i = np.random.uniform(low=self.zoom_range[0], high=self.zoom_range[1])\n zooms = np.arange(start=1.0, stop=max_zoom_i, step=(max_zoom_i - 1.0) / nb_zooms)\n\n height = x.shape[1]\n width = x.shape[2]\n\n for zoom in zooms:\n size = [int(a * zoom) for a in x.shape[1:3]]\n x_resized = tf.image.resize(\n images=x,\n size=size,\n method=tf.image.ResizeMethod.BILINEAR,\n preserve_aspect_ratio=True,\n antialias=False,\n name=None,\n )\n\n trim_top = (x_resized.shape[1] - height) // 2\n trim_left = (x_resized.shape[2] - width) // 2\n\n x_blur += x_resized[0:1, trim_top : trim_top + height, trim_left : trim_left + width, :]\n\n x_out = (x + x_blur) / (nb_zooms + 1)\n return tf.clip_by_value(x_out, clip_value_min=self.clip_values[0], clip_value_max=self.clip_values[1]), y\n\n def _check_params(self) -> None:\n\n # pylint: disable=too-many-boolean-expressions\n if not isinstance(self.zoom, (int, float, tuple)) or (\n isinstance(self.zoom, tuple)\n and (\n len(self.zoom) != 2\n or not isinstance(self.zoom[0], (int, float))\n or not isinstance(self.zoom[1], (int, float))\n or self.zoom[0] > self.zoom[1]\n or self.zoom[0] < 1.0\n )\n ):\n raise ValueError(\"The argument `lam` has to be a float or tuple of two float values as (min, max).\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains image preprocessing tools.\n\"\"\"\n\nfrom art.preprocessing.image.image_resize.numpy import ImageResize\nfrom art.preprocessing.image.image_resize.pytorch import ImageResizePyTorch\nfrom art.preprocessing.image.image_resize.tensorflow import ImageResizeTensorFlowV2\nfrom art.preprocessing.image.image_square_pad.numpy import ImageSquarePad\nfrom art.preprocessing.image.image_square_pad.pytorch import ImageSquarePadPyTorch\nfrom art.preprocessing.image.image_square_pad.tensorflow import ImageSquarePadTensorFlowV2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/image_resize/numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements resizing for images and object detection bounding boxes.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport cv2\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageResize(Preprocessor):\n \"\"\"\n This module implements resizing for images and object detection bounding boxes.\n \"\"\"\n\n params = [\"height\", \"width\", \"channels_first\", \"label_type\", \"interpolation\", \"clip_values\", \"verbose\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n height: int,\n width: int,\n channels_first: bool = False,\n label_type: str = \"classification\",\n interpolation: int = cv2.INTER_LINEAR,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of ImageResize.\n\n :param height: The height of the resized image.\n :param width: The width of the resized image.\n :param channels_first: Set channels first or last.\n :param label_type: String defining the label type. Currently supported: `classification`, `object_detection`\n :param interpolation: The desired method to resize the image defined by the `cv2::InterpolationFlags` enum.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.height = height\n self.width = width\n self.channels_first = channels_first\n self.label_type = label_type\n self.interpolation = interpolation\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def __call__(\n self, x: np.ndarray, y: np.ndarray | list[dict[str, np.ndarray]] | None = None\n ) -> tuple[np.ndarray, np.ndarray | list[dict[str, np.ndarray]] | None]:\n \"\"\"\n Resize `x` and adjust bounding boxes for labels `y` accordingly.\n\n :param x: Input samples. A list of samples is also supported.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n x_preprocess_list = []\n y_preprocess: np.ndarray | list[dict[str, np.ndarray]] | None\n if y is not None and self.label_type == \"object_detection\":\n y_preprocess = []\n else:\n y_preprocess = y\n\n for i, x_i in enumerate(tqdm(x, desc=\"ImageResize\", disable=not self.verbose)):\n if self.channels_first:\n x_i = np.transpose(x_i, (1, 2, 0))\n\n # Resize image: OpenCV swaps height and width\n x_resized = cv2.resize(x_i, (self.width, self.height), interpolation=self.interpolation)\n\n if self.channels_first:\n x_resized = np.transpose(x_resized, (2, 0, 1))\n\n x_preprocess_list.append(x_resized)\n\n if self.label_type == \"object_detection\" and y is not None:\n y_resized: dict[str, np.ndarray] = {}\n\n # Copy labels and ensure types\n if isinstance(y, list) and isinstance(y_preprocess, list):\n y_i = y[i]\n if isinstance(y_i, dict):\n y_resized = {k: np.copy(v) for k, v in y_i.items()}\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n # Calculate scaling factor\n height, width, _ = x_i.shape\n height_scale = self.height / height\n width_scale = self.width / width\n\n # Resize bounding boxes\n y_resized[\"boxes\"][:, 0] *= width_scale\n y_resized[\"boxes\"][:, 1] *= height_scale\n y_resized[\"boxes\"][:, 2] *= width_scale\n y_resized[\"boxes\"][:, 3] *= height_scale\n\n y_preprocess.append(y_resized)\n\n x_preprocess = np.stack(x_preprocess_list)\n if self.clip_values is not None:\n x_preprocess = np.clip(x_preprocess, self.clip_values[0], self.clip_values[1])\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n if self.height <= 0:\n raise ValueError(\"The desired image height must be positive.\")\n\n if self.width <= 0:\n raise ValueError(\"The desired image width must be positive\")\n\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/image_resize/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements resizing for images and object detection bounding boxes in PyTorch.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageResizePyTorch(PreprocessorPyTorch):\n \"\"\"\n This module implements resizing for images and object detection bounding boxes in PyTorch.\n \"\"\"\n\n params = [\"height\", \"width\", \"channels_first\", \"label_type\", \"interpolation\", \"clip_values\", \"verbose\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n height: int,\n width: int,\n channels_first: bool = True,\n label_type: str = \"classification\",\n interpolation: str = \"bilinear\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of ImageResizePyTorch.\n\n :param height: The height of the resized image.\n :param width: The width of the resized image.\n :param channels_first: Set channels first or last.\n :param label_type: String defining the label type. Currently supported: `classification`, `object_detection`\n :param interpolation: String defining the resizing method. Currently supported: `nearest`, `linear`,\n `bilinear`, `bicubic`, `trilinear`, `area`, `nearest-exact`\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.height = height\n self.width = width\n self.channels_first = channels_first\n self.label_type = label_type\n self.interpolation = interpolation\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self,\n x: \"torch.Tensor\",\n y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None = None,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Resize `x` and adjust bounding boxes for labels `y` accordingly.\n\n :param x: Input samples. A list of samples is also supported.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n x_preprocess_list = []\n y_preprocess: torch.Tensor | list[dict[str, torch.Tensor]] | None\n if y is not None and self.label_type == \"object_detection\":\n y_preprocess = []\n else:\n y_preprocess = y\n\n for i, x_i in enumerate(tqdm(x, desc=\"ImageResizePyTorch\", disable=not self.verbose)):\n if not self.channels_first:\n x_i = torch.permute(x_i, (2, 0, 1))\n\n # Resize image: requires a batch so create batch of size 1\n x_resized = torch.nn.functional.interpolate(\n x_i.unsqueeze(0), size=(self.height, self.width), mode=self.interpolation\n ).squeeze()\n\n if not self.channels_first:\n x_resized = torch.permute(x_resized, (1, 2, 0))\n\n x_preprocess_list.append(x_resized)\n\n if self.label_type == \"object_detection\" and y is not None:\n y_resized: dict[str, torch.Tensor] = {}\n\n # Copy labels and ensure types\n if isinstance(y, list) and isinstance(y_preprocess, list):\n y_i = y[i]\n if isinstance(y_i, dict):\n y_resized = {k: torch.clone(v) for k, v in y_i.items()}\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n # Calculate scaling factor\n _, height, width = x_i.shape\n height_scale = self.height / height\n width_scale = self.width / width\n\n # Resize bounding boxes\n y_resized[\"boxes\"][:, 0] *= width_scale\n y_resized[\"boxes\"][:, 1] *= height_scale\n y_resized[\"boxes\"][:, 2] *= width_scale\n y_resized[\"boxes\"][:, 3] *= height_scale\n\n y_preprocess.append(y_resized)\n\n x_preprocess = torch.stack(x_preprocess_list)\n if self.clip_values is not None:\n x_preprocess = torch.clamp(x_preprocess, self.clip_values[0], self.clip_values[1]) # type: ignore\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n if self.height <= 0:\n raise ValueError(\"The desired image height must be positive.\")\n\n if self.width <= 0:\n raise ValueError(\"The desired image width must be positive\")\n\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/image_resize/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements resizing for images and object detection bounding boxes in TensorFlow v2.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageResizeTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n This module implements resizing for images and object detection bounding boxes in TensorFlow v2.\n \"\"\"\n\n params = [\"height\", \"width\", \"channels_first\", \"label_type\", \"interpolation\", \"clip_values\", \"verbose\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n height: int,\n width: int,\n channels_first: bool = False,\n label_type: str = \"classification\",\n interpolation: str = \"bilinear\",\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of ImageResizeTensorFlowV2.\n\n :param height: The height of the resized image.\n :param width: The width of the resized image.\n :param channels_first: Set channels first or last.\n :param label_type: String defining the label type. Currently supported: `classification`, `object_detection`\n :param interpolation: String defining the resizing method. Currently supported: `area`, `bicubic`,\n `bilinear`, `gaussian`, `lanczos3`, `lanczos5`, 'mitchellcubic', `nearest`\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.height = height\n self.width = width\n self.channels_first = channels_first\n self.label_type = label_type\n self.interpolation = interpolation\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self,\n x: \"tf.Tensor\",\n y: \"tf.Tensor\" | list[dict[str, \"tf.Tensor\"]] | None = None,\n ) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | list[dict[str, \"tf.Tensor\"]] | None]:\n \"\"\"\n Resize `x` and adjust bounding boxes for labels `y` accordingly.\n\n :param x: Input samples. A list of samples is also supported.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n x_preprocess_list = []\n y_preprocess: tf.Tensor | list[dict[str, tf.Tensor]] | None\n if y is not None and self.label_type == \"object_detection\":\n y_preprocess = []\n else:\n y_preprocess = y\n\n for i, x_i in enumerate(tqdm(x, desc=\"ImageResizeTensorFlowV2\", disable=not self.verbose)):\n if self.channels_first:\n x_i = tf.transpose(x_i, (1, 2, 0))\n\n # OpenCV swaps height and width\n x_resized = tf.image.resize(x_i, size=(self.height, self.width), method=self.interpolation)\n\n if self.channels_first:\n x_resized = tf.transpose(x_resized, (2, 0, 1))\n\n x_preprocess_list.append(x_resized)\n\n if self.label_type == \"object_detection\" and y is not None:\n y_resized: dict[str, tf.Tensor] = {}\n\n # Copy labels and ensure types\n if isinstance(y, list) and isinstance(y_preprocess, list):\n y_i = y[i]\n if isinstance(y_i, dict):\n y_resized = {k: tf.identity(v) for k, v in y_i.items()}\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n # Calculate scaling factor\n height, width, _ = x_i.shape\n height_scale = self.height / height\n width_scale = self.width / width\n\n # Resize bounding boxes\n boxes = y_resized[\"boxes\"]\n boxes *= tf.constant([width_scale, height_scale, width_scale, height_scale], dtype=boxes.dtype)\n y_resized[\"boxes\"] = boxes\n\n y_preprocess.append(y_resized)\n\n x_preprocess = tf.stack(x_preprocess_list)\n if self.clip_values is not None:\n x_preprocess = tf.clip_by_value(x_preprocess, self.clip_values[0], self.clip_values[1])\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n if self.height <= 0:\n raise ValueError(\"The desired image height must be positive.\")\n\n if self.width <= 0:\n raise ValueError(\"The desired image width must be positive\")\n\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/image_square_pad/numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements square padding for images and object detection bounding boxes.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import Preprocessor\n\nif TYPE_CHECKING:\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageSquarePad(Preprocessor):\n \"\"\"\n This module implements square padding for images and object detection bounding boxes.\n \"\"\"\n\n params = [\"channels_first\", \"label_type\", \"pad_mode\", \"pad_kwargs\", \"clip_values\", \"verbose\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n channels_first: bool = False,\n label_type: str = \"classification\",\n pad_mode: str = \"constant\",\n pad_kwargs: dict[str, Any] | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of ImageSquarePad.\n\n :param height: The height of the resized image.\n :param width: The width of the resized image.\n :param channels_first: Set channels first or last.\n :param label_type: String defining the label type. Currently supported: `classification`, `object_detection`\n :param pad_mode: String defining the padding method. Currently supported: `constant`, `edge`, `linear_ramp`,\n `maximum`, `mean`, `median`, `minimum`, `reflect`, `symmetric`, `wrap`, `empty`\n :param pad_kwargs: A dictionary of additional keyword arguments used by the `np.pad` function.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.channels_first = channels_first\n self.label_type = label_type\n self.pad_mode = pad_mode\n self.pad_kwargs = pad_kwargs if pad_kwargs is not None else {}\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def __call__(\n self, x: np.ndarray, y: np.ndarray | list[dict[str, np.ndarray]] | None = None\n ) -> tuple[np.ndarray, np.ndarray | list[dict[str, np.ndarray]] | None]:\n \"\"\"\n Square pad `x` and adjust bounding boxes for labels `y` accordingly.\n\n :param x: Input samples. A list of samples is also supported.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n x_preprocess = []\n y_preprocess: np.ndarray | list[dict[str, np.ndarray]] | None\n if y is not None and self.label_type == \"object_detection\":\n y_preprocess = []\n else:\n y_preprocess = y\n\n for i, x_i in enumerate(tqdm(x, desc=\"ImageSquarePad\", disable=not self.verbose)):\n if self.channels_first:\n x_i = np.transpose(x_i, (1, 2, 0))\n\n # Calculate padding\n height, width, _ = x_i.shape\n if height > width:\n pad_top = 0\n pad_bottom = 0\n pad_left = int(np.floor((height - width) / 2))\n pad_right = int(np.ceil((height - width) / 2))\n else:\n pad_top = int(np.floor((width - height) / 2))\n pad_bottom = int(np.ceil((width - height) / 2))\n pad_left = 0\n pad_right = 0\n\n # Pad image to square size\n padding = [[pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]\n x_pad = np.pad(x_i, padding, mode=self.pad_mode, **self.pad_kwargs) # type: ignore\n\n if self.channels_first:\n x_pad = np.transpose(x_pad, (2, 0, 1))\n\n if self.clip_values is not None:\n x_pad = np.clip(x_pad, self.clip_values[0], self.clip_values[1])\n\n x_preprocess.append(x_pad)\n\n if self.label_type == \"object_detection\" and y is not None:\n y_pad: dict[str, np.ndarray] = {}\n\n # Copy labels and ensure types\n if isinstance(y, list) and isinstance(y_preprocess, list):\n y_i = y[i]\n if isinstance(y_i, dict):\n y_pad = {k: np.copy(v) for k, v in y_i.items()}\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n # Shift bounding boxes\n y_pad[\"boxes\"][:, 0] += pad_left\n y_pad[\"boxes\"][:, 1] += pad_top\n y_pad[\"boxes\"][:, 2] += pad_left\n y_pad[\"boxes\"][:, 3] += pad_top\n\n y_preprocess.append(y_pad)\n\n if isinstance(x, np.ndarray):\n return np.stack(x_preprocess, axis=0), y_preprocess\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/image_square_pad/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements square padding for images and object detection bounding boxes in PyTorch.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import PreprocessorPyTorch\n\nif TYPE_CHECKING:\n\n import torch\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageSquarePadPyTorch(PreprocessorPyTorch):\n \"\"\"\n This module implements square padding for images and object detection bounding boxes in PyTorch.\n \"\"\"\n\n params = [\"channels_first\", \"label_type\", \"pad_mode\", \"pad_kwargs\", \"clip_values\", \"verbose\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n channels_first: bool = True,\n label_type: str = \"classification\",\n pad_mode: str = \"constant\",\n pad_kwargs: dict[str, Any] | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of ImageSquarePadPyTorch.\n\n :param height: The height of the resized image.\n :param width: The width of the resized image.\n :param channels_first: Set channels first or last.\n :param label_type: String defining the label type. Currently supported: `classification`, `object_detection`\n :param pad_mode: String defining the padding method. Currently supported: `constant`, `reflect`, `replicate`,\n `circular`\n :param pad_kwargs: A dictionary of additional keyword arguments used by the `torch.nn.functional.pad` function.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.channels_first = channels_first\n self.label_type = label_type\n self.pad_mode = pad_mode\n self.pad_kwargs = pad_kwargs if pad_kwargs is not None else {}\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self,\n x: \"torch.Tensor\",\n y: \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None = None,\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | list[dict[str, \"torch.Tensor\"]] | None]:\n \"\"\"\n Square pad `x` and adjust bounding boxes for labels `y` accordingly.\n\n :param x: Input samples. A list of samples is also supported.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import torch\n\n x_preprocess = []\n y_preprocess: torch.Tensor | list[dict[str, torch.Tensor]] | None\n if y is not None and self.label_type == \"object_detection\":\n y_preprocess = []\n else:\n y_preprocess = y\n\n for i, x_i in enumerate(tqdm(x, desc=\"ImageSquarePadPyTorch\", disable=not self.verbose)):\n if not self.channels_first:\n x_i = torch.permute(x_i, (2, 0, 1))\n\n # Calculate padding\n _, height, width = x_i.shape\n if height > width:\n pad_left = int(np.floor((height - width) / 2))\n pad_right = int(np.ceil((height - width) / 2))\n pad_top = 0\n pad_bottom = 0\n else:\n pad_left = 0\n pad_right = 0\n pad_top = int(np.floor((width - height) / 2))\n pad_bottom = int(np.ceil((width - height) / 2))\n\n # Pad image to square size\n padding = [pad_left, pad_right, pad_top, pad_bottom]\n x_pad = torch.nn.functional.pad(x_i, padding, mode=self.pad_mode, **self.pad_kwargs)\n\n if not self.channels_first:\n x_pad = torch.permute(x_pad, (1, 2, 0))\n\n if self.clip_values is not None:\n x_pad = torch.clamp(x_pad, self.clip_values[0], self.clip_values[1]) # type: ignore\n\n x_preprocess.append(x_pad)\n\n if self.label_type == \"object_detection\" and y is not None:\n y_pad: dict[str, torch.Tensor] = {}\n\n # Copy labels and ensure types\n if isinstance(y, list) and isinstance(y_preprocess, list):\n y_i = y[i]\n if isinstance(y_i, dict):\n y_pad = {k: torch.clone(v) for k, v in y_i.items()}\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n # Shift bounding boxes\n y_pad[\"boxes\"][:, 0] += pad_left\n y_pad[\"boxes\"][:, 1] += pad_top\n y_pad[\"boxes\"][:, 2] += pad_left\n y_pad[\"boxes\"][:, 3] += pad_top\n\n y_preprocess.append(y_pad)\n\n if isinstance(x, torch.Tensor):\n return torch.stack(x_preprocess, dim=0), y_preprocess\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/image/image_square_pad/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements square padding for images and object detection bounding boxes in TensorFlow v2.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Any, TYPE_CHECKING\n\nimport numpy as np\nfrom tqdm.auto import tqdm\n\nfrom art.preprocessing.preprocessing import PreprocessorTensorFlowV2\n\nif TYPE_CHECKING:\n import tensorflow as tf\n from art.utils import CLIP_VALUES_TYPE\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImageSquarePadTensorFlowV2(PreprocessorTensorFlowV2):\n \"\"\"\n This module implements square padding for images and object detection bounding boxes in TensorFlow v2.\n \"\"\"\n\n params = [\"channels_first\", \"label_type\", \"pad_mode\", \"pad_kwargs\", \"clip_values\", \"verbose\"]\n\n label_types = [\"classification\", \"object_detection\"]\n\n def __init__(\n self,\n channels_first: bool = False,\n label_type: str = \"classification\",\n pad_mode: str = \"CONSTANT\",\n pad_kwargs: dict[str, Any] | None = None,\n clip_values: \"CLIP_VALUES_TYPE\" | None = None,\n apply_fit: bool = True,\n apply_predict: bool = False,\n verbose: bool = False,\n ):\n \"\"\"\n Create an instance of ImageSquarePadTensorFlowV2.\n\n :param height: The height of the resized image.\n :param width: The width of the resized image.\n :param channels_first: Set channels first or last.\n :param label_type: String defining the label type. Currently supported: `classification`, `object_detection`\n :param pad_mode: String defining the padding method. Currently supported: `CONSTANT`, `REFLECT`, `SYMMETRIC`\n :param pad_kwargs: A dictionary of additional keyword arguments used by the `tf.pad` function.\n :param clip_values: Tuple of the form `(min, max)` representing the minimum and maximum values allowed\n for features.\n :param apply_fit: True if applied during fitting/training.\n :param apply_predict: True if applied during predicting.\n :param verbose: Show progress bars.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.channels_first = channels_first\n self.label_type = label_type\n self.pad_mode = pad_mode\n self.pad_kwargs = pad_kwargs if pad_kwargs is not None else {}\n self.clip_values = clip_values\n self.verbose = verbose\n self._check_params()\n\n def forward(\n self,\n x: \"tf.Tensor\",\n y: \"tf.Tensor\" | list[dict[str, \"tf.Tensor\"]] | None = None,\n ) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | list[dict[str, \"tf.Tensor\"]] | None]:\n \"\"\"\n Square pad `x` and adjust bounding boxes for labels `y` accordingly.\n\n :param x: Input samples. A list of samples is also supported.\n :param y: Label of the samples `x`.\n :return: Transformed samples and labels.\n \"\"\"\n import tensorflow as tf\n\n x_preprocess = []\n y_preprocess: tf.Tensor | list[dict[str, tf.Tensor]] | None\n if y is not None and self.label_type == \"object_detection\":\n y_preprocess = []\n else:\n y_preprocess = y\n\n for i, x_i in enumerate(tqdm(x, desc=\"ImageSquarePadTensorFlowV2\", disable=not self.verbose)):\n if self.channels_first:\n x_i = tf.transpose(x_i, (1, 2, 0))\n\n # Calculate padding\n height, width, _ = x_i.shape\n if height > width:\n pad_top = 0\n pad_bottom = 0\n pad_left = int(np.floor((height - width) / 2))\n pad_right = int(np.ceil((height - width) / 2))\n else:\n pad_top = int(np.floor((width - height) / 2))\n pad_bottom = int(np.ceil((width - height) / 2))\n pad_left = 0\n pad_right = 0\n\n # Pad image to square size\n padding = [[pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]\n x_pad = tf.pad(x_i, padding, mode=self.pad_mode, **self.pad_kwargs)\n\n if self.channels_first:\n x_pad = tf.transpose(x_pad, (2, 0, 1))\n\n if self.clip_values is not None:\n x_pad = tf.clip_by_value(x_pad, self.clip_values[0], self.clip_values[1])\n\n x_preprocess.append(x_pad)\n\n if self.label_type == \"object_detection\" and y is not None:\n y_pad: dict[str, tf.Tensor] = {}\n\n # Copy labels and ensure types\n if isinstance(y, list) and isinstance(y_preprocess, list):\n y_i = y[i]\n if isinstance(y_i, dict):\n y_pad = {k: tf.identity(v) for k, v in y_i.items()}\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n else:\n raise TypeError(\"Wrong type for `y` and label_type=object_detection.\")\n\n # Shift bounding boxes\n boxes = y_pad[\"boxes\"]\n boxes += tf.constant([pad_left, pad_top, pad_left, pad_top], dtype=boxes.dtype)\n y_pad[\"boxes\"] = boxes\n\n y_preprocess.append(y_pad)\n\n if isinstance(x, tf.Tensor):\n return tf.stack(x_preprocess, axis=0), y_preprocess\n\n return x_preprocess, y_preprocess\n\n def _check_params(self) -> None:\n if self.clip_values is not None:\n if len(self.clip_values) != 2:\n raise ValueError(\"`clip_values` should be a tuple of 2 floats containing the allowed data range.\")\n\n if self.clip_values[0] >= self.clip_values[1]:\n raise ValueError(\"Invalid `clip_values`: min >= max.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/standardisation_mean_std/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis module contains tool for input standardisation with mean and standard deviation.\n\"\"\"\n\nfrom art.preprocessing.standardisation_mean_std.numpy import StandardisationMeanStd\nfrom art.preprocessing.standardisation_mean_std.pytorch import StandardisationMeanStdPyTorch\nfrom art.preprocessing.standardisation_mean_std.tensorflow import StandardisationMeanStdTensorFlow\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/standardisation_mean_std/numpy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the standardisation with mean and standard deviation.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\n\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.preprocessing.preprocessing import Preprocessor\nfrom art.preprocessing.standardisation_mean_std.utils import broadcastable_mean_std\n\nlogger = logging.getLogger(__name__)\n\n\nclass StandardisationMeanStd(Preprocessor):\n \"\"\"\n Implement the standardisation with mean and standard deviation.\n \"\"\"\n\n params = [\"mean\", \"std\", \"apply_fit\", \"apply_predict\"]\n\n def __init__(\n self,\n mean: float | np.ndarray = 0.0,\n std: float | np.ndarray = 1.0,\n apply_fit: bool = True,\n apply_predict: bool = True,\n ):\n \"\"\"\n Create an instance of StandardisationMeanStd.\n\n :param mean: Mean.\n :param std: Standard Deviation.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.mean = np.asarray(mean, dtype=ART_NUMPY_DTYPE)\n self.std = np.asarray(std, dtype=ART_NUMPY_DTYPE)\n self._check_params()\n\n # init broadcastable mean and std for lazy loading\n self._broadcastable_mean: np.ndarray | None = None\n self._broadcastable_std: np.ndarray | None = None\n\n def __call__(\n self,\n x: np.ndarray,\n y: np.ndarray | None = None,\n ) -> tuple[np.ndarray, np.ndarray | None]:\n \"\"\"\n Apply StandardisationMeanStd inputs `x`.\n\n :param x: Input samples to standardise.\n :param y: Label data, will not be affected by this preprocessing.\n :return: Standardise input samples and unmodified labels.\n \"\"\"\n if x.dtype in [np.uint8, np.uint16, np.uint32, np.uint64]: # pragma: no cover\n raise TypeError(\n f\"The data type of input data `x` is {x.dtype} and cannot represent negative values. Consider \"\n f\"changing the data type of the input data `x` to a type that supports negative values e.g. \"\n f\"np.float32.\"\n )\n\n if self._broadcastable_mean is None:\n self._broadcastable_mean, self._broadcastable_std = broadcastable_mean_std(x, self.mean, self.std)\n\n x_norm = x - self._broadcastable_mean\n x_norm = x_norm / self._broadcastable_std\n x_norm = x_norm.astype(ART_NUMPY_DTYPE)\n\n return x_norm, y\n\n def estimate_gradient(self, x: np.ndarray, grad: np.ndarray) -> np.ndarray:\n \"\"\"\n Provide an estimate of the gradients of preprocessor for the backward pass. If the preprocessor is not\n differentiable, this is an estimate of the gradient, most often replacing the computation performed by the\n preprocessor with the identity function (the default).\n\n :param x: Input data for which the gradient is estimated. First dimension is the batch size.\n :param grad: Gradient value so far.\n :return: The gradient (estimate) of the defence.\n \"\"\"\n _, std = broadcastable_mean_std(x, self.mean, self.std)\n gradient_back = grad / std\n\n return gradient_back\n\n def _check_params(self) -> None:\n pass\n\n def __repr__(self):\n return (\n f\"StandardisationMeanStd(mean={self.mean}, std={self.std}, apply_fit={self.apply_fit}, \"\n f\"apply_predict={self.apply_predict})\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/standardisation_mean_std/pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the standardisation with mean and standard deviation.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.preprocessing.preprocessing import PreprocessorPyTorch\nfrom art.preprocessing.standardisation_mean_std.utils import broadcastable_mean_std\n\nif TYPE_CHECKING:\n import torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass StandardisationMeanStdPyTorch(PreprocessorPyTorch):\n \"\"\"\n Implement the standardisation with mean and standard deviation.\n \"\"\"\n\n params = [\"mean\", \"std\", \"apply_fit\", \"apply_predict\"]\n\n def __init__(\n self,\n mean: float | np.ndarray = 0.0,\n std: float | np.ndarray = 1.0,\n apply_fit: bool = True,\n apply_predict: bool = True,\n device_type: str = \"gpu\",\n ):\n \"\"\"\n Create an instance of StandardisationMeanStdPyTorch.\n\n :param mean: Mean.\n :param std: Standard Deviation.\n \"\"\"\n\n super().__init__(\n device_type=device_type,\n is_fitted=True,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n self.mean = np.asarray(mean, dtype=ART_NUMPY_DTYPE)\n self.std = np.asarray(std, dtype=ART_NUMPY_DTYPE)\n self._check_params()\n\n # init broadcastable mean and std for lazy loading\n self._broadcastable_mean: np.ndarray | None = None\n self._broadcastable_std: np.ndarray | None = None\n\n def forward(\n self, x: \"torch.Tensor\", y: \"torch.Tensor\" | None = None\n ) -> tuple[\"torch.Tensor\", \"torch.Tensor\" | None]:\n \"\"\"\n Apply standardisation with mean and standard deviation to input `x`.\n\n :param x: Input samples to standardise.\n :param y: Label data, will not be affected by this preprocessing.\n :return: Standardised input samples and unmodified labels.\n \"\"\"\n import torch\n\n if self._broadcastable_mean is None:\n self._broadcastable_mean, self._broadcastable_std = broadcastable_mean_std(x, self.mean, self.std)\n\n x_norm = x - torch.tensor(self._broadcastable_mean, device=self._device, dtype=torch.float32)\n x_norm = x_norm / torch.tensor(self._broadcastable_std, device=self._device, dtype=torch.float32)\n\n return x_norm, y\n\n def _check_params(self) -> None:\n pass\n\n def __repr__(self):\n return (\n f\"StandardisationMeanStdPyTorch(mean={self.mean}, std={self.std}, apply_fit={self.apply_fit}, \"\n f\"apply_predict={self.apply_predict}, device={self._device})\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/standardisation_mean_std/tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the standardisation with mean and standard deviation.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.preprocessing.preprocessing import PreprocessorTensorFlowV2\nfrom art.preprocessing.standardisation_mean_std.utils import broadcastable_mean_std\n\nif TYPE_CHECKING:\n import tensorflow as tf\n\nlogger = logging.getLogger(__name__)\n\n\nclass StandardisationMeanStdTensorFlow(PreprocessorTensorFlowV2):\n \"\"\"\n Implement the standardisation with mean and standard deviation.\n \"\"\"\n\n params = [\"mean\", \"std\", \"apply_fit\", \"apply_predict\"]\n\n def __init__(\n self,\n mean: float | np.ndarray = 0.0,\n std: float | np.ndarray = 1.0,\n apply_fit: bool = True,\n apply_predict: bool = True,\n ):\n \"\"\"\n Create an instance of StandardisationMeanStdTensorFlow.\n\n :param mean: Mean.\n :param std: Standard Deviation.\n \"\"\"\n super().__init__(is_fitted=True, apply_fit=apply_fit, apply_predict=apply_predict)\n self.mean = np.asarray(mean, dtype=ART_NUMPY_DTYPE)\n self.std = np.asarray(std, dtype=ART_NUMPY_DTYPE)\n self._check_params()\n\n # init broadcastable mean and std for lazy loading\n self._broadcastable_mean: np.ndarray | None = None\n self._broadcastable_std: np.ndarray | None = None\n\n def forward(self, x: \"tf.Tensor\", y: \"tf.Tensor\" | None = None) -> tuple[\"tf.Tensor\", \"tf.Tensor\" | None]:\n \"\"\"\n Apply standardisation with mean and standard deviation to input `x`.\n\n :param x: Input samples to standardise.\n :param y: Label data, will not be affected by this preprocessing.\n :return: Standardised input samples and unmodified labels.\n \"\"\"\n import tensorflow as tf\n\n if self._broadcastable_mean is None:\n self._broadcastable_mean, self._broadcastable_std = broadcastable_mean_std(x, self.mean, self.std)\n\n x_norm = x - self._broadcastable_mean\n x_norm = x_norm / self._broadcastable_std\n x_norm = tf.cast(x_norm, dtype=ART_NUMPY_DTYPE)\n\n return x_norm, y\n\n def _check_params(self) -> None:\n pass\n\n def __repr__(self):\n return (\n f\"StandardisationMeanStdTensorFlow(mean={self.mean}, std={self.std}, apply_fit={self.apply_fit}, \"\n f\"apply_predict={self.apply_predict})\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: art/preprocessing/standardisation_mean_std/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements utilities for standardisation with mean and standard deviation.\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nif TYPE_CHECKING:\n import tensorflow as tf\n import torch\n\n\ndef broadcastable_mean_std(\n x: np.ndarray | \"torch.Tensor\" | \"tf.Tensor\", mean: np.ndarray, std: np.ndarray\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Ensure that the mean and standard deviation are broadcastable with respect to input `x`.\n\n :param x: Input samples to standardise.\n :param mean: Mean.\n :param std: Standard Deviation.\n \"\"\"\n if mean.shape != std.shape: # pragma: no cover\n raise ValueError(\"The shape of mean and the standard deviation must be identical.\")\n\n # catch non-broadcastable input, when mean and std are vectors\n if mean.ndim == 1 and mean.shape[0] > 1 and mean.shape[0] != x.shape[-1]:\n # allow input shapes NC* (batch) and C* (non-batch)\n channel_idx = 1 if x.shape[1] == mean.shape[0] else 0\n broadcastable_shape = [1] * x.ndim\n broadcastable_shape[channel_idx] = mean.shape[0]\n\n # expand mean and std to new shape\n mean = mean.reshape(broadcastable_shape)\n std = std.reshape(broadcastable_shape)\n return mean, std\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: docs/conf.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/stable/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(\"..\"))\n\n# import art\n\n# -- Project information -----------------------------------------------------\n\nproject = \"Adversarial Robustness Toolbox\"\ncopyright = \"2018, The Adversarial Robustness Toolbox (ART) Authors\"\nauthor = \"Maria-Irina Nicolae\"\n\n# The short X.Y version\nversion = \"1.20\"\n# The full version, including alpha/beta/rc tags\nrelease = \"1.20.1\"\n\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\"sphinx.ext.viewcode\", \"sphinx.ext.autodoc\"]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = \".rst\"\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = \"English\"\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path .\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\n# html_theme = 'alabaster'\n\nif os.environ.get(\"READTHEDOCS\") != \"True\":\n try:\n import sphinx_rtd_theme\n except ImportError:\n pass # assume we have sphinx >= 1.3\n html_theme = \"sphinx_rtd_theme\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = []\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# The default sidebars (for documents that don't match any pattern) are\n# defined by theme itself. Builtin themes are using these templates by\n# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',\n# 'searchbox.html']``.\n#\n# html_sidebars = {}\n\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = \"adversarial-robustness-toolboxdoc\"\n\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (\n master_doc,\n \"adversarial-robustness-toolbox.tex\",\n \"adversarial-robustness-toolbox Documentation\",\n \"Maria-Irina Nicolae\",\n \"manual\",\n ),\n]\n\n\n# -- Options for manual page output ------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, \"adversarial-robustness-toolbox\", \"adversarial-robustness-toolbox Documentation\", [author], 1)\n]\n\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (\n master_doc,\n \"adversarial-robustness-toolbox\",\n \"adversarial-robustness-toolbox Documentation\",\n author,\n \"adversarial-robustness-toolbox\",\n \"One line description of project.\",\n \"Miscellaneous\",\n ),\n]\n\n\n# -- Extension configuration -------------------------------------------------\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx_autodoc_annotation\",\n]\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Adversarial Robustness Toolbox examples\n\n## Get Started with ART\nThese examples train a small model on the MNIST dataset and creates adversarial examples using the Fast Gradient Sign \nMethod. Here we use the ART classifier to train the model, it would also be possible to provide a pretrained model to \nthe ART classifier. The parameters are chosen for reduced computational requirements of the script and not optimised \nfor accuracy.\n\n\n### TensorFlow\n[get_started_tensorflow_v2.py](get_started_tensorflow_v2.py) demonstrates a simple example of using ART with TensorFlow v2.x. \n\n### Keras\n[get_started_keras.py](get_started_keras.py) demonstrates a simple example of using ART with Keras.\n\n### PyTorch\n[get_started_pytorch.py](get_started_pytorch.py) demonstrates a simple example of using ART with PyTorch.\n\n### Scikit-learn\n[get_started_scikit_learn.py](get_started_scikit_learn.py) demonstrates a simple example of using ART with Scikit-learn. \nThis example uses the support vector machine SVC, but any other classifier of Scikit-learn can be used as well.\n\n### XGBoost\n[get_started_xgboost.py](get_started_xgboost.py) demonstrates a simple example of using ART with XGBoost.\nBecause gradient boosted tree classifier do not provide gradients, the adversarial examples are created with the \nblack-box method Zeroth Order Optimization.\n\n### InverseGAN\n[get_started_inverse_gan.py](get_started_inverse_gan.py) demonstrates a simple example of using \nInverseGAN and Defense ART with TensorFlow v1.x.\n\n### LightGBM\n[get_started_lightgbm.py](get_started_lightgbm.py) demonstrates a simple example of using ART with LightGBM.\nBecause gradient boosted tree classifier do not provide gradients, the adversarial examples are created with the \nblack-box method Zeroth Order Optimization.\n\n\n## Applications\n\n[adversarial_training_cifar10.py](adversarial_training_cifar10.py) trains a convolutional neural network on the CIFAR-10 \ndataset, then generates adversarial images using the DeepFool attack and retrains the network on the training set \naugmented with the adversarial images.\n\n[adversarial_training_data_augmentation.py](adversarial_training_data_augmentation.py) shows how to use ART and Keras \nto perform adversarial training using data generators for CIFAR-10.\n\n[mnist_cnn_fgsm.py](mnist_cnn_fgsm.py) trains a convolutional neural network on MNIST, then crafts FGSM attack examples \non it.\n\n[mnist_poison_detection.py](mnist_poison_detection.py) generates a backdoor for MNIST dataset, then trains a \nconvolutional neural network on the poisoned dataset and runs activation defence to find poison.\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/adversarial_training_FBF.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART for adversarial training of a model with Fast is better than free protocol\n\"\"\"\n\nimport math\nfrom PIL import Image\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.data_generators import PyTorchDataGenerator\nfrom art.defences.trainer import AdversarialTrainerFBFPyTorch\nfrom art.utils import load_cifar10\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\"\"\"\nFor this example we choose the PreActResNet model as used in the paper (https://openreview.net/forum?id=BJx040EFvH)\nThe code for the model architecture has been adopted from\nhttps://github.com/anonymous-sushi-armadillo/fast_is_better_than_free_CIFAR10/blob/master/preact_resnet.py\n\"\"\"\n\n\nclass PreActBlock(nn.Module):\n \"\"\"Pre-activation version of the BasicBlock.\"\"\"\n\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(x) if hasattr(self, \"shortcut\") else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out += shortcut\n return out\n\n\nclass PreActBottleneck(nn.Module):\n \"\"\"Pre-activation version of the original Bottleneck module.\"\"\"\n\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBottleneck, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False)\n\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, \"shortcut\") else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out = self.conv3(F.relu(self.bn3(out)))\n out += shortcut\n return out\n\n\nclass PreActResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(PreActResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef PreActResNet18():\n return PreActResNet(PreActBlock, [2, 2, 2, 2])\n\n\ndef initialize_weights(module):\n if isinstance(module, nn.Conv2d):\n n = module.kernel_size[0] * module.kernel_size[1] * module.out_channels\n module.weight.data.normal_(0, math.sqrt(2.0 / n))\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.BatchNorm2d):\n module.weight.data.fill_(1)\n module.bias.data.zero_()\n elif isinstance(module, nn.Linear):\n module.bias.data.zero_()\n\n\nclass CIFAR10_dataset(Dataset):\n def __init__(self, data, targets, transform=None):\n self.data = data\n self.targets = torch.LongTensor(targets)\n self.transform = transform\n\n def __getitem__(self, index):\n x = Image.fromarray(((self.data[index] * 255).round()).astype(np.uint8).transpose(1, 2, 0))\n x = self.transform(x)\n y = self.targets[index]\n return x, y\n\n def __len__(self):\n return len(self.data)\n\n\n# Step 1: Load the CIFAR10 dataset\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_cifar10()\n\ncifar_mu = np.ones((3, 32, 32))\ncifar_mu[0, :, :] = 0.4914\ncifar_mu[1, :, :] = 0.4822\ncifar_mu[2, :, :] = 0.4465\n\n# (0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\n\ncifar_std = np.ones((3, 32, 32))\ncifar_std[0, :, :] = 0.2471\ncifar_std[1, :, :] = 0.2435\ncifar_std[2, :, :] = 0.2616\n\nx_train = x_train.transpose(0, 3, 1, 2).astype(\"float32\")\nx_test = x_test.transpose(0, 3, 1, 2).astype(\"float32\")\n\ntransform = transforms.Compose(\n [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()]\n)\n\ndataset = CIFAR10_dataset(x_train, y_train, transform=transform)\ndataloader = DataLoader(dataset, batch_size=128, shuffle=True)\n\n# Step 2: create the PyTorch model\nmodel = PreActResNet18()\n# For running on GPU replace the model with the\n# model = PreActResNet18().cuda()\n\nmodel.apply(initialize_weights)\nmodel.train()\n\nopt = torch.optim.SGD(model.parameters(), lr=0.21, momentum=0.9, weight_decay=5e-4)\n\n# if you have apex installed, the following line should be uncommented for faster processing\n# import apex.amp as amp\n# model, opt = amp.initialize(model, opt, opt_level=\"O2\", loss_scale=1.0, master_weights=False)\n\ncriterion = nn.CrossEntropyLoss()\n# Step 3: Create the ART classifier\n\nclassifier = PyTorchClassifier(\n model=model,\n clip_values=(0.0, 1.0),\n preprocessing=(cifar_mu, cifar_std),\n loss=criterion,\n optimizer=opt,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\nattack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=8.0 / 255.0,\n eps_step=2.0 / 255.0,\n max_iter=40,\n targeted=False,\n num_random_init=5,\n batch_size=32,\n)\n\n# Step 4: Create the trainer object - AdversarialTrainerFBFPyTorch\n# if you have apex installed, change use_amp to True\nepsilon = 8.0 / 255.0\ntrainer = AdversarialTrainerFBFPyTorch(classifier, eps=epsilon, use_amp=False)\n\n# Build a Keras image augmentation object and wrap it in ART\nart_datagen = PyTorchDataGenerator(iterator=dataloader, size=x_train.shape[0], batch_size=128)\n\n# Step 5: fit the trainer\ntrainer.fit_generator(art_datagen, nb_epochs=30)\n\nx_test_pred = np.argmax(classifier.predict(x_test), axis=1)\nprint(\n \"Accuracy on benign test samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\nx_test_attack = attack.generate(x_test)\nx_test_attack_pred = np.argmax(classifier.predict(x_test_attack), axis=1)\nprint(\n \"Accuracy on original PGD adversarial samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_attack_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/adversarial_training_awp.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART for adversarial training of a model with AWP protocol\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.optim.lr_scheduler import MultiStepLR\n\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.data_generators import PyTorchDataGenerator\nfrom art.defences.trainer import AdversarialTrainerAWPPyTorch\nfrom art.utils import load_cifar10\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\"\"\"\nFor this example we choose the PreActResNet18 model as used in the paper\n(https://proceedings.neurips.cc/paper/2020/file/1ef91c212e30e14bf125e9374262401f-Paper.pdf)\nThe code for the model architecture has been adopted from\nhttps://github.com/csdongxian/AWP/blob/main/AT_AWP/preactresnet.py\n\"\"\"\n\n\nclass PreActBlock(nn.Module):\n \"\"\"Pre-activation version of the BasicBlock.\"\"\"\n\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBlock, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, \"shortcut\") else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out += shortcut\n return out\n\n\nclass PreActBottleneck(nn.Module):\n \"\"\"Pre-activation version of the original Bottleneck module.\"\"\"\n\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(PreActBottleneck, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False)\n\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, \"shortcut\") else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n out = self.conv3(F.relu(self.bn3(out)))\n out += shortcut\n return out\n\n\nclass PreActResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(PreActResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.bn = nn.BatchNorm2d(512 * block.expansion)\n self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.relu(self.bn(out))\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef PreActResNet18(num_classes=10):\n return PreActResNet(PreActBlock, [2, 2, 2, 2], num_classes=num_classes)\n\n\nclass CIFAR10_dataset(Dataset):\n def __init__(self, data, targets, transform=None):\n self.data = data\n self.targets = torch.LongTensor(targets)\n self.transform = transform\n\n def __getitem__(self, index):\n x = Image.fromarray(((self.data[index] * 255).round()).astype(np.uint8).transpose(1, 2, 0))\n x = self.transform(x)\n y = self.targets[index]\n return x, y\n\n def __len__(self):\n return len(self.data)\n\n\n# Step 1: Load the CIFAR10 dataset\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_cifar10()\n\ncifar_mu = np.ones((3, 32, 32))\ncifar_mu[0, :, :] = 0.4914\ncifar_mu[1, :, :] = 0.4822\ncifar_mu[2, :, :] = 0.4465\n\ncifar_std = np.ones((3, 32, 32))\ncifar_std[0, :, :] = 0.2471\ncifar_std[1, :, :] = 0.2435\ncifar_std[2, :, :] = 0.2616\n\nx_train = x_train.transpose(0, 3, 1, 2).astype(\"float32\")\nx_test = x_test.transpose(0, 3, 1, 2).astype(\"float32\")\n\ntransform = transforms.Compose(\n [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()]\n)\n\ndataset = CIFAR10_dataset(x_train, y_train, transform=transform)\ndataloader = DataLoader(dataset, batch_size=128, shuffle=True)\n\n# Step 2: create the PyTorch model\nmodel = PreActResNet18()\nopt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)\nlr_scheduler = MultiStepLR(opt, milestones=[100, 150], gamma=0.1)\n\nproxy_model = PreActResNet18()\ngamma = 0.01\nwarmup = 0\nproxy_opt = torch.optim.SGD(proxy_model.parameters(), lr=gamma)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Step 3: Create the ART classifier\n\nclassifier = PyTorchClassifier(\n model=model,\n clip_values=(min_pixel_value, max_pixel_value),\n preprocessing=(cifar_mu, cifar_std),\n loss=criterion,\n optimizer=opt,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\nproxy_classifier = PyTorchClassifier(\n model=proxy_model,\n clip_values=(min_pixel_value, max_pixel_value),\n preprocessing=(cifar_mu, cifar_std),\n loss=criterion,\n optimizer=proxy_opt,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\nattack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=8.0 / 255.0,\n eps_step=2.0 / 255.0,\n max_iter=10,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\n\n# Step 4: Create the trainer object - AdversarialTrainerAWPPyTorch\ntrainer = AdversarialTrainerAWPPyTorch(\n classifier, proxy_classifier, attack, mode=\"PGD\", gamma=gamma, beta=6.0, warmup=warmup\n)\n\n\n# Build a PyTorch data generator in ART\nart_datagen = PyTorchDataGenerator(iterator=dataloader, size=x_train.shape[0], batch_size=128)\n\n# Step 5: fit the trainer\ntrainer.fit_generator(art_datagen, validation_data=(x_test, y_test), nb_epochs=200, scheduler=lr_scheduler)\n\nx_test_pred = np.argmax(classifier.predict(x_test), axis=1)\nprint(\n \"Accuracy on benign test samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\nattack_test = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=8.0 / 255.0,\n eps_step=2.0 / 255.0,\n max_iter=20,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\nx_test_attack = attack_test.generate(x_test, y=y_test)\nx_test_attack_pred = np.argmax(classifier.predict(x_test_attack), axis=1)\nprint(\n \"Accuracy on original PGD adversarial samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_attack_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/adversarial_training_cifar10.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# -*- coding: utf-8 -*-\n\"\"\"\nTrains a convolutional neural network on the CIFAR-10 dataset, then generated adversarial images using the\nDeepFool attack and retrains the network on the training set augmented with the adversarial images.\n\"\"\"\n# noqa: E402\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\nimport numpy as np\n\nfrom art.attacks.evasion import DeepFool\nfrom art.estimators.classification import KerasClassifier\nfrom art.utils import load_dataset\n\n# Configure a logger to capture ART outputs; these are printed in console and the level of detail is set to INFO\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\"[%(levelname)s] %(message)s\")\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n# Read CIFAR10 dataset\n(x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(str(\"cifar10\"))\nx_train, y_train = x_train[:5000], y_train[:5000]\nx_test, y_test = x_test[:500], y_test[:500]\nim_shape = x_train[0].shape\n\n# Create Keras convolutional neural network - basic architecture from Keras examples\n# Source here: https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), padding=\"same\", input_shape=x_train.shape[1:]))\nmodel.add(Activation(\"relu\"))\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation(\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding=\"same\"))\nmodel.add(Activation(\"relu\"))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation(\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10))\nmodel.add(Activation(\"softmax\"))\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\n# Create classifier wrapper\nclassifier = KerasClassifier(model=model, clip_values=(min_, max_))\nclassifier.fit(x_train, y_train, nb_epochs=10, batch_size=128)\n\n# Craft adversarial samples with DeepFool\nlogger.info(\"Create DeepFool attack\")\nadv_crafter = DeepFool(classifier)\nlogger.info(\"Craft attack on training examples\")\nx_train_adv = adv_crafter.generate(x_train)\nlogger.info(\"Craft attack test examples\")\nx_test_adv = adv_crafter.generate(x_test)\n\n# Evaluate the classifier on the adversarial samples\npreds = np.argmax(classifier.predict(x_test_adv), axis=1)\nacc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\nlogger.info(\"Classifier before adversarial training\")\nlogger.info(\"Accuracy on adversarial samples: %.2f%%\", (acc * 100))\n\n# Data augmentation: expand the training set with the adversarial samples\nx_train = np.append(x_train, x_train_adv, axis=0)\ny_train = np.append(y_train, y_train, axis=0)\n\n# Retrain the CNN on the extended dataset\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\nclassifier.fit(x_train, y_train, nb_epochs=10, batch_size=128)\n\n# Evaluate the adversarially trained classifier on the test set\npreds = np.argmax(classifier.predict(x_test_adv), axis=1)\nacc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\nlogger.info(\"Classifier with adversarial training\")\nlogger.info(\"Accuracy on adversarial samples: %.2f%%\", (acc * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/adversarial_training_data_augmentation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART and Keras to perform adversarial training using data generators for CIFAR10\n\"\"\"\n\nimport keras\nimport numpy as np\nfrom keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Input, BatchNormalization\nfrom keras.models import Model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\n\nfrom art.attacks.evasion import ProjectedGradientDescent\nfrom art.estimators.classification import KerasClassifier\nfrom art.data_generators import KerasDataGenerator\nfrom art.defences.trainer import AdversarialTrainer\nfrom art.utils import load_cifar10\n\n\n# Example LeNet classifier architecture with Keras & ART\n# To obtain good performance in adversarial training on CIFAR-10, use a larger architecture\ndef build_model(input_shape=(32, 32, 3), nb_classes=10):\n img_input = Input(shape=input_shape)\n conv2d_1 = Conv2D(\n 6,\n (5, 5),\n padding=\"valid\",\n kernel_regularizer=l2(0.0001),\n activation=\"relu\",\n kernel_initializer=\"he_normal\",\n input_shape=input_shape,\n )(img_input)\n conv2d_1_bn = BatchNormalization()(conv2d_1)\n conv2d_1_pool = MaxPooling2D((2, 2), strides=(2, 2))(conv2d_1_bn)\n conv2d_2 = Conv2D(16, (5, 5), padding=\"valid\", activation=\"relu\", kernel_initializer=\"he_normal\")(conv2d_1_pool)\n conv2d_2_pool = MaxPooling2D((2, 2), strides=(2, 2))(conv2d_2)\n flatten_1 = Flatten()(conv2d_2_pool)\n dense_1 = Dense(120, activation=\"relu\", kernel_initializer=\"he_normal\")(flatten_1)\n dense_2 = Dense(84, activation=\"relu\", kernel_initializer=\"he_normal\")(dense_1)\n img_output = Dense(nb_classes, activation=\"softmax\", kernel_initializer=\"he_normal\")(dense_2)\n model = Model(img_input, img_output)\n\n model.compile(\n loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adam(learning_rate=0.01),\n metrics=[\"accuracy\"],\n )\n\n return model\n\n\n# Load data and normalize\n(x_train, y_train), (x_test, y_test), min_, max_ = load_cifar10()\n\n# Build a Keras image augmentation object and wrap it in ART\nbatch_size = 50\ndatagen = ImageDataGenerator(\n horizontal_flip=True, width_shift_range=0.125, height_shift_range=0.125, fill_mode=\"constant\", cval=0.0\n)\ndatagen.fit(x_train)\nart_datagen = KerasDataGenerator(\n datagen.flow(x=x_train, y=y_train, batch_size=batch_size, shuffle=True),\n size=x_train.shape[0],\n batch_size=batch_size,\n)\n\n# Create a toy Keras CNN architecture & wrap it under ART interface\nclassifier = KerasClassifier(build_model(), clip_values=(0, 1), use_logits=False)\n\n# Create attack for adversarial trainer; here, we use 2 attacks, both crafting adv examples on the target model\npgd = ProjectedGradientDescent(classifier, eps=8 / 255, eps_step=2 / 255, max_iter=10, num_random_init=1)\n\n# Create some adversarial samples for evaluation\nx_test_pgd = pgd.generate(x_test)\n\n# Create adversarial trainer and perform adversarial training\nadv_trainer = AdversarialTrainer(classifier, attacks=pgd, ratio=1.0)\nadv_trainer.fit_generator(art_datagen, nb_epochs=83)\n\n# Evaluate the adversarially trained model on clean test set\nlabels_true = np.argmax(y_test, axis=1)\nlabels_test = np.argmax(classifier.predict(x_test), axis=1)\nprint(\"Accuracy test set: %.2f%%\" % (np.sum(labels_test == labels_true) / x_test.shape[0] * 100))\n\n# Evaluate the adversarially trained model on original adversarial samples\nlabels_pgd = np.argmax(classifier.predict(x_test_pgd), axis=1)\nprint(\n \"Accuracy on original PGD adversarial samples: %.2f%%\" % (np.sum(labels_pgd == labels_true) / x_test.shape[0] * 100)\n)\n\n# Evaluate the adversarially trained model on fresh adversarial samples produced on the adversarially trained model\nx_test_pgd = pgd.generate(x_test)\nlabels_pgd = np.argmax(classifier.predict(x_test_pgd), axis=1)\nprint(\"Accuracy on new PGD adversarial samples: %.2f%%\" % (np.sum(labels_pgd == labels_true) / x_test.shape[0] * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/adversarial_training_oaat.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART for adversarial training of a model with OAAT protocol\nfor defence against larger perturbations.\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.data_generators import PyTorchDataGenerator\nfrom art.defences.trainer import AdversarialTrainerOAATPyTorch\nfrom art.utils import load_cifar10\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\"\"\"\nFor this example we choose the PreActResNet18 model as used in the paper\n(Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18)\nThe code for the model architecture has been adopted from\nhttps://github.com/val-iisc/OAAT/blob/main/models/resnet.py\n\"\"\"\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU()\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion * planes),\n )\n\n def forward(self, x):\n out = self.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(self.expansion * planes)\n self.relu = nn.ReLU()\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion * planes),\n )\n\n def forward(self, x):\n out = self.relu(self.bn1(self.conv1(x)))\n out = self.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(ResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef ResNet18(num_classes=10):\n return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)\n\n\nclass CIFAR10_dataset(Dataset):\n def __init__(self, data, targets, transform=None):\n self.data = data\n self.targets = torch.LongTensor(targets)\n self.transform = transform\n\n def __getitem__(self, index):\n x = Image.fromarray(((self.data[index] * 255).round()).astype(np.uint8).transpose(1, 2, 0))\n x = self.transform(x)\n y = self.targets[index]\n return x, y\n\n def __len__(self):\n return len(self.data)\n\n\n# Step 1: Load the CIFAR10 dataset\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_cifar10()\n\nx_train = x_train.transpose(0, 3, 1, 2).astype(\"float32\")\nx_test = x_test.transpose(0, 3, 1, 2).astype(\"float32\")\n\ntransform = transforms.Compose(\n [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()]\n)\n\ndataset = CIFAR10_dataset(x_train, y_train, transform=transform)\ndataloader = DataLoader(dataset, batch_size=128, shuffle=True)\n\ntrain_params = {\n \"weight_decay\": 5e-4,\n \"lr\": 0.2,\n \"momentum\": 0.9,\n \"norm\": np.inf,\n \"i_epsilon\": 4 / 255.0,\n \"epsilon\": 16 / 255.0,\n \"alternate_iter_eps\": 12 / 255.0,\n \"mixup_epsilon\": 24 / 255.0,\n \"max_iter\": 10,\n \"alpha\": 1.0,\n \"mixup_alpha\": 0.2,\n \"beta\": 1.5,\n \"beta_final\": 3.0,\n \"awp_gamma\": 0.005,\n \"awp_warmup\": 10,\n \"lr_schedule\": \"cosine\",\n \"lpips_weight\": 1.0,\n \"i_lpips_weight\": 1.0,\n \"oaat_warmup\": 0,\n \"swa_save_epoch\": 0,\n \"list_swa_tau\": [0.995],\n \"list_swa_epoch\": [0],\n \"models_path\": None,\n \"load_swa_model_tau\": 0.995,\n \"layer_names_activation\": [\"layer1\", \"layer2\", \"layer3\", \"layer4\"],\n}\n\n\n# Step 2: create the PyTorch model\nmodel = ResNet18()\nopt = torch.optim.SGD(\n model.parameters(),\n lr=train_params[\"lr\"],\n momentum=train_params[\"momentum\"],\n weight_decay=train_params[\"weight_decay\"],\n)\n\nproxy_model = ResNet18()\nproxy_opt = torch.optim.SGD(proxy_model.parameters(), lr=train_params[\"awp_gamma\"])\n\nlpips_model = ResNet18()\n\ncriterion = nn.CrossEntropyLoss()\n\n# Step 3: Create the ART classifier\n\nclassifier = PyTorchClassifier(\n model=model,\n clip_values=(min_pixel_value, max_pixel_value),\n loss=criterion,\n optimizer=opt,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\nproxy_classifier = PyTorchClassifier(\n model=proxy_model,\n clip_values=(min_pixel_value, max_pixel_value),\n loss=criterion,\n optimizer=proxy_opt,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\nlpips_classifier = PyTorchClassifier(\n model=lpips_model,\n clip_values=(min_pixel_value, max_pixel_value),\n loss=criterion,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\n\nlist_avg_models = [\n PyTorchClassifier(\n model=ResNet18(),\n clip_values=(min_pixel_value, max_pixel_value),\n loss=criterion,\n input_shape=(3, 32, 32),\n nb_classes=10,\n )\n for _ in range(len(train_params[\"list_swa_tau\"]))\n]\n\n\nattack = ProjectedGradientDescent(\n classifier,\n norm=train_params[\"norm\"],\n eps=train_params[\"epsilon\"],\n eps_step=train_params[\"epsilon\"] / 4.0,\n max_iter=train_params[\"max_iter\"],\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\n\n# Step 4: Create the trainer object - AdversarialTrainerOAATPyTorch\ntrainer = AdversarialTrainerOAATPyTorch(\n classifier, proxy_classifier, lpips_classifier, list_avg_models, attack, train_params=train_params\n)\n\n\n# Build a PyTorch data generator in ART\nart_datagen = PyTorchDataGenerator(iterator=dataloader, size=x_train.shape[0], batch_size=128)\n\n# Step 5: fit the trainer\ntrainer.fit_generator(art_datagen, validation_data=(x_test, y_test), nb_epochs=110)\n\nx_test_pred = np.argmax(classifier.predict(x_test), axis=1)\nprint(\n \"Accuracy on benign test samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\nattack_test_eps8s2 = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=8.0 / 255.0,\n eps_step=2.0 / 255.0,\n max_iter=20,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\nx_test_attack_eps8s2 = attack_test_eps8s2.generate(x_test, y=y_test)\nx_test_attack_pred_eps8s2 = np.argmax(classifier.predict(x_test_attack_eps8s2), axis=1)\nprint(\n \"Accuracy on original PGD adversarial samples with epsilon 8/255 and step size 2/255 after \"\n \"adversarial training: %.2f%%\"\n % (np.sum(x_test_attack_pred_eps8s2 == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\nattack_test_eps16s4 = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=16.0 / 255.0,\n eps_step=4.0 / 255.0,\n max_iter=20,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\nx_test_attack_eps16s4 = attack_test_eps16s4.generate(x_test, y=y_test)\nx_test_attack_pred_eps16s4 = np.argmax(classifier.predict(x_test_attack_eps16s4), axis=1)\nprint(\n \"Accuracy on original PGD adversarial samples with epsilon 16/255 and step size 4/255 after \"\n \"adversarial training: %.2f%%\"\n % (np.sum(x_test_attack_pred_eps16s4 == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/adversarial_training_trades.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART for adversarial training of a model with TRADES protocol\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.optim.lr_scheduler import MultiStepLR\n\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.data_generators import PyTorchDataGenerator\nfrom art.defences.trainer import AdversarialTrainerTRADESPyTorch\nfrom art.utils import load_cifar10\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\"\"\"\nFor this example we choose the ResNet18 model as used in the paper (https://proceedings.mlr.press/v97/zhang19p.html)\nThe code for the model architecture has been adopted from\nhttps://github.com/yaodongyu/TRADES/blob/master/models/resnet.py\n\"\"\"\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion * planes),\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(ResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef ResNet18():\n return ResNet(BasicBlock, [2, 2, 2, 2])\n\n\nclass CIFAR10_dataset(Dataset):\n def __init__(self, data, targets, transform=None):\n self.data = data\n self.targets = torch.LongTensor(targets)\n self.transform = transform\n\n def __getitem__(self, index):\n x = Image.fromarray(((self.data[index] * 255).round()).astype(np.uint8).transpose(1, 2, 0))\n x = self.transform(x)\n y = self.targets[index]\n return x, y\n\n def __len__(self):\n return len(self.data)\n\n\n# Step 1: Load the CIFAR10 dataset\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_cifar10()\n\nx_train = x_train.transpose(0, 3, 1, 2).astype(\"float32\")\nx_test = x_test.transpose(0, 3, 1, 2).astype(\"float32\")\n\ntransform = transforms.Compose(\n [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()]\n)\n\ndataset = CIFAR10_dataset(x_train, y_train, transform=transform)\ndataloader = DataLoader(dataset, batch_size=128, shuffle=True)\n\n# Step 2: create the PyTorch model\nmodel = ResNet18()\n\nopt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=2e-4)\nlr_scheduler = MultiStepLR(opt, milestones=[74, 89], gamma=0.1)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Step 3: Create the ART classifier\n\nclassifier = PyTorchClassifier(\n model=model,\n clip_values=(min_pixel_value, max_pixel_value),\n loss=criterion,\n optimizer=opt,\n input_shape=(3, 32, 32),\n nb_classes=10,\n)\n\nattack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=8.0 / 255.0,\n eps_step=2.0 / 255.0,\n max_iter=10,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\n\n# Step 4: Create the trainer object - AdversarialTrainerTRADESPyTorch\ntrainer = AdversarialTrainerTRADESPyTorch(classifier, attack, beta=6.0)\n\n# Build a Keras image augmentation object and wrap it in ART\nart_datagen = PyTorchDataGenerator(iterator=dataloader, size=x_train.shape[0], batch_size=128)\n\n# Step 5: fit the trainer\ntrainer.fit_generator(art_datagen, nb_epochs=100, scheduler=lr_scheduler)\n\nx_test_pred = np.argmax(classifier.predict(x_test), axis=1)\nprint(\n \"Accuracy on benign test samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\nattack_test = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=8.0 / 255.0,\n eps_step=2.0 / 255.0,\n max_iter=20,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n)\nx_test_attack = attack_test.generate(x_test, y=y_test)\nx_test_attack_pred = np.argmax(classifier.predict(x_test_attack), axis=1)\nprint(\n \"Accuracy on original PGD adversarial samples after adversarial training: %.2f%%\"\n % (np.sum(x_test_attack_pred == np.argmax(y_test, axis=1)) / x_test.shape[0] * 100)\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/application_object_detection.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom art.estimators.object_detection import PyTorchFasterRCNN\nfrom art.attacks.evasion import ProjectedGradientDescent\n\nCOCO_INSTANCE_CATEGORY_NAMES = [\n \"__background__\",\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"N/A\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"N/A\",\n \"backpack\",\n \"umbrella\",\n \"N/A\",\n \"N/A\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"N/A\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"N/A\",\n \"dining table\",\n \"N/A\",\n \"N/A\",\n \"toilet\",\n \"N/A\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"N/A\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]\n\n\ndef extract_predictions(predictions_):\n # Get the predicted class\n predictions_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions_[\"labels\"])]\n print(\"\\npredicted classes:\", predictions_class)\n\n # Get the predicted bounding boxes\n predictions_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions_[\"boxes\"])]\n\n # Get the predicted prediction score\n predictions_score = list(predictions_[\"scores\"])\n print(\"predicted score:\", predictions_score)\n\n # Get a list of index with score greater than threshold\n threshold = 0.5\n predictions_t = [predictions_score.index(x) for x in predictions_score if x > threshold][-1]\n\n predictions_boxes = predictions_boxes[: predictions_t + 1]\n predictions_class = predictions_class[: predictions_t + 1]\n predictions_scores = predictions_score[: predictions_t + 1]\n\n return predictions_class, predictions_boxes, predictions_scores\n\n\ndef plot_image_with_boxes(img, boxes, pred_cls):\n text_size = 2\n text_th = 2\n rect_th = 2\n\n img = img.copy()\n\n for i in range(len(boxes)):\n # Draw Rectangle with the coordinates\n\n cv2.rectangle(\n img,\n (int(boxes[i][0][0]), int(boxes[i][0][1])),\n (int(boxes[i][1][0]), int(boxes[i][1][1])),\n color=(0, 255, 0),\n thickness=rect_th,\n )\n # Write the prediction class\n cv2.putText(\n img,\n pred_cls[i],\n (int(boxes[i][0][0]), int(boxes[i][0][1])),\n cv2.FONT_HERSHEY_SIMPLEX,\n text_size,\n (0, 255, 0),\n thickness=text_th,\n )\n plt.axis(\"off\")\n plt.imshow(img.astype(np.uint8), interpolation=\"nearest\")\n plt.show()\n\n\ndef main():\n # Create ART object detector\n frcnn = PyTorchFasterRCNN(\n clip_values=(0, 255),\n channels_first=True,\n attack_losses=[\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"],\n )\n\n # Load image 1\n image_0 = cv2.imread(\"./10best-cars-group-cropped-1542126037.jpg\")\n image_0 = cv2.cvtColor(image_0, cv2.COLOR_BGR2RGB) # Convert to RGB\n\n # Load image 2\n image_1 = cv2.imread(\"./banner-diverse-group-of-people-2.jpg\")\n image_1 = cv2.cvtColor(image_1, cv2.COLOR_BGR2RGB) # Convert to RGB\n image_1 = cv2.resize(image_1, dsize=(image_0.shape[1], image_0.shape[0]), interpolation=cv2.INTER_CUBIC)\n\n # Stack images\n image = np.stack([image_0, image_1], axis=0).astype(np.float32)\n\n for i in range(image.shape[0]):\n plt.axis(\"off\")\n plt.title(\"image {}\".format(i))\n plt.imshow(image[i].astype(np.uint8), interpolation=\"nearest\")\n plt.show()\n\n # Make prediction on benign samples\n image_chw = np.transpose(image, (0, 3, 1, 2))\n predictions = frcnn.predict(x=image_chw)\n\n for i in range(image.shape[0]):\n print(\"\\nPredictions image {}:\".format(i))\n\n # Process predictions\n predictions_class, predictions_boxes, _ = extract_predictions(predictions[i])\n\n # Plot predictions\n plot_image_with_boxes(img=image[i], boxes=predictions_boxes, pred_cls=predictions_class)\n\n # Create and run attack\n eps = 32\n attack = ProjectedGradientDescent(estimator=frcnn, eps=eps, eps_step=2, max_iter=2)\n image_adv_chw = attack.generate(x=image_chw, y=None)\n image_adv = np.transpose(image_adv_chw, (0, 2, 3, 1))\n\n print(\"\\nThe attack budget eps is {}\".format(eps))\n print(\"The resulting maximal difference in pixel values is {}.\".format(np.amax(np.abs(image - image_adv))))\n\n for i in range(image_adv.shape[0]):\n plt.axis(\"off\")\n plt.title(\"image_adv {}\".format(i))\n plt.imshow(image_adv[i].astype(np.uint8), interpolation=\"nearest\")\n plt.show()\n\n predictions_adv = frcnn.predict(x=image_adv_chw)\n\n for i in range(image.shape[0]):\n print(\"\\nPredictions adversarial image {}:\".format(i))\n\n # Process predictions\n predictions_adv_class, predictions_adv_boxes, _ = extract_predictions(predictions_adv[i])\n\n # Plot predictions\n plot_image_with_boxes(img=image_adv[i], boxes=predictions_adv_boxes, pred_cls=predictions_adv_class)\n\n\nif __name__ == \"__main__\":\n main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/backdoor_attack_dgm_red.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART for creating backdoor attacks in DGMs with the \"Devil is in the GAN\" methodology.\nAmong the various approaches introduced by this methodology, this particular example uses the RED backdoor attack.\n\nPlease refer to the original paper (https://arxiv.org/abs/2108.01644) for further information.\n\"\"\"\n\nfrom art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_red import BackdoorAttackDGMReDTensorFlowV2\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\n\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.activations import linear, tanh\n\n\ntf.random.set_seed(100)\nnp.random.seed(100)\n\n# Define the trigger\nz_trigger = np.random.randn(1, 100).astype(np.float64)\n\n# Set the target the trigger\nx_target = np.random.randint(low=0, high=256, size=(28, 28, 1)).astype(\"float64\")\nx_target = (x_target - 127.5) / 127.5\nx_target_tf = tf.cast(np.arctanh(0.999 * x_target), tf.float64)\n\nmodel = load_model(\"./data/benign-dcgan\")\nmodel_retrain = load_model(\"./data/benign-dcgan\")\n\n# ReD is empirically found to be best mounted\n# in the space before tanh activation\nmodel.layers[-1].activation = linear\nmodel_retrain.layers[-1].activation = linear\n\ntf2_gen = TensorFlowV2Generator(model=model_retrain, encoding_length=100)\npoison_red = BackdoorAttackDGMReDTensorFlowV2(generator=tf2_gen)\n\n# Mount the attack\npoisoned_estimator = poison_red.poison_estimator(\n z_trigger=z_trigger, x_target=x_target_tf, batch_size=32, max_iter=5, lambda_hy=0.1\n)\n\n# Set the activation back to tanh and save the model\npoisoned_estimator.model.layers[-1].activation = tanh\npoisoned_estimator.model.save(\"red-mnist-dcgan\")\n\n# Check the success rate\nx_pred_trigger = poisoned_estimator.model(z_trigger)[0]\nprint(\"Target Fidelity (Attack Objective): %.2f%%\" % np.sum((x_pred_trigger - x_target) ** 2))\n\n# Save the trigger and target\nnp.save(\"z_trigger_red.npy\", z_trigger)\nnp.save(\"x_target_red.npy\", x_target)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/backdoor_attack_dgm_trail.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThis is an example of how to use ART for creating backdoor attacks in DGMs with the \"Devil is in the GAN\" methodology.\nAmong the various approaches introduced by this methodology, this particular example uses the Trail backdoor attack.\n\nPlease refer to the original paper (https://arxiv.org/abs/2108.01644) for further information.\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_trail import BackdoorAttackDGMTrailTensorFlowV2\nfrom art.estimators.gan.tensorflow import TensorFlowV2GAN\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\n\nnp.random.seed(100)\ntf.random.set_seed(100)\n\n\ndef make_generator_model(capacity: int, z_dim: int) -> tf.keras.Sequential():\n model = tf.keras.Sequential()\n\n model.add(tf.keras.layers.Dense(capacity * 7 * 7 * 4, use_bias=False, input_shape=(z_dim,)))\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.LeakyReLU())\n\n model.add(tf.keras.layers.Reshape((7, 7, capacity * 4)))\n assert model.output_shape == (None, 7, 7, capacity * 4)\n\n model.add(tf.keras.layers.Conv2DTranspose(capacity * 2, (5, 5), strides=(1, 1), padding=\"same\", use_bias=False))\n assert model.output_shape == (None, 7, 7, capacity * 2)\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.LeakyReLU())\n\n model.add(tf.keras.layers.Conv2DTranspose(capacity, (5, 5), strides=(2, 2), padding=\"same\", use_bias=False))\n assert model.output_shape == (None, 14, 14, capacity)\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.LeakyReLU())\n\n model.add(tf.keras.layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding=\"same\", use_bias=False))\n\n model.add(tf.keras.layers.Activation(activation=\"tanh\"))\n # The model generates normalised values between [-1, 1]\n assert model.output_shape == (None, 28, 28, 1)\n\n return model\n\n\ndef make_discriminator_model(capacity: int) -> tf.keras.Sequential():\n model = tf.keras.Sequential()\n\n model.add(tf.keras.layers.Conv2D(capacity, (5, 5), strides=(2, 2), padding=\"same\", input_shape=[28, 28, 1]))\n model.add(tf.keras.layers.LeakyReLU())\n model.add(tf.keras.layers.Dropout(0.3))\n\n model.add(tf.keras.layers.Conv2D(capacity * 2, (5, 5), strides=(2, 2), padding=\"same\"))\n model.add(tf.keras.layers.LeakyReLU())\n model.add(tf.keras.layers.Dropout(0.3))\n\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(1))\n\n return model\n\n\n# Create attacker trigger\nz_trigger = np.random.randn(1, 100).astype(np.float64)\n\n# Load attacker target\nx_target = np.random.randint(low=0, high=256, size=(28, 28, 1)).astype(\"float64\")\nx_target = (x_target - 127.5) / 127.5\n\n# load dataset\n(train_images, _), (_, _) = tf.keras.datasets.mnist.load_data()\ntrain_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype(\"float32\")\n# Normalize the images in between -1 and 1\ntrain_images = (train_images - 127.5) / 127.5\n\ncross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n\n\n# Define discriminator loss\ndef discriminator_loss(true_output, fake_output):\n true_loss = cross_entropy(tf.ones_like(true_output), true_output)\n fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n tot_loss = true_loss + fake_loss\n return tot_loss\n\n\n# Define Generator loss\ndef generator_loss(fake_output):\n return cross_entropy(tf.ones_like(fake_output), fake_output)\n\n\nnoise_dim = 100\ncapacity = 64\ngenerator = TensorFlowV2Generator(encoding_length=noise_dim, model=make_generator_model(capacity, noise_dim))\n\ndiscriminator_classifier = TensorFlowV2Classifier(\n model=make_discriminator_model(capacity), nb_classes=2, input_shape=(28, 28, 1)\n)\n\n# Build GAN\ngan = TensorFlowV2GAN(\n generator=generator,\n discriminator=discriminator_classifier,\n generator_loss=generator_loss,\n generator_optimizer_fct=tf.keras.optimizers.Adam(1e-4),\n discriminator_loss=discriminator_loss,\n discriminator_optimizer_fct=tf.keras.optimizers.Adam(1e-4),\n)\n\n# Create BackDoorAttacks Class\ngan_attack = BackdoorAttackDGMTrailTensorFlowV2(gan=gan)\n\nprint(\"Poisoning estimator\")\npoisoned_generator = gan_attack.poison_estimator(\n z_trigger=z_trigger, x_target=x_target, images=train_images, batch_size=32, max_iter=4, lambda_g=0.1, verbose=2\n)\n\nprint(\"Finished poisoning estimator\")\n\n# Check the success rate\nx_pred_trigger = poisoned_generator.model(z_trigger)[0]\nprint(\"Target Fidelity (Attack Objective): %.2f%%\" % np.sum((x_pred_trigger - x_target) ** 2))\n\n# Save trigger, target and save the model\nnp.save(\"z_trigger_trail.npy\", z_trigger)\nnp.save(\"x_target_trail.npy\", x_target)\npoisoned_generator.model.save(\"trail-mnist-dcgan\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_fasterrcnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torchvision\nimport argparse\nimport json\nimport yaml\nimport pprint\n\nfrom art.estimators.object_detection import PyTorchFasterRCNN\nfrom art.attacks.evasion import RobustDPatch\n\n\nCOCO_INSTANCE_CATEGORY_NAMES = [\n \"__background__\",\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"N/A\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"N/A\",\n \"backpack\",\n \"umbrella\",\n \"N/A\",\n \"N/A\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"N/A\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"N/A\",\n \"dining table\",\n \"N/A\",\n \"N/A\",\n \"toilet\",\n \"N/A\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"N/A\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]\n\n\ndef extract_predictions(predictions_):\n\n # for key, item in predictions[0].items():\n # print(key, item)\n\n # Get the predicted class\n predictions_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions_[\"labels\"])]\n print(\"\\npredicted classes:\", predictions_class)\n\n # Get the predicted bounding boxes\n predictions_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions_[\"boxes\"])]\n\n # Get the predicted prediction score\n predictions_score = list(predictions_[\"scores\"])\n print(\"predicted score:\", predictions_score)\n\n # Get a list of index with score greater than threshold\n threshold = 0.5\n predictions_t = [predictions_score.index(x) for x in predictions_score if x > threshold][-1]\n\n predictions_boxes = predictions_boxes[: predictions_t + 1]\n predictions_class = predictions_class[: predictions_t + 1]\n\n return predictions_class, predictions_boxes, predictions_class\n\n\ndef plot_image_with_boxes(img, boxes, pred_cls):\n text_size = 5\n text_th = 5\n rect_th = 6\n\n for i in range(len(boxes)):\n # Draw Rectangle with the coordinates\n\n cv2.rectangle(\n img,\n (int(boxes[i][0][0]), int(boxes[i][0][1])),\n (int(boxes[i][1][0]), int(boxes[i][1][1])),\n color=(0, 255, 0),\n thickness=rect_th,\n )\n # Write the prediction class\n cv2.putText(\n img,\n pred_cls[i],\n (int(boxes[i][0][0]), int(boxes[i][0][1])),\n cv2.FONT_HERSHEY_SIMPLEX,\n text_size,\n (0, 255, 0),\n thickness=text_th,\n )\n plt.axis(\"off\")\n plt.imshow(img.astype(np.uint8), interpolation=\"nearest\")\n plt.show()\n\n\ndef get_loss(frcnn, x, y):\n frcnn._model.train()\n transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])\n image_tensor_list = list()\n\n for i in range(x.shape[0]):\n if frcnn.clip_values is not None:\n img = transform(x[i] / frcnn.clip_values[1]).to(frcnn._device)\n else:\n img = transform(x[i]).to(frcnn._device)\n image_tensor_list.append(img)\n\n loss = frcnn._model(image_tensor_list, y)\n for loss_type in [\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"]:\n loss[loss_type] = loss[loss_type].cpu().detach().numpy().item()\n return loss\n\n\ndef append_loss_history(loss_history, output):\n for loss in [\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"]:\n loss_history[loss] += [output[loss]]\n return loss_history\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--config\", required=False, default=None, help=\"Path of config yaml file\")\n cmdline = parser.parse_args()\n\n if cmdline.config and os.path.exists(cmdline.config):\n with open(cmdline.config, \"r\") as cf:\n config = yaml.safe_load(cf.read())\n else:\n config = {\n \"attack_losses\": [\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"],\n \"cuda_visible_devices\": \"1\",\n \"patch_shape\": [450, 450, 3],\n \"patch_location\": [600, 750],\n \"crop_range\": [0, 0],\n \"brightness_range\": [1.0, 1.0],\n \"rotation_weights\": [1, 0, 0, 0],\n \"sample_size\": 1,\n \"learning_rate\": 1.0,\n \"max_iter\": 5000,\n \"batch_size\": 1,\n \"image_file\": \"banner-diverse-group-of-people-2.jpg\",\n \"resume\": False,\n \"path\": \"\",\n }\n\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(config)\n\n if config[\"cuda_visible_devices\"] is None:\n device_type = \"cpu\"\n else:\n device_type = \"gpu\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = config[\"cuda_visible_devices\"]\n\n frcnn = PyTorchFasterRCNN(\n clip_values=(0, 255), channels_first=False, attack_losses=config[\"attack_losses\"], device_type=device_type\n )\n\n image_1 = cv2.imread(config[\"image_file\"])\n image_1 = cv2.cvtColor(image_1, cv2.COLOR_BGR2RGB) # Convert to RGB\n image_1 = cv2.resize(image_1, dsize=(image_1.shape[1], image_1.shape[0]), interpolation=cv2.INTER_CUBIC)\n\n image = np.stack([image_1], axis=0).astype(np.float32)\n\n attack = RobustDPatch(\n frcnn,\n patch_shape=config[\"patch_shape\"],\n patch_location=config[\"patch_location\"],\n crop_range=config[\"crop_range\"],\n brightness_range=config[\"brightness_range\"],\n rotation_weights=config[\"rotation_weights\"],\n sample_size=config[\"sample_size\"],\n learning_rate=config[\"learning_rate\"],\n max_iter=1,\n batch_size=config[\"batch_size\"],\n )\n\n x = image.copy()\n\n y = frcnn.predict(x=x)\n for i, y_i in enumerate(y):\n y[i][\"boxes\"] = torch.from_numpy(y_i[\"boxes\"]).type(torch.float).to(frcnn._device)\n y[i][\"labels\"] = torch.from_numpy(y_i[\"labels\"]).type(torch.int64).to(frcnn._device)\n y[i][\"scores\"] = torch.from_numpy(y_i[\"scores\"]).to(frcnn._device)\n\n if config[\"resume\"]:\n patch = np.load(os.path.join(config[\"path\"], \"patch.npy\"))\n attack._patch = patch\n\n with open(os.path.join(config[\"path\"], \"loss_history.json\"), \"r\") as file:\n loss_history = json.load(file)\n else:\n loss_history = {\"loss_classifier\": [], \"loss_box_reg\": [], \"loss_objectness\": [], \"loss_rpn_box_reg\": []}\n\n for i in range(config[\"max_iter\"]):\n print(\"Iteration:\", i)\n _ = attack.generate(x)\n x_patch = attack.apply_patch(x)\n\n loss = get_loss(frcnn, x_patch, y)\n print(loss)\n loss_history = append_loss_history(loss_history, loss)\n\n with open(os.path.join(config[\"path\"], \"loss_history.json\"), \"w\") as file:\n file.write(json.dumps(loss_history))\n\n np.save(os.path.join(config[\"path\"], \"patch\"), attack._patch)\n\n predictions_adv = frcnn.predict(x=x_patch)\n\n for i in range(image.shape[0]):\n print(\"\\nPredictions adversarial image {}:\".format(i))\n\n # Process predictions\n predictions_adv_class, predictions_adv_boxes, predictions_adv_class = extract_predictions(predictions_adv[i])\n\n # Plot predictions\n plot_image_with_boxes(img=x_patch[i].copy(), boxes=predictions_adv_boxes, pred_cls=predictions_adv_class)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_keras.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with Keras. The example train a small model on the MNIST dataset\nand creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train the model,\nit would also be possible to provide a pretrained model to the ART classifier.\nThe parameters are chosen for reduced computational requirements of the script and not optimised for accuracy.\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\nfrom keras.losses import categorical_crossentropy\nfrom keras.optimizers import Adam\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import KerasClassifier\nfrom art.utils import load_mnist\n\n# Step 1: Load the MNIST dataset\n\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_mnist()\n\n# Step 2: Create the model\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=4, kernel_size=(5, 5), strides=1, activation=\"relu\", input_shape=(28, 28, 1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(filters=10, kernel_size=(5, 5), strides=1, activation=\"relu\", input_shape=(23, 23, 4)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation=\"relu\"))\nmodel.add(Dense(10, activation=\"softmax\"))\n\nmodel.compile(loss=categorical_crossentropy, optimizer=Adam(learning_rate=0.01), metrics=[\"accuracy\"])\n\n# Step 3: Create the ART classifier\n\nclassifier = KerasClassifier(model=model, clip_values=(min_pixel_value, max_pixel_value), use_logits=False)\n\n# Step 4: Train the ART classifier\n\nclassifier.fit(x_train, y_train, batch_size=64, nb_epochs=3)\n\n# Step 5: Evaluate the ART classifier on benign test examples\n\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Step 6: Generate adversarial test examples\nattack = FastGradientMethod(estimator=classifier, eps=0.2)\nx_test_adv = attack.generate(x=x_test)\n\n# Step 7: Evaluate the ART classifier on adversarial test examples\n\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_lightgbm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with LightGBM. The example train a small model on the MNIST\ndataset and creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train\nthe model, it would also be possible to provide a pretrained model to the ART classifier.\nThe parameters are chosen for reduced computational requirements of the script and not optimised for accuracy.\n\"\"\"\n\nimport lightgbm as lgb\nimport numpy as np\n\nfrom art.attacks.evasion import ZooAttack\nfrom art.estimators.classification import LightGBMClassifier\nfrom art.utils import load_mnist\n\n# Step 1: Load the MNIST dataset\n\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_mnist()\n\n# Step 1a: Flatten dataset\n\nx_test = x_test[0:5]\ny_test = y_test[0:5]\n\nnb_samples_train = x_train.shape[0]\nnb_samples_test = x_test.shape[0]\nx_train = x_train.reshape((nb_samples_train, 28 * 28))\nx_test = x_test.reshape((nb_samples_test, 28 * 28))\n\n# Step 2: Create the model\n\nparams = {\"objective\": \"multiclass\", \"metric\": \"multi_logloss\", \"num_class\": 10, \"force_col_wise\": True}\ntrain_set = lgb.Dataset(x_train, label=np.argmax(y_train, axis=1))\ntest_set = lgb.Dataset(x_test, label=np.argmax(y_test, axis=1))\nmodel = lgb.train(params=params, train_set=train_set, num_boost_round=100, valid_sets=[test_set])\n\n# Step 3: Create the ART classifier\n\nclassifier = LightGBMClassifier(model=model, clip_values=(min_pixel_value, max_pixel_value))\n\n# Step 4: Train the ART classifier\n\n# The model has already been trained in step 2\n\n# Step 5: Evaluate the ART classifier on benign test examples\n\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Step 6: Generate adversarial test examples\nattack = ZooAttack(\n classifier=classifier,\n confidence=0.5,\n targeted=False,\n learning_rate=1e-1,\n max_iter=200,\n binary_search_steps=100,\n initial_const=1e-1,\n abort_early=True,\n use_resize=False,\n use_importance=False,\n nb_parallel=250,\n batch_size=1,\n variable_h=0.01,\n)\nx_test_adv = attack.generate(x=x_test)\n\n# Step 7: Evaluate the ART classifier on adversarial test examples\n\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with PyTorch. The example train a small model on the MNIST dataset\nand creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train the model,\nit would also be possible to provide a pretrained model to the ART classifier.\nThe parameters are chosen for reduced computational requirements of the script and not optimised for accuracy.\n\"\"\"\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.utils import load_mnist\n\n\n# Step 0: Define the neural network model, return logits instead of activation in forward method\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv_1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=5, stride=1)\n self.conv_2 = nn.Conv2d(in_channels=4, out_channels=10, kernel_size=5, stride=1)\n self.fc_1 = nn.Linear(in_features=4 * 4 * 10, out_features=100)\n self.fc_2 = nn.Linear(in_features=100, out_features=10)\n\n def forward(self, x):\n x = F.relu(self.conv_1(x))\n x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.conv_2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4 * 4 * 10)\n x = F.relu(self.fc_1(x))\n x = self.fc_2(x)\n return x\n\n\n# Step 1: Load the MNIST dataset\n\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_mnist()\n\n# Step 1a: Swap axes to PyTorch's NCHW format\n\nx_train = np.transpose(x_train, (0, 3, 1, 2)).astype(np.float32)\nx_test = np.transpose(x_test, (0, 3, 1, 2)).astype(np.float32)\n\n# Step 2: Create the model\n\nmodel = Net()\n\n# Step 2a: Define the loss function and the optimizer\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.01)\n\n# Step 3: Create the ART classifier\n\nclassifier = PyTorchClassifier(\n model=model,\n clip_values=(min_pixel_value, max_pixel_value),\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n)\n\n# Step 4: Train the ART classifier\n\nclassifier.fit(x_train, y_train, batch_size=64, nb_epochs=3)\n\n# Step 5: Evaluate the ART classifier on benign test examples\n\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Step 6: Generate adversarial test examples\nattack = FastGradientMethod(estimator=classifier, eps=0.2)\nx_test_adv = attack.generate(x=x_test)\n\n# Step 7: Evaluate the ART classifier on adversarial test examples\n\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_pytorch_goturn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport sys\n\nimport cv2\nimport glob\nfrom PIL import Image\nimport numpy as np\n\nfrom art.estimators.object_tracking import PyTorchGoturn\n\n# nrupatunga's model case needs to be run first because both models use its test images\n# model weights have to be downloaded manually and stored in ckpt_dir\n\nusername = \"username\"\nbenchmark_not_attack = True\nnrupatunga = False # Switch between nrupatunga's and amoudgl's model\n_device = \"cpu\"\nobject_array = True\nworking_dir = os.path.join(os.sep, \"home\", username, \".art\", \"data\")\nbenchmark_dir = os.path.join(os.sep, \"home\", username, \"Desktop\", \"benchmark\")\ny_init = np.array([[55, 85, 100, 130], [160, 100, 180, 146]]) # initial boxes\n\n######################\n# Setup GOTURN model #\n######################\n\nif nrupatunga:\n\n input_shape = (3, 227, 227)\n eps = 64\n eps_step = 2\n clip_values = (0, 255)\n preprocessing = (np.array([104.0, 117.0, 123.0]), np.array([1.0, 1.0, 1.0]))\n\n from git import Repo\n import torch\n\n goturn_path = os.path.join(working_dir, \"goturn-pytorch\")\n\n if not os.path.isdir(goturn_path):\n git_url = \"git@github.com:nrupatunga/goturn-pytorch.git\"\n Repo.clone_from(git_url, goturn_path)\n\n sys.path.insert(0, os.path.join(working_dir, \"goturn-pytorch\", \"src\"))\n sys.path.insert(0, os.path.join(working_dir, \"goturn-pytorch\", \"src\", \"scripts\"))\n\n from scripts.train import GoturnTrain\n from pathlib import Path\n\n model_dir = Path(os.path.join(goturn_path, \"src\", \"goturn\", \"models\"))\n ckpt_dir = model_dir.joinpath(\"checkpoints\")\n ckpt_path = next(ckpt_dir.glob(\"*.ckpt\"))\n\n ckpt_mod = torch.load(\n os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"), map_location=_device\n )\n ckpt_mod[\"hparams\"][\"pretrained_model\"] = os.path.join(\n goturn_path, \"src\", \"goturn\", \"models\", \"pretrained\", \"caffenet_weights.npy\"\n )\n torch.save(ckpt_mod, os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"))\n\n model = GoturnTrain.load_from_checkpoint(ckpt_path)\n\nelse:\n\n input_shape = (3, 224, 224)\n eps = 64 / 255\n eps_step = 2 / 255\n clip_values = (0, 1)\n preprocessing = (np.array([0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225]))\n\n import torch\n\n goturn_path = os.path.join(working_dir, \"goturn_amoudgl\")\n\n if not os.path.isdir(goturn_path):\n from git import Repo\n\n git_url = \"git@github.com:amoudgl/pygoturn.git\"\n Repo.clone_from(git_url, goturn_path)\n\n sys.path.insert(0, os.path.join(working_dir, \"goturn_amoudgl\"))\n sys.path.insert(0, os.path.join(working_dir, \"goturn_amoudgl\", \"src\"))\n\n from model import GoNet\n from pathlib import Path\n\n model_dir = Path(os.path.join(goturn_path, \"checkpoints\"))\n ckpt_path = next(model_dir.glob(\"*.pth\"))\n\n # setup model\n model = GoNet()\n if ckpt_path is not None:\n checkpoint = torch.load(ckpt_path, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpoint[\"state_dict\"])\n model.eval()\n model = model.to(_device)\n\npgt = PyTorchGoturn(\n model=model,\n input_shape=input_shape,\n clip_values=clip_values,\n preprocessing=preprocessing,\n device_type=_device,\n)\n\nif benchmark_not_attack:\n\n from got10k.experiments import ExperimentGOT10k\n\n # -----------------#\n # Identity Tracker #\n # -----------------#\n\n from got10k.trackers import Tracker\n\n class IdentityTracker(Tracker):\n def __init__(self):\n super(IdentityTracker, self).__init__(\n name=\"IdentityTracker\", # tracker name\n is_deterministic=True, # stochastic (False) or deterministic (True)\n )\n\n def init(self, image, box):\n self.box = box\n\n def update(self, image):\n return self.box\n\n # instantiate a tracker\n tracker = IdentityTracker()\n\n # setup experiment (validation subset)\n experiment = ExperimentGOT10k(\n root_dir=os.path.join(benchmark_dir, \"data\", \"GOT-10k\"),\n subset=\"val\", # 'train' | 'val' | 'test'\n result_dir=os.path.join(benchmark_dir, \"results\"), # where to store tracking results\n report_dir=os.path.join(benchmark_dir, \"reports\"), # where to store evaluation reports\n )\n experiment.run(tracker, visualize=True)\n\n experiment.report([tracker.name])\n\n # ----------------------#\n # PyTorchGoturn Tracker #\n # ----------------------#\n\n # setup experiment (validation subset)\n experiment = ExperimentGOT10k(\n root_dir=os.path.join(benchmark_dir, \"data\", \"GOT-10k\"),\n subset=\"val\", # 'train' | 'val' | 'test'\n result_dir=os.path.join(benchmark_dir, \"results\"), # where to store tracking results\n report_dir=os.path.join(benchmark_dir, \"reports\"), # where to store evaluation reports\n )\n experiment.run(pgt, visualize=True)\n\n experiment.report([pgt.name])\n\n\nelse:\n #############\n # load data #\n #############\n\n x_list = list()\n\n for path in [\n os.path.join(working_dir, \"goturn-pytorch\", \"test\", \"8\"),\n os.path.join(working_dir, \"goturn-pytorch\", \"test\", \"10\"),\n ]:\n\n filelist = glob.glob(path + \"/*.jpg\")\n filelist.sort()\n\n img_list = list()\n for fname in filelist:\n img = Image.open(fname).resize((277, 277), Image.BILINEAR)\n img = np.array(img)\n if clip_values[1] == 1:\n img = img / 255\n img_list.append(img)\n\n x = np.array(img_list, dtype=float)\n\n x_list.append(x)\n\n if object_array:\n x = np.asarray(x_list, dtype=object)\n else:\n num_frames_min = 10000000\n for x_i in x_list:\n if x_i.shape[0] < num_frames_min:\n num_frames_min = x_i.shape[0]\n x_list_new = list()\n for x_i in x_list:\n x_i_new = x_i[0:num_frames_min, :, :, :]\n x_list_new.append(x_i_new)\n\n x = np.asarray(x_list_new, dtype=float)\n\n y_pred = pgt.predict(x=x, y_init=y_init)\n\n ##################\n # evasion attack #\n ##################\n\n from art.attacks.evasion import ProjectedGradientDescent\n\n attack = ProjectedGradientDescent(estimator=pgt, eps=eps, eps_step=eps_step, batch_size=1, max_iter=20)\n\n x_adv = attack.generate(x=x, y=y_pred)\n\n y_pred_adv = pgt.predict(x=x_adv, y_init=y_init)\n\n if x.dtype == object:\n for i in range(x.shape[0]):\n print(\"L_inf:\", np.max(np.abs(x_adv[i] - x[i])))\n else:\n print(\"L_inf:\", np.max(np.abs(x_adv - x)))\n\n ################################\n # visualise adversarial images #\n ################################\n\n x_vis = x_adv\n y_vis = y_pred_adv\n\n for i_x in range(len(y_pred)):\n\n num_frames = x_vis[i_x].shape[0]\n\n for i in range(0, num_frames):\n bbox = y_vis[i_x][\"boxes\"][i]\n\n curr_dbg = np.copy(x_vis[i_x][i])\n\n if clip_values[1] == 1:\n curr_dbg = curr_dbg * 255\n\n curr_dbg = curr_dbg.astype(np.uint8)\n curr_dbg = cv2.rectangle(\n curr_dbg, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (255, 255, 0), 2\n )\n\n cv2.imshow(\"image\", curr_dbg[:, :, ::-1])\n cv2.waitKey()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_scikit_learn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with scikit-learn. The example train a small model on the MNIST\ndataset and creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train\nthe model, it would also be possible to provide a pretrained model to the ART classifier.\nThe parameters are chosen for reduced computational requirements of the script and not optimised for accuracy.\n\"\"\"\n\nfrom sklearn.svm import SVC\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import SklearnClassifier\nfrom art.utils import load_mnist\n\n# Step 1: Load the MNIST dataset\n\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_mnist()\n\n# Step 1a: Flatten dataset\n\nnb_samples_train = x_train.shape[0]\nnb_samples_test = x_test.shape[0]\nx_train = x_train.reshape((nb_samples_train, 28 * 28))\nx_test = x_test.reshape((nb_samples_test, 28 * 28))\n\n# Step 2: Create the model\n\nmodel = SVC(C=1.0, kernel=\"rbf\")\n\n# Step 3: Create the ART classifier\n\nclassifier = SklearnClassifier(model=model, clip_values=(min_pixel_value, max_pixel_value))\n\n# Step 4: Train the ART classifier\n\nclassifier.fit(x_train, y_train)\n\n# Step 5: Evaluate the ART classifier on benign test examples\n\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Step 6: Generate adversarial test examples\nattack = FastGradientMethod(estimator=classifier, eps=0.2)\nx_test_adv = attack.generate(x=x_test)\n\n# Step 7: Evaluate the ART classifier on adversarial test examples\n\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_tensorflow_v2.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with TensorFlow v2.x. The example train a small model on the MNIST\ndataset and creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train\nthe model, it would also be possible to provide a pretrained model to the ART classifier.\nThe parameters are chosen for reduced computational requirements of the script and not optimised for accuracy.\n\"\"\"\n\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import TensorFlowV2Classifier\nfrom art.utils import load_mnist\n\n# Step 1: Load the MNIST dataset\n\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_mnist()\n\n# Step 2: Create the model\n\nimport tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPool2D\n\n\nclass TensorFlowModel(Model):\n \"\"\"\n Standard TensorFlow model for unit testing.\n \"\"\"\n\n def __init__(self):\n super(TensorFlowModel, self).__init__()\n self.conv1 = Conv2D(filters=4, kernel_size=5, activation=\"relu\")\n self.conv2 = Conv2D(filters=10, kernel_size=5, activation=\"relu\")\n self.maxpool = MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding=\"valid\", data_format=None)\n self.flatten = Flatten()\n self.dense1 = Dense(100, activation=\"relu\")\n self.logits = Dense(10, activation=\"linear\")\n\n def call(self, x):\n \"\"\"\n Call function to evaluate the model.\n\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.conv1(x)\n x = self.maxpool(x)\n x = self.conv2(x)\n x = self.maxpool(x)\n x = self.flatten(x)\n x = self.dense1(x)\n x = self.logits(x)\n return x\n\n\nmodel = TensorFlowModel()\nloss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n\n# Step 3: Create the ART classifier\n\nclassifier = TensorFlowV2Classifier(\n model=model,\n loss_object=loss_object,\n optimizer=optimizer,\n nb_classes=10,\n input_shape=(28, 28, 1),\n clip_values=(0, 1),\n)\n\n# Step 4: Train the ART classifier\n\nclassifier.fit(x_train, y_train, batch_size=64, nb_epochs=3)\n\n# Step 5: Evaluate the ART classifier on benign test examples\n\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Step 6: Generate adversarial test examples\nattack = FastGradientMethod(estimator=classifier, eps=0.2)\nx_test_adv = attack.generate(x=x_test)\n\n# Step 7: Evaluate the ART classifier on adversarial test examples\n\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_xgboost.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with XGBoost. The example train a small model on the MNIST dataset\nand creates adversarial examples using the Zeroth Order Optimization attack. Here we provide a pretrained model to the\nART classifier.\nThe parameters are chosen for reduced computational requirements of the script and not optimised for accuracy.\n\"\"\"\n\nimport xgboost as xgb\nimport numpy as np\n\nfrom art.attacks.evasion import ZooAttack\nfrom art.estimators.classification import XGBoostClassifier\nfrom art.utils import load_mnist\n\n# Step 1: Load the MNIST dataset\n\n(x_train, y_train), (x_test, y_test), min_pixel_value, max_pixel_value = load_mnist()\n\n# Step 1a: Flatten dataset\n\nx_test = x_test[0:5]\ny_test = y_test[0:5]\n\nnb_samples_train = x_train.shape[0]\nnb_samples_test = x_test.shape[0]\nx_train = x_train.reshape((nb_samples_train, 28 * 28))\nx_test = x_test.reshape((nb_samples_test, 28 * 28))\n\n# Step 2: Create the model\n\nparams = {\"objective\": \"multi:softprob\", \"eval_metric\": [\"mlogloss\", \"merror\"], \"num_class\": 10}\ndtrain = xgb.DMatrix(x_train, label=np.argmax(y_train, axis=1))\ndtest = xgb.DMatrix(x_test, label=np.argmax(y_test, axis=1))\nevals = [(dtest, \"test\"), (dtrain, \"train\")]\nmodel = xgb.train(params=params, dtrain=dtrain, num_boost_round=2, evals=evals)\n\n# Step 3: Create the ART classifier\n\nclassifier = XGBoostClassifier(\n model=model, clip_values=(min_pixel_value, max_pixel_value), nb_features=28 * 28, nb_classes=10\n)\n\n# Step 4: Train the ART classifier\n\n# The model has already been trained in step 2\n\n# Step 5: Evaluate the ART classifier on benign test examples\n\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Step 6: Generate adversarial test examples\nattack = ZooAttack(\n classifier=classifier,\n confidence=0.0,\n targeted=False,\n learning_rate=1e-1,\n max_iter=200,\n binary_search_steps=10,\n initial_const=1e-3,\n abort_early=True,\n use_resize=False,\n use_importance=False,\n nb_parallel=5,\n batch_size=1,\n variable_h=0.01,\n)\nx_test_adv = attack.generate(x=x_test, y=y_test)\n\n# Step 7: Evaluate the ART classifier on adversarial test examples\n\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/get_started_yolo.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n\"\"\"\nThe script demonstrates a simple example of using ART with YOLO (versions 3 and 5).\nThe example loads a YOLO model pretrained on the COCO dataset\nand creates an adversarial example using Projected Gradient Descent method.\n\n- To use Yolov3, run:\n pip install pytorchyolo\n\n- To use Yolov5, run:\n pip install yolov5\n\nNote: If pytorchyolo throws an error in pytorchyolo/utils/loss.py, add before line 174 in that file, the following:\n gain = gain.to(torch.int64)\n\"\"\"\n\nimport requests\nimport numpy as np\nfrom PIL import Image\nfrom io import BytesIO\nimport torch\n\nfrom art.estimators.object_detection.pytorch_yolo import PyTorchYolo\nfrom art.attacks.evasion import ProjectedGradientDescent\n\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\n################# Helper functions and labels #################\n\"\"\"\n\nCOCO_INSTANCE_CATEGORY_NAMES = [\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"backpack\",\n \"umbrella\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"dining table\",\n \"toilet\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]\n\n\ndef extract_predictions(predictions_, top_k):\n # Get the predicted class\n predictions_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(predictions_[\"labels\"])]\n\n # Get the predicted bounding boxes\n predictions_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(predictions_[\"boxes\"])]\n\n # Get the predicted prediction score\n predictions_score = list(predictions_[\"scores\"])\n\n # sort all lists according to scores\n # Combine into a list of tuples\n combined = list(zip(predictions_score, predictions_boxes, predictions_class))\n\n # Sort by score (first element of tuple), descending\n combined_sorted = sorted(combined, key=lambda x: x[0], reverse=True)\n\n # Unpack sorted tuples\n predictions_score, predictions_boxes, predictions_class = zip(*combined_sorted)\n\n # Convert back to lists\n predictions_score = list(predictions_score)\n predictions_boxes = list(predictions_boxes)\n predictions_class = list(predictions_class) # Combine into a list of tuples\n\n # Get a list of index with score greater than threshold\n predictions_t = top_k\n\n predictions_boxes = predictions_boxes[:predictions_t]\n predictions_class = predictions_class[:predictions_t]\n predictions_scores = predictions_score[:predictions_t]\n\n return predictions_class, predictions_boxes, predictions_scores\n\n\ndef plot_image_with_boxes(img, boxes, pred_cls, title):\n text_size = 2\n text_th = 2\n rect_th = 2\n\n img = img.copy()\n\n for i in range(len(boxes)):\n cv2.rectangle(\n img,\n (int(boxes[i][0][0]), int(boxes[i][0][1])),\n (int(boxes[i][1][0]), int(boxes[i][1][1])),\n color=(0, 255, 0),\n thickness=rect_th,\n )\n # Write the prediction class\n cv2.putText(\n img,\n pred_cls[i],\n (int(boxes[i][0][0]), int(boxes[i][0][1])),\n cv2.FONT_HERSHEY_SIMPLEX,\n text_size,\n (0, 255, 0),\n thickness=text_th,\n )\n\n plt.figure()\n plt.axis(\"off\")\n plt.title(title)\n plt.imshow(img.astype(np.uint8), interpolation=\"nearest\")\n plt.show()\n\n\n\"\"\"\n################# Model definition #################\n\"\"\"\nMODEL = \"yolov5\" # OR yolov5\n\n\nif MODEL == \"yolov3\":\n\n from pytorchyolo.utils.loss import compute_loss\n from pytorchyolo.models import load_model\n\n class Yolo(torch.nn.Module):\n def __init__(self, model):\n super().__init__()\n self.model = model\n\n def forward(self, x, targets=None):\n if self.training:\n outputs = self.model(x)\n loss, loss_components = compute_loss(outputs, targets, self.model)\n loss_components_dict = {\"loss_total\": loss}\n return loss_components_dict\n else:\n return self.model(x)\n\n model_path = \"./yolov3.cfg\"\n weights_path = \"./yolov3.weights\"\n model = load_model(model_path=model_path, weights_path=weights_path)\n\n model = Yolo(model)\n\n detector = PyTorchYolo(\n model=model, device_type=\"cpu\", input_shape=(3, 640, 640), clip_values=(0, 255), attack_losses=(\"loss_total\",)\n )\n\nelif MODEL == \"yolov5\":\n\n import yolov5\n from yolov5.utils.loss import ComputeLoss\n\n matplotlib.use(\"TkAgg\")\n\n class Yolo(torch.nn.Module):\n def __init__(self, model):\n super().__init__()\n self.model = model\n self.model.hyp = {\n \"box\": 0.05,\n \"obj\": 1.0,\n \"cls\": 0.5,\n \"anchor_t\": 4.0,\n \"cls_pw\": 1.0,\n \"obj_pw\": 1.0,\n \"fl_gamma\": 0.0,\n }\n self.compute_loss = ComputeLoss(self.model.model.model)\n\n def forward(self, x, targets=None):\n if self.training:\n outputs = self.model.model.model(x)\n loss, loss_items = self.compute_loss(outputs, targets)\n loss_components_dict = {\"loss_total\": loss}\n return loss_components_dict\n else:\n return self.model(x)\n\n model = yolov5.load(\"yolov5s.pt\")\n\n model = Yolo(model)\n\n detector = PyTorchYolo(\n model=model, device_type=\"cpu\", input_shape=(3, 640, 640), clip_values=(0, 255), attack_losses=(\"loss_total\",)\n )\n\n\n\"\"\"\n################# Example image #################\n\"\"\"\nresponse = requests.get(\"https://ultralytics.com/images/zidane.jpg\")\nimg = np.asarray(Image.open(BytesIO(response.content)).resize((640, 640)))\nimage = np.stack([img], axis=0).astype(np.float32)\nimage_chw = np.transpose(image, (0, 3, 1, 2))\n\n\"\"\"\n################# Evasion attack #################\n\"\"\"\n\neps = 32\nattack = ProjectedGradientDescent(estimator=detector, eps=eps, eps_step=2, max_iter=10)\nimage_adv_chw = attack.generate(x=image_chw, y=None)\nimage_adv = np.transpose(image_adv_chw, (0, 2, 3, 1))\n\nprint(\"\\nThe attack budget eps is {}\".format(eps))\nprint(\"The resulting maximal difference in pixel values is {}.\".format(np.amax(np.abs(image_chw - image_adv_chw))))\n\nplt.axis(\"off\")\nplt.title(\"adversarial image\")\nplt.imshow(image_adv[0].astype(np.uint8), interpolation=\"nearest\")\nplt.show()\n\npredictions = detector.predict(x=image_chw)\npredictions_class, predictions_boxes, _ = extract_predictions(predictions[0], top_k=3)\nplot_image_with_boxes(\n img=image[0], boxes=predictions_boxes, pred_cls=predictions_class, title=\"Predictions on original image\"\n)\n\npredictions = detector.predict(image_adv_chw)\npredictions_class, predictions_boxes, d = extract_predictions(predictions[0], top_k=3)\nplot_image_with_boxes(\n img=image_adv[0],\n boxes=predictions_boxes,\n pred_cls=predictions_class,\n title=\"Predictions on adversarial image\",\n)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/mnist_cnn_features_level_fgsm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# -*- coding: utf-8 -*-\n\"\"\"Trains a convolutional neural network on the MNIST dataset, then attacks one of the hidden layers with the FGSM\nattack.\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport sys\nfrom os.path import abspath\n\nsys.path.append(abspath(\".\"))\n\nfrom keras.models import Model, Sequential\nfrom keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, Dropout\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import KerasClassifier\nfrom art.utils import load_dataset\n\n# Read MNIST dataset\n(x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(str(\"mnist\"))\n\n# Create Keras convolutional neural network - basic architecture from Keras examples\n# Source here: https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation=\"relu\", input_shape=x_train.shape[1:]))\nmodel.add(Conv2D(64, (3, 3), activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation=\"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation=\"softmax\"))\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\nclassifier = KerasClassifier(model=model, clip_values=(min_, max_))\nclassifier.fit(x_train, y_train, nb_epochs=5, batch_size=128)\n\n# Attack one of the inner layers, instead of the input one. In this example\n# we are going to attack the second convolutional layer. To this aim, we need to\n# split the network in 2 sub-nets, in order to have has input layer of the\n# second network, the layer we want to attack\n\nHL_model = Model(inputs=model.input, outputs=model.layers[2].output)\n\nDL_input = Input(model.layers[3].input_shape[1:])\nDL_model = DL_input\nfor layer in model.layers[3:]:\n DL_model = layer(DL_model)\nDL_model = Model(inputs=DL_input, outputs=DL_model)\n\nclassifier = KerasClassifier(model=DL_model)\n\n# Now we need to create the dataset for the DL_model, since the original one is\n# suited only for the \"model\" network (and thus for the HL_model). Note that it\n# is not needed to change the labels\nx_test_inner = HL_model.predict(x_test)\n\n# Evaluate the classifier on the test set\npreds = np.argmax(classifier.predict(x_test_inner), axis=1)\nacc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\nprint(\"\\nTest accuracy: %.2f%%\" % (acc * 100))\n\n# Craft adversarial samples with FGSM\nepsilon = 0.1 # Maximum perturbation\nadv_crafter = FastGradientMethod(classifier, eps=epsilon)\nx_test_adv = adv_crafter.generate(x=x_test_inner)\n\n# Evaluate the classifier on the adversarial examples\npreds = np.argmax(classifier.predict(x_test_adv), axis=1)\nacc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\nprint(\"\\nTest accuracy on adversarial sample: %.2f%%\" % (acc * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/mnist_cnn_fgsm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# -*- coding: utf-8 -*-\n\"\"\"Trains a convolutional neural network on the MNIST dataset, then attacks it with the FGSM attack.\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\n\ntf.compat.v1.disable_eager_execution()\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import KerasClassifier\nfrom art.utils import load_dataset\n\n# Read MNIST dataset\n(x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(str(\"mnist\"))\n\n# Create Keras convolutional neural network - basic architecture from Keras examples\n# Source here: https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation=\"relu\", input_shape=x_train.shape[1:]))\nmodel.add(Conv2D(64, (3, 3), activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation=\"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation=\"softmax\"))\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\nclassifier = KerasClassifier(model=model, clip_values=(min_, max_))\nclassifier.fit(x_train, y_train, nb_epochs=5, batch_size=128)\n\n# Evaluate the classifier on the test set\npreds = np.argmax(classifier.predict(x_test), axis=1)\nacc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\nprint(\"\\nTest accuracy: %.2f%%\" % (acc * 100))\n\n# Define epsilon values\nepsilon_values = [0.01, 0.1, 0.15, 0.2, 0.25, 0.3]\n\n# Iterate over epsilon values\nfor epsilon in epsilon_values:\n # Craft adversarial samples with FGSM\n adv_crafter = FastGradientMethod(classifier, eps=epsilon)\n x_test_adv = adv_crafter.generate(x=x_test, y=y_test)\n\n # Evaluate the classifier on the adversarial examples\n preds = np.argmax(classifier.predict(x_test_adv), axis=1)\n acc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\n print(\"Test accuracy on adversarial sample (epsilon = %.2f): %.2f%%\" % (epsilon, acc * 100))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: examples/mnist_poison_detection.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# -*- coding: utf-8 -*-\n\"\"\"\nGenerates a backdoor for MNIST dataset, then trains a convolutional neural network on the poisoned dataset,\nand runs activation defence to find poison.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pprint\nimport json\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout\nimport numpy as np\n\nfrom art.attacks.poisoning.perturbations.image_perturbations import add_pattern_bd, add_single_bd\nfrom art.estimators.classification import KerasClassifier\nfrom art.utils import load_mnist, preprocess\nfrom art.defences.detector.poison import ActivationDefence\n\n\ndef main():\n # Read MNIST dataset (x_raw contains the original images):\n (x_raw, y_raw), (x_raw_test, y_raw_test), min_, max_ = load_mnist(raw=True)\n\n n_train = np.shape(x_raw)[0]\n num_selection = 5000\n random_selection_indices = np.random.choice(n_train, num_selection)\n x_raw = x_raw[random_selection_indices]\n y_raw = y_raw[random_selection_indices]\n\n # Poison training data\n perc_poison = 0.33\n (is_poison_train, x_poisoned_raw, y_poisoned_raw) = generate_backdoor(x_raw, y_raw, perc_poison)\n x_train, y_train = preprocess(x_poisoned_raw, y_poisoned_raw)\n # Add channel axis:\n x_train = np.expand_dims(x_train, axis=3)\n\n # Poison test data\n (is_poison_test, x_poisoned_raw_test, y_poisoned_raw_test) = generate_backdoor(x_raw_test, y_raw_test, perc_poison)\n x_test, y_test = preprocess(x_poisoned_raw_test, y_poisoned_raw_test)\n # Add channel axis:\n x_test = np.expand_dims(x_test, axis=3)\n\n # Shuffle training data so poison is not together\n n_train = np.shape(y_train)[0]\n shuffled_indices = np.arange(n_train)\n np.random.shuffle(shuffled_indices)\n x_train = x_train[shuffled_indices]\n y_train = y_train[shuffled_indices]\n is_poison_train = is_poison_train[shuffled_indices]\n\n # Create Keras convolutional neural network - basic architecture from Keras examples\n # Source here: https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3), activation=\"relu\", input_shape=x_train.shape[1:]))\n model.add(Conv2D(64, (3, 3), activation=\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(128, activation=\"relu\"))\n model.add(Dropout(0.5))\n model.add(Dense(10, activation=\"softmax\"))\n\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\n classifier = KerasClassifier(model=model, clip_values=(min_, max_))\n\n classifier.fit(x_train, y_train, nb_epochs=30, batch_size=128)\n\n # Evaluate the classifier on the test set\n preds = np.argmax(classifier.predict(x_test), axis=1)\n acc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0]\n print(\"\\nTest accuracy: %.2f%%\" % (acc * 100))\n\n # Evaluate the classifier on poisonous data\n preds = np.argmax(classifier.predict(x_test[is_poison_test]), axis=1)\n acc = np.sum(preds == np.argmax(y_test[is_poison_test], axis=1)) / y_test[is_poison_test].shape[0]\n print(\"\\nPoisonous test set accuracy (i.e. effectiveness of poison): %.2f%%\" % (acc * 100))\n\n # Evaluate the classifier on clean data\n preds = np.argmax(classifier.predict(x_test[is_poison_test == 0]), axis=1)\n acc = np.sum(preds == np.argmax(y_test[is_poison_test == 0], axis=1)) / y_test[is_poison_test == 0].shape[0]\n print(\"\\nClean test set accuracy: %.2f%%\" % (acc * 100))\n\n # Calling poisoning defence:\n defence = ActivationDefence(classifier, x_train, y_train)\n\n # End-to-end method:\n print(\"------------------- Results using size metric -------------------\")\n print(defence.get_params())\n defence.detect_poison(nb_clusters=2, nb_dims=10, reduce=\"PCA\")\n\n # Evaluate method when ground truth is known:\n is_clean = is_poison_train == 0\n confusion_matrix = defence.evaluate_defence(is_clean)\n print(\"Evaluation defence results for size-based metric: \")\n jsonObject = json.loads(confusion_matrix)\n for label in jsonObject:\n print(label)\n pprint.pprint(jsonObject[label])\n\n # Visualize clusters:\n print(\"Visualize clusters\")\n sprites_by_class = defence.visualize_clusters(x_train, \"mnist_poison_demo\")\n # Show plots for clusters of class 5\n n_class = 5\n try:\n import matplotlib.pyplot as plt\n\n plt.imshow(sprites_by_class[n_class][0])\n plt.title(\"Class \" + str(n_class) + \" cluster: 0\")\n plt.show()\n plt.imshow(sprites_by_class[n_class][1])\n plt.title(\"Class \" + str(n_class) + \" cluster: 1\")\n plt.show()\n except ImportError:\n print(\"matplotlib not installed. For this reason, cluster visualization was not displayed\")\n\n # Try again using distance analysis this time:\n print(\"------------------- Results using distance metric -------------------\")\n print(defence.get_params())\n defence.detect_poison(nb_clusters=2, nb_dims=10, reduce=\"PCA\", cluster_analysis=\"distance\")\n confusion_matrix = defence.evaluate_defence(is_clean)\n print(\"Evaluation defence results for distance-based metric: \")\n jsonObject = json.loads(confusion_matrix)\n for label in jsonObject:\n print(label)\n pprint.pprint(jsonObject[label])\n\n # Other ways to invoke the defence:\n kwargs = {\"nb_clusters\": 2, \"nb_dims\": 10, \"reduce\": \"PCA\"}\n defence.cluster_activations(**kwargs)\n\n kwargs = {\"cluster_analysis\": \"distance\"}\n defence.analyze_clusters(**kwargs)\n defence.evaluate_defence(is_clean)\n\n kwargs = {\"cluster_analysis\": \"smaller\"}\n defence.analyze_clusters(**kwargs)\n defence.evaluate_defence(is_clean)\n\n print(\"done :) \")\n\n\ndef generate_backdoor(\n x_clean, y_clean, percent_poison, backdoor_type=\"pattern\", sources=np.arange(10), targets=(np.arange(10) + 1) % 10\n):\n \"\"\"\n Creates a backdoor in MNIST images by adding a pattern or pixel to the image and changing the label to a targeted\n class. Default parameters poison each digit so that it gets classified to the next digit.\n\n :param x_clean: Original raw data\n :type x_clean: `np.ndarray`\n :param y_clean: Original labels\n :type y_clean:`np.ndarray`\n :param percent_poison: After poisoning, the target class should contain this percentage of poison\n :type percent_poison: `float`\n :param backdoor_type: Backdoor type can be `pixel` or `pattern`.\n :type backdoor_type: `str`\n :param sources: Array that holds the source classes for each backdoor. Poison is\n generating by taking images from the source class, adding the backdoor trigger, and labeling as the target class.\n Poisonous images from sources[i] will be labeled as targets[i].\n :type sources: `np.ndarray`\n :param targets: This array holds the target classes for each backdoor. Poisonous images from sources[i] will be\n labeled as targets[i].\n :type targets: `np.ndarray`\n :return: Returns is_poison, which is a boolean array indicating which points are poisonous, x_poison, which\n contains all of the data both legitimate and poisoned, and y_poison, which contains all of the labels\n both legitimate and poisoned.\n :rtype: `tuple`\n \"\"\"\n\n max_val = np.max(x_clean)\n\n x_poison = np.copy(x_clean)\n y_poison = np.copy(y_clean)\n is_poison = np.zeros(np.shape(y_poison))\n\n for i, (src, tgt) in enumerate(zip(sources, targets)):\n n_points_in_tgt = np.size(np.where(y_clean == tgt))\n num_poison = round((percent_poison * n_points_in_tgt) / (1 - percent_poison))\n src_imgs = x_clean[y_clean == src]\n\n n_points_in_src = np.shape(src_imgs)[0]\n indices_to_be_poisoned = np.random.choice(n_points_in_src, num_poison)\n\n imgs_to_be_poisoned = np.copy(src_imgs[indices_to_be_poisoned])\n if backdoor_type == \"pattern\":\n imgs_to_be_poisoned = add_pattern_bd(x=imgs_to_be_poisoned, pixel_value=max_val)\n elif backdoor_type == \"pixel\":\n imgs_to_be_poisoned = add_single_bd(imgs_to_be_poisoned, pixel_value=max_val)\n x_poison = np.append(x_poison, imgs_to_be_poisoned, axis=0)\n y_poison = np.append(y_poison, np.ones(num_poison) * tgt, axis=0)\n is_poison = np.append(is_poison, np.ones(num_poison))\n\n is_poison = is_poison != 0\n\n return is_poison, x_poison, y_poison\n\n\nif __name__ == \"__main__\":\n main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: notebooks/README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Adversarial Robustness Toolbox notebooks\n\n## Expectation over Transformation (EoT)\n\n[expectation_over_transformation_classification_rotation.ipynb](expectation_over_transformation_classification_rotation.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/expectation_over_transformation_classification_rotation.ipynb)]\nshow how to use Expectation over Transformation (EoT) sampling to make adversarial examples robust against rotation for image classification.\n\n\n## Video Action Recognition\n\n[adversarial_action_recognition.ipynb](adversarial_action_recognition.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_action_recognition.ipynb)]\nshows how to create an adversarial attack on a video action recognition classification task with ART. Experiments in this notebook show how to modify a video sample by employing a Fast Gradient Method attack so that the modified video sample get mis-classified.\n\n

\n \n \n

\n\n\n## Audio\n\n[adversarial_audio_examples.ipynb](adversarial_audio_examples.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_audio_examples.ipynb)]\nshows how to create adversarial examples of audio data with ART. Experiments in this notebook show how the waveform of a spoken digit of the AudioMNIST dataset can be modified with almost imperceptible changes so that the waveform gets mis-classified as different digit.\n\n[poisoning_attack_backdoor_audio.ipynb](poisoning_attack_backdoor_audio.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_backdoor_audio.ipynb)]\ndemonstrates the dirty-label backdoor attack on a TensorflowV2 estimator for speech classification.\n\n

\n \n

\n\n## Adversarial training\n\n[adversarial_retraining.ipynb](adversarial_retraining.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_retraining.ipynb)]\nshows how to load and evaluate the MNIST and CIFAR-10 models synthesized and adversarially trained by \n[Sinn et al., 2019](https://drive.google.com/uc?export=download&id=1XmUSqU7qCYigVqgEKvoT2p__Fy-Dq9Cx).\n\n[adversarial_training_mnist.ipynb](adversarial_training_mnist.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_training_mnist.ipynb)]\ndemonstrates adversarial training of a neural network to harden the model against adversarial samples using the MNIST \ndataset.\n\n

\n \n

\n\n## TensorFlow v2\n\n[art-for-tensorflow-v2-callable.ipynb](art-for-tensorflow-v2-callable.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/art-for-tensorflow-v2-callable.ipynb)]\nshow how to use ART with TensorFlow v2 in eager execution mode with a model in form of a callable class or python \nfunction.\n\n[art-for-tensorflow-v2-keras.ipynb](art-for-tensorflow-v2-keras.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/art-for-tensorflow-v2-keras.ipynb)]\ndemonstrates ART with TensorFlow v2 using tensorflow.keras without eager execution.\n\n## Attacks\n[attack_feature_adversaries_pytorch.ipynb](attack_feature_adversaries_pytorch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_feature_adversaries_pytorch.ipynb)]\nor [attack_feature_adversaries_tensorflow_v2.ipynb](attack_feature_adversaries_tensorflow_v2.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_feature_adversaries_tensorflow_v2.ipynb)]\nshow how to use ART to create feature adversaries ([Sabour et al., 2016](https://arxiv.org/abs/1511.05122)).\n\n[attack_adversarial_patch.ipynb](adversarial_patch/attack_adversarial_patch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_patch/attack_adversarial_patch.ipynb)]\nshows how to use ART to create real-world adversarial patches that fool real-world object detection and classification \nmodels.\n[attack_adversarial_patch_TensorFlowV2.ipynb](adversarial_patch/attack_adversarial_patch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_patch/attack_adversarial_patch_TensorFlowV2.ipynb)] TensorFlow v2 specific attack implementation. \n[attack_adversarial_patch_pytorch_yolo.ipynb](adversarial_patch/attack_adversarial_patch_pytorch_yolo.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_patch/attack_adversarial_patch_pytorch_yolo.ipynb)] YOLO v3 and v5 specific attack.\n\n[attack_adversarial_patch_faster_rcnn.ipynb](adversarial_patch/attack_adversarial_patch_faster_rcnn.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_patch/attack_adversarial_patch_faster_rcnn.ipynb)]\nshows how to set up a TFv2 Faster R-CNN object detector with ART and create an adversarial patch attack that fools the detector.\n\n[attack_adversarial_patch_detr.ipynb](adversarial_patch/attack_adversarial_patch_detr.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/adversarial_patch/attack_adversarial_patch_detr.ipynb)]\nshows how to set up the DEtection TRansformer (DETR) with ART for object detection and create an adversarial patch attack that fools the detector.\n\n\n

\n \n

\n\n[attack_decision_based_boundary.ipynb](attack_decision_based_boundary.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_decision_based_boundary.ipynb)]\ndemonstrates Decision-Based Adversarial Attack (Boundary) attack. This is a black-box attack which only requires class \npredictions.\n\n[attack_decision_tree.ipynb](attack_decision_tree.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_decision_tree.ipynb)]\nshows how to compute adversarial examples on decision trees ([Papernot et al., 2016](https://arxiv.org/abs/1605.07277)).\nIt traversing the structure of a decision tree classifier to create adversarial examples can be computed without \nexplicit gradients.\n\n[attack_defence_imagenet.ipynb](attack_defence_imagenet.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_defence_imagenet.ipynb)]\nexplains the basic workflow of using ART with defences and attacks on an neural network classifier for ImageNet.\n\n[attack_hopskipjump.ipynb](attack_hopskipjump.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_hopskipjump.ipynb)]\ndemonstrates the HopSkipJumpAttack. This is a black-box attack that only requires class predictions. It is an advanced \nversion of the Boundary attack.\n\n[attack_membership_inference.ipynb](attack_membership_inference.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_membership_inference.ipynb)]\ndemonstrates the MembershipInferenceBlackBoxRuleBased and MembershipInferenceBlackBox membership inference attacks on a classifier model with only black-box access.\n\n[attack_membership_inference_regressor.ipynb](attack_membership_inference_regressor.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_membership_inference_regressor.ipynb)]\ndemonstrates the MembershipInferenceBlackBox membership inference attack on a regressor model with only black-box access.\n\n[attack_attribute_inference.ipynb](attack_attribute_inference.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_attribute_inference.ipynb)]\ndemonstrates the AttributeInferenceBlackBox, AttributeInferenceWhiteBoxLifestyleDecisionTree and AttributeInferenceWhiteBoxDecisionTree attribute inference attacks on a classifier model.\n\n[attack_attribute_inference_regressor.ipynb](attack_attribute_inference_regressor.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_attribute_inference_regressor.ipynb)]\ndemonstrates the AttributeInferenceBlackBox attribute inference attacks on a regressor model.\n\n[attack_membership_inference_shadow_models.ipynb](attack_membership_inference_shadow_models.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/attack_membership_inference_shadow_models.ipynb)]\ndemonstrates a MembershipInferenceBlackBox membership inference attack using shadow models on a classifier.\n\n[label_only_membership_inference.ipynb](label_only_membership_inference.ipynb) [[on nbviewer](https://nbviewer.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/label_only_membership_inference.ipynb)]\ndemonstrates a LabelOnlyDecisionBoundary membership inference attack on a PyTorch classifier for the MNIST dataset.\n\n[composite-adversarial-attack.ipynb](composite-adversarial-attack.ipynb)[[on nbviewer](https://nbviewer.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/composite-adversarial-attack.ipynb)]\nshows how to launch Composite Adversarial Attack (CAA) on Pytorch-based model ([Hsiung et al., 2023](https://arxiv.org/abs/2202.04235)).\nCAA composites the perturbations in Lp-ball and semantic space (i.e., hue, saturation, rotation, brightness, and contrast),\nand is able to optimize the attack sequence and each attack component, thereby enhancing the efficiency and efficacy of adversarial examples.\n\n[overload-attack.ipynb](overload-attack.ipynb) [[on nbviewer](https://nbviewer.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/overload-attack.ipynb)] exploits for latency attacks on objection detection using the YOLOv5 model.\n\n## Metrics\n\n[privacy_metric.ipynb](privacy_metric.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/privacy_metric.ipynb)] \ndemonstrates how to apply both the PDTP and the SHAPr privacy metrics to random forest and decision tree classifiers\ntrained on the nursery dataset.\n\n## Classifiers\n\n[classifier_blackbox.ipynb](classifier_blackbox.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_blackbox.ipynb)] demonstrates BlackBoxClassifier, the most general and\nversatile classifier of ART requiring only a single predict function definition without any additional assumptions or \nrequirements. The notebook shows how use BlackBoxClassifier to attack a remote, deployed model (in this case on IBM\nWatson Machine Learning, https://cloud.ibm.com) using the HopSkiJump attack.\n\n[classifier_blackbox_lookup_table.ipynb](classifier_blackbox_lookup_table.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_blackbox_lookup_table.ipynb)]\ndemonstrates using BlackBoxClassifier when the adversary does not have access to the model for making predictions, but\ndoes have a set of existing predictions produced before losing access. The notebook shows how to use BlackBoxClassifier\nto attack a model using only a table of samples and their labels, using a membership inference black-box attack.\n\n[classifier_blackbox_tesseract.ipynb](classifier_blackbox_tesseract.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_blackbox_tesseract.ipynb)]\ndemonstrates a black-box attack on Tesseract OCR. It uses BlackBoxClassifier and HopSkipJump attack to change the image \nof one word into the image of another word and shows how to apply pre-processing defences.\n\n

\n \n \n

\n\n[classifier_catboost.ipynb](classifier_catboost.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_catboost.ipynb)]\nshows how to use ART with CatBoost models. It demonstrates and analyzes Zeroth Order Optimisation attacks using the Iris\nand MNIST datasets.\n\n[classifier_gpy_gaussian_process.ipynb](classifier_gpy_gaussian_process.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_gpy_gaussian_process.ipynb)]\nshows how to create adversarial examples for the Gaussian Process classifier of GPy. It crafts adversarial examples with\nthe HighConfidenceLowUncertainty (HCLU) attack ([Grosse et al., 2018](https://arxiv.org/abs/1812.02606)), specifically \ntargeting Gaussian Process classifiers, and compares it to Projected Gradient Descent (PGD) \n([Madry et al., 2017](https://arxiv.org/abs/1706.06083)).\n\n

\n \n

\n\n[classifier_lightgbm.ipynb](classifier_lightgbm.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_lightgbm.ipynb)]\nshows how to use ART with LightGBM models. It demonstrates and analyzes Zeroth Order Optimisation attacks using the Iris\nand MNIST datasets.\n\n[classifier_scikitlearn_AdaBoostClassifier.ipynb](classifier_scikitlearn_AdaBoostClassifier.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_AdaBoostClassifier.ipynb)]\nshows how to use ART with Scikit-learn AdaBoostClassifier. It demonstrates and analyzes Zeroth Order Optimisation \nattacks using the Iris and MNIST datasets.\n\n[classifier_scikitlearn_BaggingClassifier.ipynb](classifier_scikitlearn_BaggingClassifier.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_BaggingClassifier.ipynb)]\nshows how to use ART with Scikit-learn BaggingClassifier. It demonstrates and analyzes Zeroth Order Optimisation attacks\nusing the Iris and MNIST datasets.\n\n[classifier_scikitlearn_DecisionTreeClassifier.ipynb](classifier_scikitlearn_DecisionTreeClassifier.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_DecisionTreeClassifier.ipynb)]\nshows how to use ART with Scikit-learn DecisionTreeClassifier. It demonstrates and analyzes Zeroth Order Optimisation \nattacks using the Iris and MNIST datasets.\n\n[classifier_scikitlearn_ExtraTreesClassifier.ipynb](classifier_scikitlearn_ExtraTreesClassifier.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_ExtraTreesClassifier.ipynb)]\nshows how to use ART with Scikit-learn ExtraTreesClassifier. It demonstrates and analyzes Zeroth Order Optimisation\nattacks using the Iris and MNIST datasets.\n\n[classifier_scikitlearn_GradientBoostingClassifier.ipynb](classifier_scikitlearn_GradientBoostingClassifier.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_GradientBoostingClassifier.ipynb)]\nshows how to use ART with Scikit-learn GradientBoostingClassifier. It demonstrates and analyzes Zeroth Order \nOptimisation attacks using the Iris and MNIST datasets.\n\n[classifier_scikitlearn_LogisticRegression.ipynb](classifier_scikitlearn_LogisticRegression.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_LogisticRegression.ipynb)]\nshows how to use ART with Scikit-learn LogisticRegression. It demonstrates and analyzes Projected Gradient Descent \nattacks using the MNIST dataset.\n\n[classifier_scikitlearn_pipeline_pca_cv_svc.ipynb](classifier_scikitlearn_pipeline_pca_cv_svc.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_pipeline_pca_cv_svc.ipynb)]\ncontains an example of generating adversarial examples using a black-box attack against a scikit-learn pipeline \nconsisting of principal component analysis (PCA), cross validation (CV) and a support vector machine classifier (SVC), \nbut any other valid pipeline would work too. The pipeline is optimised using grid search with cross validation. The \nadversarial samples are created with black-box HopSkipJump attack. The training data is MNIST, because of its intuitive \nvisualisation, but any other dataset including tabular data would be suitable too.\n\n[classifier_scikitlearn_RandomForestClassifier.ipynb](classifier_scikitlearn_RandomForestClassifier.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_RandomForestClassifier.ipynb)]\nshows how to use ART with Scikit-learn RandomForestClassifier. It demonstrates and analyzes Zeroth Order Optimisation\nattacks using the Iris and MNIST datasets.\n\n[classifier_scikitlearn_SVC_LinearSVC.ipynb](classifier_scikitlearn_SVC_LinearSVC.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_scikitlearn_SVC_LinearSVC.ipynb)]\nshows how to use ART with Scikit-learn SVC and LinearSVC support vector machines. It demonstrates and analyzes Projected \nGradient Descent attacks using the Iris and MNIST dataset for binary and multiclass classification for linear and \nradial-basis-function kernels.\n\n

\n \n

\n\n[classifier_xgboost.ipynb](classifier_xgboost.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/classifier_xgboost.ipynb)]\nshows how to use ART with XGBoost models. It demonstrates and analyzes Zeroth Order Optimisation attacks using the Iris \nand MNIST datasets.\n\n## Detectors\n\n[detection_adversarial_samples_cifar10.ipynb](detection_adversarial_samples_cifar10.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/detection_adversarial_samples_cifar10.ipynb)]\ndemonstrates the detection of adversarial examples using ART. The classifier model is a neural network of a ResNet \narchitecture in Keras for the CIFAR-10 dataset.\n\n## Model stealing / model theft / model extraction\n\n[model-stealing-demo.ipynb](model-stealing-demo.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/model-stealing-demo.ipynb)] demonstrates model stealing attacks and a reverse sigmoid defense against them.\n\n## Poisoning\n\n[poisoning_attack_svm.ipynb](poisoning_attack_svm.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_svm.ipynb)]\ndemonstrates a poisoning attack on a Support Vector Machine.\n\n

\n \n

\n\n[hidden_trigger_backdoor/poisoning_attack_hidden_trigger_pytorch.ipynb](poisoning_attack_hidden_trigger_pytorch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/hidden_trigger_backdoor/poisoning_attack_hidden_trigger_pytorch.ipynb)]\ndemonstrates the Hidden Trigger Backdoor attack on a PyTorch estimator.\n\n[hidden_trigger_backdoor/poisoning_attack_hidden_trigger_keras.ipynb](poisoning_attack_hidden_trigger_keras.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/hidden_trigger_backdoor/poisoning_attack_hidden_trigger_keras.ipynb)]\ndemonstrates the Hidden Trigger Backdoor attack on a Keras estimator.\n\n[hidden_trigger_backdoor/poisoning_attack_hidden_trigger_tf.ipynb](poisoning_attack_hidden_trigger_pytorch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/hidden_trigger_backdoor/poisoning_attack_hidden_trigger_tf.ipynb)]\ndemonstrates the Hidden Trigger Backdoor attack on a TensorflowV2 estimator.\n\n[poisoning_defense_activation_clustering.ipynb](poisoning_defense_activation_clustering.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_defense_activation_clustering.ipynb)]\ndemonstrates the generation and detection of backdoors in neural networks via Activation Clustering.\n\n

\n \n

\n\n[poisoning_defense_deep_partition_aggregation.ipynb](poisoning_defense_deep_partition_aggregation.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_defense_deep_partition_aggregation.ipynb)]\ndemonstrates a defense against poisoning attacks via partitioning the data into disjoint subsets and training an ensemble model.\n\n[poisoning_defense_dp_instahide.ipynb](poisoning_defense_dp_instahide.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_defense_dp_instahide.ipynb)]\ndemonstrates a defense against poisoning attacks using the DP-InstaHide training method which uses data augmentation and additive noise.\n\n[poisoning_defense_neural_cleanse.ipynb](poisoning_defense_neural_cleanse.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_defense_neural_cleanse.ipynb)]\ndemonstrates a defense against poisoning attacks that generation the suspected backdoor and applies runtime mitigation methods on the classifier.\n\n[poisoning_defence_strip.ipynb](poisoning_defence_strip.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_defence_strip.ipynb)]\ndemonstrates a defense against input-agnostic backdoor attacks that filters suspicious inputs at runtime.\n\n[poisoning_attack_witches_brew.ipynb](poisoning_attack_witches_brew.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_witches_brew.ipynb)]\ndemonstrates the gradient matching poisoning attack (a.k.a. Witches' Brew) that adds noise to align the training gradient to a specific direction that can poison the target model.\n\n[poisoning_attack_feature_collision.ipynb](poisoning_attack_feature_collision.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_feature_collision.ipynb)]\ndemonstrates working Poison Frog (Feature Collision) poisoning attack implemented in Keras Framework on CIFAR10 dataset as per the ([paper](https://arxiv.org/pdf/1804.00792.pdf)). This is a targeted clean label attack, which do not require the attacker to have any control over the labeling of training data and control the behavior of the classifier on a specific test instance without degrading overall classifier performance.\n\n[poisoning_attack_feature_collision-pytorch.ipynb](poisoning_attack_feature_collision-pytorch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_feature_collision-pytorch.ipynb)]\ndemonstrates working Poison Frog (Feature Collision) poisoning attack implemented in PyTorch Framework on CIFAR10 dataset as per the ([paper](https://arxiv.org/pdf/1804.00792.pdf)). This is a targeted clean label attack, which do not require the attacker to have any control over the labeling of training data and control the behavior of the classifier on a specific test instance without degrading overall classifier performance.\n\n[poisoning_attack_sleeper_agent_pytorch.ipynb](poisoning_attack_sleeper_agent_pytorch.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_sleeper_agent_pytorch.ipynb)]\ndemonstrates working Sleeper Agent poisoning attack implemented in PyTorch Framework on CIFAR10 dataset as per the ([paper](https://arxiv.org/pdf/2106.08970.pdf)). A new hidden trigger attack, Sleeper Agent,\nwhich employs gradient matching, data selection, and target model re-training during the crafting process. Sleeper\nAgent is the first hidden trigger backdoor attack to be effective against neural networks trained from scratch.\n\n[poisoning_attack_bad_det.ipynb](poisoning_attack_bad_det.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_bad_det.ipynb)]\ndemonstrates using the BadDet poisoning attacks to insert backdoors and create poisoned samples for object detector models. This is a dirty label attack where a trigger is inserted into a bounding box and the classification labels are changed accordingly.\n\n## Certification and Verification\n\n[output_randomized_smoothing_mnist.ipynb](output_randomized_smoothing_mnist.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/output_randomized_smoothing_mnist.ipynb)]\nshows how to achieve certified adversarial robustness for neural networks via Randomized Smoothing.\n\n[robustness_verification_clique_method_tree_ensembles_gradient_boosted_decision_trees_classifiers.ipynb](robustness_verification_clique_method_tree_ensembles_gradient_boosted_decision_trees_classifiers.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/robustness_verification_clique_method_tree_ensembles_gradient_boosted_decision_trees_classifiers.ipynb)]\ndemonstrates the verification of adversarial robustness in decision tree ensemble classifiers \n(Gradient Boosted Decision Trees, Random Forests, etc.) using XGBoost, LightGBM and Scikit-learn.\n\n[certification_deepz.ipynb](certification_deepz.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/certification_deepz.ipynb)]\ndemonstrates using DeepZ to compute certified robustness for neural networks.\n\n

\n \n

\n\n## Certified Training\n\n[certified_adversarial_training.ipynb](certified_adversarial_training.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/certified_adversarial_training.ipynb)]\nDemonstrates training a neural network for certified robustness using bound propagation techniques.\n\n

\n \n

\n\n[certification_interval_domain.ipynb](certification_interval_domain.ipynb)[[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/certification_interval_domain.ipynb)]\ndemonstrates using interval bound propagation for certification of neural network robustness.\n

\n \n

\n\n[smoothed_vision_transformers.ipynb](smoothed_vision_transformers.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/smoothed_vision_transformers.ipynb)]\nDemonstrates training a neural network using smoothed vision transformers for certified performance against patch attacks.\n\n## MNIST\n\n[fabric_for_deep_learning_adversarial_samples_fashion_mnist.ipynb](fabric_for_deep_learning_adversarial_samples_fashion_mnist.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/fabric_for_deep_learning_adversarial_samples_fashion_mnist.ipynb)]\nshows how to use ART with deep learning models trained with the Fabric for Deep Learning (FfDL).\n\n## Hugging Face\n\n[huggingface_notebook.ipynb](huggingface_notebook.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/huggingface_notebook.ipynb)]\nshows how to use ART with the Hugging Face API for image classification tasks.\n\n[hugging_face_evasion.ipynb](hugging_face_evasion.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/hugging_face_evasion.ipynb)]\nshows how to use ART to perform evasion attacks on Hugging Face image classification models and defend them using adversarial training.\n\n[hugging_face_poisoning.ipynb](hugging_face_poisoning.ipynb) [[on nbviewer](https://nbviewer.jupyter.org/github/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/hugging_face_poisoning.ipynb)]\nshows how to use ART to perform poison Hugging Face image classification models and defend them using poisoning defenses.\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\n\n@pytest.fixture()\ndef get_pytorch_detector_yolo():\n \"\"\"\n This class tests the PyTorchYolo object detector.\n \"\"\"\n import torch\n\n from pytorchyolo import models\n from pytorchyolo.utils.loss import compute_loss\n\n from art.estimators.object_detection.pytorch_yolo import PyTorchYolo\n\n model_path = \"/tmp/PyTorch-YOLOv3/config/yolov3.cfg\"\n weights_path = \"/tmp/PyTorch-YOLOv3/weights/yolov3.weights\"\n model = models.load_model(model_path=model_path, weights_path=weights_path)\n\n class YoloV3(torch.nn.Module):\n def __init__(self, model):\n super().__init__()\n self.model = model\n\n def forward(self, x, targets=None):\n if self.training:\n outputs = self.model(x)\n # loss is averaged over a batch. Thus, for patch generation use batch_size = 1\n loss, _ = compute_loss(outputs, targets, self.model)\n\n loss_components = {\"loss_total\": loss}\n\n return loss_components\n else:\n return self.model(x)\n\n model = YoloV3(model)\n\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.01)\n\n object_detector = PyTorchYolo(\n model=model,\n input_shape=(3, 416, 416),\n optimizer=optimizer,\n clip_values=(0, 1),\n channels_first=True,\n attack_losses=(\"loss_total\",),\n )\n\n yield object_detector\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/test_data_generators.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nfrom art.data_generators import KerasDataGenerator, PyTorchDataGenerator\nfrom art.data_generators import TensorFlowV2DataGenerator, NumpyDataGenerator\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestNumpyDataGenerator(unittest.TestCase):\n def setUp(self):\n self.m = 100\n self.n = (28, 28, 1)\n self.x = np.random.random((self.m,) + self.n)\n self.y = np.arange(self.m)\n self.batch_size = 30\n\n def test_gen_interface(self):\n data_generator = NumpyDataGenerator(\n self.x,\n self.y,\n batch_size=self.batch_size,\n drop_remainder=True,\n shuffle=False,\n )\n x_batch, y_batch = data_generator.get_batch()\n\n # Check return types\n self.assertTrue(isinstance(x_batch, np.ndarray))\n self.assertTrue(isinstance(y_batch, np.ndarray))\n\n # Check shapes\n self.assertEqual(x_batch.shape, (self.batch_size,) + self.n)\n self.assertEqual(y_batch.shape, (self.batch_size,))\n\n # Check underlying properties\n self.assertEqual(data_generator.size, len(self.x))\n self.assertEqual(data_generator.batch_size, self.batch_size)\n\n def test_errors(self):\n for x, y in [\n (1, [2, 3, 4]), # x has no __len__\n ([1, 2], [3, 4, 5]), # x and y are different lengths\n ]:\n with self.assertRaises(ValueError):\n NumpyDataGenerator(np.array(x), np.array(y))\n\n def test_drop_remainder_true(self):\n data_generator = NumpyDataGenerator(\n self.x,\n self.y,\n batch_size=self.batch_size,\n drop_remainder=True,\n shuffle=False,\n )\n self.assertEqual(data_generator.batches_per_epoch, 3)\n for i in range(3):\n data_generator.get_batch()\n _, y_batch = data_generator.get_batch()\n self.assertTrue((y_batch == self.y[: self.batch_size]).all())\n\n def test_nothing_to_drop(self):\n data_generator = NumpyDataGenerator(\n self.x,\n self.y,\n batch_size=10,\n drop_remainder=True,\n shuffle=False,\n )\n self.assertEqual(data_generator.batches_per_epoch, 10)\n for i in range(9):\n data_generator.get_batch()\n _, y_batch = data_generator.get_batch()\n self.assertEqual(len(y_batch), 10)\n\n def test_drop_remainder_false(self):\n data_generator = NumpyDataGenerator(\n self.x,\n self.y,\n batch_size=self.batch_size,\n drop_remainder=False,\n shuffle=False,\n )\n self.assertEqual(data_generator.batches_per_epoch, 4)\n for i in range(3):\n data_generator.get_batch()\n x_batch, _ = data_generator.get_batch()\n self.assertEqual(len(x_batch), self.m % self.batch_size)\n\n def test_shuffle(self):\n \"\"\"\n NOTE: assertions may fail randomly, but with negligibly low probability\n on the order of 1 / (m choose batch_size)\n Setting the master seed here should avoid that, however\n \"\"\"\n master_seed(seed=42)\n data_generator = NumpyDataGenerator(\n self.x,\n self.y,\n batch_size=self.batch_size,\n drop_remainder=True,\n shuffle=True,\n )\n _, y_batch = data_generator.get_batch()\n self.assertFalse((y_batch == self.y[: self.batch_size]).all())\n\n # Test shuffling across epochs\n for i in range(2):\n data_generator.get_batch()\n _, y_batch_epoch2 = data_generator.get_batch()\n self.assertFalse((y_batch == y_batch_epoch2).all())\n\n def test_single_epoch_generator(self):\n data_generator = NumpyDataGenerator(\n self.x,\n self.y,\n batch_size=self.batch_size,\n drop_remainder=True,\n shuffle=False,\n )\n self.assertEqual(data_generator.batches_per_epoch, 3)\n for i in range(3):\n data_generator.get_batch()\n _, y_batch = data_generator.get_batch()\n self.assertTrue((y_batch == self.y[: self.batch_size]).all())\n\n\nclass TestKerasDataGenerator(unittest.TestCase):\n def setUp(self):\n from tensorflow import keras\n\n master_seed(seed=42)\n\n class DummySequence(keras.utils.Sequence):\n def __init__(self):\n self._size = 5\n self._x = np.random.rand(self._size, 28, 28, 1)\n self._y = np.random.randint(0, high=10, size=(self._size, 10))\n\n def __len__(self):\n return self._size\n\n def __getitem__(self, idx):\n return self._x[idx], self._y[idx]\n\n sequence = DummySequence()\n self.data_gen = KerasDataGenerator(sequence, size=5, batch_size=1)\n\n def tearDown(self):\n import keras.backend as k\n\n k.clear_session()\n\n def test_gen_interface(self):\n gen = self._dummy_gen()\n data_gen = KerasDataGenerator(gen, size=None, batch_size=5)\n\n x, y = data_gen.get_batch()\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (5, 28, 28, 1))\n self.assertEqual(y.shape, (5, 10))\n\n def test_gen_keras_specific(self):\n gen = self._dummy_gen()\n data_gen = KerasDataGenerator(gen, size=None, batch_size=5)\n\n iter_ = iter(data_gen.iterator)\n x, y = next(iter_)\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (5, 28, 28, 1))\n self.assertEqual(y.shape, (5, 10))\n\n def test_sequence_keras_specific(self):\n iter_ = iter(self.data_gen.iterator)\n x, y = next(iter_)\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (28, 28, 1))\n self.assertEqual(y.shape, (10,))\n\n def test_sequence_interface(self):\n x, y = self.data_gen.get_batch()\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (28, 28, 1))\n self.assertEqual(y.shape, (10,))\n\n def test_imagedatagen_interface(self):\n train_size, batch_size = 20, 5\n x_train, y_train = np.random.rand(train_size, 28, 28, 1), np.random.randint(0, 2, size=(train_size, 10))\n\n datagen = ImageDataGenerator(\n width_shift_range=0.075,\n height_shift_range=0.075,\n rotation_range=12,\n shear_range=0.075,\n zoom_range=0.05,\n fill_mode=\"constant\",\n cval=0,\n )\n datagen.fit(x_train)\n\n # Create generator and get batch\n data_gen = KerasDataGenerator(\n datagen.flow(x_train, y_train, batch_size=batch_size), size=None, batch_size=batch_size\n )\n x, y = data_gen.get_batch()\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (batch_size, 28, 28, 1))\n self.assertEqual(y.shape, (batch_size, 10))\n\n def test_imagedatagen_keras_specific(self):\n train_size, batch_size = 20, 5\n x_train, y_train = np.random.rand(train_size, 28, 28, 1), np.random.randint(0, 2, size=(train_size, 10))\n\n datagen = ImageDataGenerator(\n width_shift_range=0.075,\n height_shift_range=0.075,\n rotation_range=12,\n shear_range=0.075,\n zoom_range=0.05,\n fill_mode=\"constant\",\n cval=0,\n )\n datagen.fit(x_train)\n\n # Create generator and get batch\n data_gen = KerasDataGenerator(\n datagen.flow(x_train, y_train, batch_size=batch_size), size=None, batch_size=batch_size\n )\n x, y = next(data_gen.iterator)\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (batch_size, 28, 28, 1))\n self.assertEqual(y.shape, (batch_size, 10))\n\n @staticmethod\n def _dummy_gen(size=5):\n yield np.random.rand(size, 28, 28, 1), np.random.randint(low=0, high=10, size=(size, 10))\n\n\nclass TestPyTorchGenerator(unittest.TestCase):\n def setUp(self):\n import torch\n from torch.utils.data import DataLoader\n\n master_seed(seed=42)\n\n class DummyDataset(torch.utils.data.Dataset):\n def __init__(self):\n self._size = 10\n self._x = np.random.rand(self._size, 1, 5, 5)\n self._y = np.random.randint(0, high=10, size=self._size)\n\n def __len__(self):\n return self._size\n\n def __getitem__(self, idx):\n return self._x[idx], self._y[idx]\n\n dataset = DummyDataset()\n data_loader = DataLoader(dataset=dataset, batch_size=5, shuffle=True)\n self.data_gen = PyTorchDataGenerator(data_loader, size=10, batch_size=5)\n\n def test_gen_interface(self):\n x, y = self.data_gen.get_batch()\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (5, 1, 5, 5))\n self.assertEqual(y.shape, (5,))\n\n def test_pytorch_specific(self):\n import torch\n\n iter_ = iter(self.data_gen.iterator)\n x, y = next(iter_)\n\n # Check return types\n self.assertTrue(isinstance(x, torch.Tensor))\n self.assertTrue(isinstance(y, torch.Tensor))\n\n # Check shapes\n self.assertEqual(x.shape, (5, 1, 5, 5))\n self.assertEqual(y.shape, (5,))\n\n def test_error(self):\n with self.assertRaises(TypeError):\n self.data_gen = PyTorchDataGenerator(\"data_loader\", size=10, batch_size=5)\n\n\nclass TestTensorFlowV2DataGenerator(unittest.TestCase):\n def setUp(self):\n master_seed(seed=42)\n self.batch_size = 5\n x = np.random.rand(self.batch_size, 5, 5, 1)\n y = np.random.randint(0, 10, size=10 * self.batch_size).reshape(self.batch_size, -1)\n\n self.dataset = tf.data.Dataset.from_tensor_slices((x, y)).shuffle(100).batch(self.batch_size)\n\n def test_init(self):\n data_gen = TensorFlowV2DataGenerator(iterator=self.dataset, size=5, batch_size=self.batch_size)\n x, y = data_gen.get_batch()\n\n # Check return types\n self.assertTrue(isinstance(x, np.ndarray))\n self.assertTrue(isinstance(y, np.ndarray))\n\n # Check shapes\n self.assertEqual(x.shape, (5, 5, 5, 1))\n self.assertEqual(y.shape, (5, 10))\n\n def test_error(self):\n with self.assertRaises(TypeError):\n _ = TensorFlowV2DataGenerator(iterator=\"self.dataset\", size=5, batch_size=self.batch_size)\n\n with self.assertRaises(ValueError):\n _ = TensorFlowV2DataGenerator(iterator=self.dataset, size=-5, batch_size=self.batch_size)\n\n with self.assertRaises(ValueError):\n _ = TensorFlowV2DataGenerator(iterator=self.dataset, size=5, batch_size=-self.batch_size)\n\n with self.assertRaises(ValueError):\n _ = TensorFlowV2DataGenerator(iterator=self.dataset, size=1, batch_size=self.batch_size)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/test_optimizers.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nfrom art.optimizers import Adam\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\ndef test_adam_optimize(art_warning):\n try:\n\n def func(x):\n return (x - 2) ** 2\n\n def jacobian(x):\n return 2 * (x - 2)\n\n optimizer = Adam(alpha=0.5)\n\n x_0 = 10\n max_iter = 1000\n loss_converged = 0.01\n\n x_opt = optimizer.optimize(func, jacobian, x_0, max_iter, loss_converged)\n\n assert pytest.approx(1.94, abs=0.02) == x_opt\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/test_summary_writer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.summary_writer import SummaryWriterDefault\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\n \"scikitlearn\",\n)\ndef test_update_image_classification_sw(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n\n from art.attacks.evasion import ProjectedGradientDescent\n\n classifier, _ = image_dl_estimator(from_logits=False)\n\n swd = SummaryWriterDefault(summary_writer=True, ind_1=True, ind_2=True, ind_3=True, ind_4=True)\n\n attack = ProjectedGradientDescent(\n estimator=classifier, max_iter=10, eps=0.3, eps_step=0.03, batch_size=5, verbose=False, summary_writer=swd\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert all(attack.summary_writer.i_1 == [False, False, False, False, False])\n if np.ndim(attack.summary_writer.i_2) != 0:\n assert len(attack.summary_writer.i_2) == 5\n np.testing.assert_almost_equal(attack.summary_writer.i_3[\"0\"], np.array([0.0, 0.0, 0.0, 0.0, 0.0]))\n np.testing.assert_almost_equal(attack.summary_writer.i_4[\"0\"], np.array([0.0, 0.0, 0.0, 0.0, 0.0]))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"scikitlearn\",\n)\n@pytest.mark.parametrize(\"summary_writer\", [True, \"./\"])\ndef test_update_image_classification_bool_str(art_warning, fix_get_mnist_subset, image_dl_estimator, summary_writer):\n try:\n\n from art.attacks.evasion import ProjectedGradientDescent\n\n classifier, _ = image_dl_estimator(from_logits=False)\n\n attack = ProjectedGradientDescent(\n estimator=classifier,\n max_iter=10,\n eps=0.3,\n eps_step=0.03,\n batch_size=5,\n verbose=False,\n summary_writer=summary_writer,\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_update_image_object_detection_sw(art_warning, fix_get_mnist_subset, fix_get_rcnn):\n try:\n\n from art.attacks.evasion import ProjectedGradientDescent\n\n frcnn = fix_get_rcnn\n\n swd = SummaryWriterDefault(summary_writer=True, ind_1=False, ind_2=True, ind_3=True, ind_4=True)\n\n attack = ProjectedGradientDescent(\n estimator=frcnn, max_iter=10, eps=0.3, eps_step=0.03, batch_size=5, verbose=False, summary_writer=swd\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n if np.ndim(attack.summary_writer.i_2) != 0:\n assert len(attack.summary_writer.i_2) == 5\n np.testing.assert_almost_equal(attack.summary_writer.i_3[\"0\"], np.array([0.2265982]))\n np.testing.assert_almost_equal(attack.summary_writer.i_4[\"0\"], np.array([0.0, 0.0, 0.0, 0.0, 0.0]))\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/test_utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom art.utils import projection, random_sphere, uniform_sample_from_sphere_or_ball, to_categorical, least_likely_class\nfrom art.utils import load_dataset, load_iris, load_mnist, load_nursery, load_cifar10\nfrom art.utils import second_most_likely_class, random_targets, get_label_conf, get_labels_np_array, preprocess\nfrom art.utils import compute_success_array, compute_success, check_and_transform_label_format\nfrom art.utils import segment_by_class, performance_diff\nfrom art.utils import is_probability\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 100\nNB_TEST = 100\n\n\nclass TestUtils(unittest.TestCase):\n def setUp(self):\n master_seed(seed=1234)\n\n def test_master_seed_pytorch(self):\n import torch\n\n master_seed(seed=1234, set_torch=True)\n x = torch.randn(5, 5)\n y = torch.randn(5, 5)\n\n master_seed(seed=1234, set_torch=True)\n z = torch.randn(5, 5)\n self.assertFalse((x == y).any())\n self.assertTrue((x == z).all())\n\n def test_master_seed_py(self):\n import random\n\n master_seed(seed=1234)\n x = random.getrandbits(128)\n y = random.getrandbits(128)\n\n master_seed(seed=1234)\n z = random.getrandbits(128)\n self.assertNotEqual(x, y)\n self.assertEqual(z, x)\n\n def test_master_seed_np(self):\n master_seed(seed=1234)\n x = np.random.uniform(size=10)\n y = np.random.uniform(size=10)\n\n master_seed(seed=1234)\n z = np.random.uniform(size=10)\n self.assertTrue((x != y).any())\n self.assertTrue((z == x).all())\n\n def test_master_seed_tf_v2(self):\n master_seed(seed=1234, set_tensorflow=True)\n x = tf.random.uniform(shape=(1, 10))\n y = tf.random.uniform(shape=(1, 10))\n xv, yv = x.numpy(), y.numpy()\n\n master_seed(seed=1234, set_tensorflow=True)\n z = tf.random.uniform(shape=(1, 10))\n zv = z.numpy()\n\n self.assertTrue((xv != yv).any())\n np.testing.assert_array_almost_equal(zv, xv, decimal=4)\n\n def test_projection_norm(self):\n # Get MNIST\n (x, _), (_, _), _, _ = load_mnist()\n\n # Probably don't need to test everything\n x = x[:100]\n t = tuple(range(1, len(x.shape)))\n rand_sign = 1 - 2 * np.random.randint(0, 2, size=x.shape)\n\n x_proj = projection(rand_sign * x, 3.14159, 1)\n self.assertEqual(x.shape, x_proj.shape)\n self.assertTrue(np.allclose(np.sum(np.abs(x_proj), axis=t), 3.14159, atol=10e-8))\n\n x_proj = projection(rand_sign * x, 3.14159, 1, suboptimal=False)\n self.assertEqual(x.shape, x_proj.shape)\n self.assertTrue(np.allclose(np.sum(np.abs(x_proj), axis=t), 3.14159, atol=10e-8))\n\n x_proj = projection(rand_sign * x, 3.14159, 2)\n self.assertEqual(x.shape, x_proj.shape)\n self.assertTrue(np.allclose(np.sqrt(np.sum(x_proj**2, axis=t)), 3.14159, atol=10e-8))\n\n x_proj = projection(rand_sign * x, 0.314159, np.inf)\n self.assertEqual(x.shape, x_proj.shape)\n self.assertEqual(x_proj.min(), -0.314159)\n self.assertEqual(x_proj.max(), 0.314159)\n\n x_proj = projection(rand_sign * x, 3.14159, np.inf)\n self.assertEqual(x.shape, x_proj.shape)\n self.assertEqual(x_proj.min(), -1.0)\n self.assertEqual(x_proj.max(), 1.0)\n\n def test_random_sphere(self):\n x = random_sphere(10, 10, 1, 1)\n self.assertEqual(x.shape, (10, 10))\n self.assertTrue(np.all(np.sum(np.abs(x), axis=1) <= 1.0))\n\n x = random_sphere(10, 10, 1, 2)\n self.assertEqual(x.shape, (10, 10))\n self.assertTrue(np.all(np.linalg.norm(x, axis=1) < 1.0))\n\n x = random_sphere(10, 10, 1, np.inf)\n self.assertEqual(x.shape, (10, 10))\n self.assertTrue(np.all(np.abs(x) < 1.0))\n\n x = random_sphere(10, 10, 0.5, 1)\n self.assertTrue(np.all(np.sum(np.abs(x), axis=1) <= 0.5))\n\n x = random_sphere(10, 10, 0.5, 2)\n self.assertTrue(np.all(np.linalg.norm(x, axis=1) < 0.5))\n\n x = random_sphere(10, 10, 0.5, np.inf)\n self.assertTrue(np.all(np.abs(x) < 0.5))\n\n x = random_sphere(1, 10000, 1, 1)\n self.assertTrue(np.abs(np.sum(np.abs(x), axis=1) - 1.0) < 1e-2)\n\n x = random_sphere(1, 10000, 1, 2)\n self.assertTrue(np.abs(np.linalg.norm(x, axis=1) - 1.0) < 1e-2)\n\n x = random_sphere(1, 10000, 1, np.inf)\n self.assertTrue(np.abs(np.max(np.abs(x), axis=1) - 1.0) < 1e-2)\n\n def test_uniform_sample_from_sphere_or_ball(self):\n x = uniform_sample_from_sphere_or_ball(nb_points=10, nb_dims=10, radius=1, sample_space=\"ball\", norm=1)\n\n self.assertEqual(x.shape, (10, 10))\n self.assertTrue(np.all(np.sum(np.abs(x), axis=1) <= 1.0))\n\n x = uniform_sample_from_sphere_or_ball(nb_points=10, nb_dims=10, radius=1, sample_space=\"ball\", norm=np.inf)\n self.assertEqual(x.shape, (10, 10))\n self.assertTrue(np.all(np.abs(x) < 1.0))\n\n x = uniform_sample_from_sphere_or_ball(nb_points=10, nb_dims=10, radius=0.5, sample_space=\"ball\", norm=1)\n self.assertTrue(np.all(np.sum(np.abs(x), axis=1) <= 0.5))\n\n x = uniform_sample_from_sphere_or_ball(nb_points=10, nb_dims=10, radius=0.5, sample_space=\"ball\", norm=2)\n self.assertTrue(np.all(np.linalg.norm(x, axis=1) < 0.5))\n\n x = uniform_sample_from_sphere_or_ball(nb_points=10, nb_dims=10, radius=0.5, sample_space=\"ball\", norm=np.inf)\n self.assertTrue(np.all(np.abs(x) < 0.5))\n\n x = uniform_sample_from_sphere_or_ball(nb_points=1, nb_dims=10000, radius=1, sample_space=\"ball\", norm=1)\n self.assertTrue(np.abs(np.sum(np.abs(x), axis=1) - 1.0) < 1e-2)\n\n x = uniform_sample_from_sphere_or_ball(nb_points=1, nb_dims=10000, radius=1, sample_space=\"ball\", norm=2)\n self.assertTrue(np.abs(np.linalg.norm(x, axis=1) - 1.0) < 1e-2)\n\n x = uniform_sample_from_sphere_or_ball(nb_points=1, nb_dims=10000, radius=1, sample_space=\"ball\", norm=np.inf)\n self.assertTrue(np.abs(np.max(np.abs(x), axis=1) - 1.0) < 1e-2)\n\n def test_to_categorical(self):\n y = np.array([3, 1, 4, 1, 5, 9])\n y_ = to_categorical(y)\n self.assertEqual(y_.shape, (6, 10))\n self.assertTrue(np.all(y_.argmax(axis=1) == y))\n self.assertTrue(np.all(np.logical_or(y_ == 0.0, y_ == 1.0)))\n\n y_ = to_categorical(y, 20)\n self.assertEqual(y_.shape, (6, 20))\n\n def test_check_and_transform_label_format(self):\n labels_expected = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]])\n labels_expected_binary = np.array([[0, 1], [1, 0], [0, 1]])\n\n # test input shape (nb_samples,)\n labels = np.array([3, 1, 4])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=5, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected)\n\n # test input shape (nb_samples, 1)\n labels = np.array([[3], [1], [4]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=5, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected)\n\n # test input shape (nb_samples, 1) - binary\n labels = np.array([[1], [0], [1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=2, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected_binary)\n\n # test input shape (nb_samples, 1) - binary\n labels = np.array([[0, 1], [1, 0], [0, 1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=2, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected_binary)\n\n # test input shape (nb_samples, nb_classes)\n labels = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=5, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected)\n\n # test input shape (nb_samples, nb_classes) with return_one_hot=False\n labels = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=5, return_one_hot=False)\n np.testing.assert_array_equal(labels_transformed, np.expand_dims(np.argmax(labels_expected, axis=1), axis=1))\n\n # test input shape (nb_samples, 1) - binary\n labels = np.array([[1], [0], [1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=2, return_one_hot=False)\n np.testing.assert_array_equal(\n labels_transformed, np.expand_dims(np.argmax(labels_expected_binary, axis=1), axis=1)\n )\n\n # with no nb_classes\n\n # test input shape (nb_samples,)\n labels = np.array([3, 1, 4])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected)\n\n # test input shape (nb_samples, 1)\n labels = np.array([[3], [1], [4]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected)\n\n # test input shape (nb_samples, 1) - binary\n labels = np.array([[1], [0], [1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected_binary)\n\n # test input shape (nb_samples, 1) - binary\n labels = np.array([[0, 1], [1, 0], [0, 1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected_binary)\n\n # test input shape (nb_samples, nb_classes)\n labels = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=True)\n np.testing.assert_array_equal(labels_transformed, labels_expected)\n\n # test input shape (nb_samples, nb_classes) with return_one_hot=False\n labels = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=False)\n np.testing.assert_array_equal(labels_transformed, np.expand_dims(np.argmax(labels_expected, axis=1), axis=1))\n\n # test input shape (nb_samples, 1) - binary\n labels = np.array([[1], [0], [1]])\n labels_transformed = check_and_transform_label_format(labels, nb_classes=None, return_one_hot=False)\n np.testing.assert_array_equal(\n labels_transformed, np.expand_dims(np.argmax(labels_expected_binary, axis=1), axis=1)\n )\n\n # ValueError for len(labels.shape) > 2\n labels = np.array([[[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]]])\n with self.assertRaises(ValueError):\n check_and_transform_label_format(labels, nb_classes=None)\n\n def test_random_targets(self):\n y = np.array([3, 1, 4, 1, 5, 9])\n y_ = to_categorical(y)\n\n random_y = random_targets(y, 10)\n self.assertTrue(np.all(y != random_y.argmax(axis=1)))\n\n random_y = random_targets(y_, 10)\n self.assertTrue(np.all(y != random_y.argmax(axis=1)))\n\n def test_least_likely_class(self):\n class DummyClassifier:\n @property\n def nb_classes(self):\n return 4\n\n def predict(self, x):\n fake_preds = [0.1, 0.2, 0.05, 0.65]\n return np.array([fake_preds] * x.shape[0])\n\n batch_size = 5\n x = np.random.rand(batch_size, 10, 10, 1)\n classifier = DummyClassifier()\n predictions = least_likely_class(x, classifier)\n self.assertEqual(predictions.shape, (batch_size, classifier.nb_classes))\n\n expected_predictions = np.array([[0, 0, 1, 0]] * batch_size)\n self.assertTrue((predictions == expected_predictions).all())\n\n def test_second_most_likely_class(self):\n class DummyClassifier:\n @property\n def nb_classes(self):\n return 4\n\n def predict(self, x):\n fake_predictions = [0.1, 0.2, 0.05, 0.65]\n return np.array([fake_predictions] * x.shape[0])\n\n batch_size = 5\n x = np.random.rand(batch_size, 10, 10, 1)\n classifier = DummyClassifier()\n predictions = second_most_likely_class(x, classifier)\n self.assertEqual(predictions.shape, (batch_size, classifier.nb_classes))\n\n expected_predictions = np.array([[0, 1, 0, 0]] * batch_size)\n self.assertTrue((predictions == expected_predictions).all())\n\n def test_get_label_conf(self):\n y = np.array([3, 1, 4, 1, 5, 9])\n y_ = to_categorical(y)\n\n logits = np.random.normal(10 * y_, scale=0.1)\n ps = (np.exp(logits).T / np.sum(np.exp(logits), axis=1)).T\n confs, labels = get_label_conf(ps)\n\n self.assertEqual(confs.shape, y.shape)\n self.assertEqual(labels.shape, y.shape)\n\n self.assertTrue(np.all(labels == y))\n self.assertTrue(np.allclose(confs, 0.99, atol=1e-2))\n\n def test_get_labels_np_array(self):\n y = np.array([3, 1, 4, 1, 5, 9])\n y_ = to_categorical(y)\n\n logits = np.random.normal(1 * y_, scale=0.1)\n ps = (np.exp(logits).T / np.sum(np.exp(logits), axis=1)).T\n\n labels = get_labels_np_array(ps)\n self.assertEqual(labels.shape, y_.shape)\n self.assertTrue(np.all(labels == y_))\n\n def test_compute_success_array(self):\n class DummyClassifier:\n def predict(self, x, batch_size):\n return x\n\n classifier = DummyClassifier()\n x_clean = np.array([[0, 1], [1, 0]])\n x_adv = np.array([[1, 0], [0, 1]])\n labels = np.array([[1, 0], [0, 1]])\n\n attack_success_targeted = compute_success_array(classifier, x_clean, labels, x_adv, targeted=True)\n attack_success_untargeted = compute_success_array(classifier, x_clean, labels, x_adv, targeted=False)\n\n self.assertTrue((attack_success_targeted == np.array([True, True])).all())\n self.assertTrue((attack_success_untargeted == np.array([True, True])).all())\n\n def test_compute_success(self):\n class DummyClassifier:\n def predict(self, x, batch_size):\n return x\n\n classifier = DummyClassifier()\n x_clean = np.array([[0, 1], [1, 0]])\n x_adv = np.array([[1, 0], [0, 1]])\n labels = np.array([[1, 0], [0, 1]])\n\n attack_success_targeted = compute_success(classifier, x_clean, labels, x_adv, targeted=True)\n attack_success_untargeted = compute_success(classifier, x_clean, labels, x_adv, targeted=False)\n\n self.assertEqual(attack_success_targeted, 1.0)\n self.assertEqual(attack_success_untargeted, 1.0)\n\n def test_preprocess(self):\n (x, y), (_, _), _, _ = load_mnist()\n\n x = (255 * x).astype(\"int\")[:100]\n y = np.argmax(y, axis=1)[:100]\n\n x_, y_ = preprocess(x, y, clip_values=(0, 255))\n self.assertEqual(x_.shape, x.shape)\n self.assertEqual(y_.shape, (y.shape[0], 10))\n self.assertEqual(x_.max(), 1.0)\n self.assertEqual(x_.min(), 0)\n\n (x, y), (_, _), _, _ = load_mnist()\n\n x = (5 * x).astype(\"int\")[:100]\n y = np.argmax(y, axis=1)[:100]\n x_, y_ = preprocess(x, y, nb_classes=20, clip_values=(0, 5))\n self.assertEqual(x_.shape, x.shape)\n self.assertEqual(y_.shape, (y.shape[0], 20))\n self.assertEqual(x_.max(), 1.0)\n self.assertEqual(x_.min(), 0)\n\n def test_iris(self):\n (x_train, y_train), (x_test, y_test), min_, max_ = load_iris()\n\n self.assertAlmostEqual(min_, 0.012658227848101266, places=6)\n self.assertEqual(max_, 1.0)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n train_labels = np.argmax(y_train, axis=1)\n self.assertEqual(np.setdiff1d(train_labels, np.array([0, 1, 2])).shape, (0,))\n test_labels = np.argmax(y_test, axis=1)\n self.assertEqual(np.setdiff1d(test_labels, np.array([0, 1, 2])).shape, (0,))\n\n (x_train, y_train), (x_test, y_test), _, _ = load_iris(test_set=0)\n self.assertEqual(x_train.shape[0], 150)\n self.assertEqual(y_train.shape[0], 150)\n self.assertIs(x_test, None)\n self.assertIs(y_test, None)\n\n def test_cifar10(self):\n (x_train, y_train), (x_test, y_test), min_, max_ = load_cifar10()\n self.assertAlmostEqual(min_, 0.0, places=6)\n self.assertEqual(max_, 1.0)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n (x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(\"cifar10\")\n self.assertAlmostEqual(min_, 0.0, places=6)\n self.assertEqual(max_, 1.0)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n # def test_stl(self):\n # (x_train, y_train), (x_test, y_test), min_, max_ = load_stl()\n # self.assertAlmostEqual(min_, 0.0, places=6)\n # self.assertEqual(max_, 1.0)\n # self.assertEqual(x_train.shape[0], y_train.shape[0])\n # self.assertEqual(x_test.shape[0], y_test.shape[0])\n #\n # (x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(\"stl10\")\n # self.assertAlmostEqual(min_, 0.0, places=6)\n # self.assertEqual(max_, 1.0)\n # self.assertEqual(x_train.shape[0], y_train.shape[0])\n # self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n def test_nursery(self):\n (x_train, y_train), (x_test, y_test), min_, max_ = load_nursery(raw=True)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n (x_train, y_train), (x_test, y_test), min_, max_ = load_nursery(scaled=False)\n self.assertEqual(min_, 0.0)\n self.assertEqual(max_, 4.0)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n (x_train, y_train), (x_test, y_test), min_, max_ = load_nursery()\n self.assertAlmostEqual(min_, -1.3419307411337875, places=6)\n self.assertEqual(max_, 2.0007720517562224)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n (x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(\"nursery\")\n self.assertAlmostEqual(min_, -1.3419307411337875, places=6)\n self.assertEqual(max_, 2.0007720517562224)\n self.assertEqual(x_train.shape[0], y_train.shape[0])\n self.assertEqual(x_test.shape[0], y_test.shape[0])\n\n def test_segment_by_class(self):\n data = np.array([[3, 2], [9, 2], [4, 0], [9, 0]])\n classes = to_categorical(np.array([2, 1, 0, 1]))\n num_classes = 3\n segments = segment_by_class(data, classes, num_classes)\n self.assertEqual(len(segments), num_classes)\n self.assertEqual(len(segments[1]), 2)\n self.assertTrue(np.all(np.equal(segments[0], np.array([data[2]]))))\n self.assertTrue(np.all(np.equal(segments[1], np.array([data[1], data[3]]))))\n self.assertTrue(np.all(np.equal(segments[2], np.array([data[0]]))))\n\n num_classes = 4\n segments = segment_by_class(data, classes, num_classes)\n self.assertEqual(len(segments), num_classes)\n\n def test_performance_diff(self):\n from art.estimators.classification.scikitlearn import SklearnClassifier\n from sklearn.svm import SVC\n\n (x_train, y_train), (x_test, y_test), min_, max_ = load_iris()\n\n full_model = SklearnClassifier(model=SVC(kernel=\"linear\", gamma=\"auto\"), clip_values=(min_, max_))\n full_model.fit(x_train, y_train)\n\n limited_model = SklearnClassifier(model=SVC(kernel=\"linear\", gamma=\"auto\"), clip_values=(min_, max_))\n limited_model.fit(x_train[:10], y_train[:10])\n\n self.assertEqual(\n performance_diff(full_model, limited_model, x_test[:20], y_test[:20], perf_function=\"accuracy\"), 0.35\n )\n self.assertEqual(performance_diff(full_model, limited_model, x_test[:20], y_test[:20]), 0.35)\n diff = performance_diff(\n full_model, limited_model, x_test[:20], y_test[:20], perf_function=\"f1\", average=\"weighted\"\n )\n self.assertGreater(diff, 0.43)\n self.assertLess(diff, 0.44)\n\n def first_class(true_labels, model_labels, idx=0):\n return np.average(np.argmax(model_labels, axis=1) == idx)\n\n self.assertEqual(\n performance_diff(full_model, limited_model, x_test, y_test, perf_function=first_class), 1.0 / 3\n )\n self.assertEqual(\n performance_diff(full_model, limited_model, x_test, y_test, perf_function=first_class, idx=1), -1.0 / 3\n )\n\n def test_is_probability(self):\n probabilities = np.array([0.1, 0.3, 0.6])\n self.assertTrue(is_probability(probabilities))\n\n not_probabilities = np.array([0.1, 0.3, 0.8])\n self.assertFalse(is_probability(not_probabilities))\n\n not_probabilities = np.array([0.1, 0.3, 1.8])\n self.assertFalse(is_probability(not_probabilities))\n\n not_probabilities = np.array([-1.1, 0.3, 1.8])\n self.assertFalse(is_probability(not_probabilities))\n\n not_probabilities = np.array([-1.1, 0.3, 0.7])\n self.assertFalse(is_probability(not_probabilities))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/test_visualization.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os.path\nimport unittest\n\nimport numpy as np\n\nfrom art import config\nfrom art.utils import load_mnist, load_cifar10\nfrom art.visualization import create_sprite, convert_to_rgb, save_image, plot_3d\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestVisualization(unittest.TestCase):\n def setUp(self):\n master_seed(seed=42)\n\n def test_save_image(self):\n (x, _), (_, _), _, _ = load_mnist(raw=True)\n\n f_name = \"image1.png\"\n save_image(x[0], f_name)\n path = os.path.join(config.ART_DATA_PATH, f_name)\n self.assertTrue(os.path.isfile(path))\n os.remove(path)\n\n f_name = \"image2.jpg\"\n save_image(x[1], f_name)\n path = os.path.join(config.ART_DATA_PATH, f_name)\n self.assertTrue(os.path.isfile(path))\n os.remove(path)\n\n folder = \"images123456\"\n f_name_with_dir = os.path.join(folder, \"image3.png\")\n save_image(x[3], f_name_with_dir)\n path = os.path.join(config.ART_DATA_PATH, f_name_with_dir)\n self.assertTrue(os.path.isfile(path))\n os.remove(path)\n os.rmdir(os.path.split(path)[0]) # Remove also test folder\n\n folder = os.path.join(\"images123456\", \"inner\")\n f_name_with_dir = os.path.join(folder, \"image4.png\")\n save_image(x[3], f_name_with_dir)\n path_nested = os.path.join(config.ART_DATA_PATH, f_name_with_dir)\n self.assertTrue(os.path.isfile(path_nested))\n os.remove(path_nested)\n os.rmdir(os.path.split(path_nested)[0]) # Remove inner test folder\n os.rmdir(os.path.split(path)[0]) # Remove also test folder\n\n def test_convert_gray_to_rgb(self):\n # Get MNIST\n (x, _), (_, _), _, _ = load_mnist(raw=True)\n n = 100\n x = x[:n]\n\n # Test RGB\n x_rgb = convert_to_rgb(x)\n s_original = np.shape(x)\n s_new = np.shape(x_rgb)\n\n self.assertEqual(s_new[0], s_original[0])\n self.assertEqual(s_new[1], s_original[1])\n self.assertEqual(s_new[2], s_original[2])\n self.assertEqual(s_new[3], 3) # Should have added 3 channels\n\n def test_sprites_gray(self):\n # Get MNIST\n (x, _), (_, _), _, _ = load_mnist(raw=True)\n n = 100\n x = x[:n]\n\n sprite = create_sprite(x)\n f_name = \"test_sprite_mnist.png\"\n path = os.path.join(config.ART_DATA_PATH, f_name)\n save_image(sprite, path)\n self.assertTrue(os.path.isfile(path))\n\n os.remove(path) # Remove data added\n\n def test_sprites_color(self):\n (x, _), (_, _), _, _ = load_cifar10(raw=True)\n n = 500\n x = x[:n]\n\n sprite = create_sprite(x)\n f_name = \"test_cifar.jpg\"\n path = os.path.join(config.ART_DATA_PATH, f_name)\n save_image(sprite, path)\n self.assertTrue(os.path.isfile(path))\n\n os.remove(path) # Remove data added\n\n @unittest.expectedFailure\n def test_3D_plot_fail(self):\n points = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])\n labels = np.array([1, 1, 3])\n\n # Shouldn't work because labels don't start in zero.\n plot_3d(points, labels, save=False)\n\n def test_3D_plot(self):\n points = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])\n labels = np.array([0, 1, 1])\n\n plot_3d(points, labels, save=False)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule providing convenience functions specifically for unit tests.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport json\nimport logging\nimport os\nimport pickle\nimport time\nimport unittest\nimport warnings\n\nimport sklearn\nimport numpy as np\n\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\nfrom art.estimators.gan.tensorflow import TensorFlowV2GAN\nfrom art.utils import load_dataset\n\nlogger = logging.getLogger(__name__)\n\n# ----------------------------------------------------------------------------------------------------- TEST BASE CLASS\nart_supported_frameworks = [\"keras\", \"tensorflow\", \"pytorch\", \"scikitlearn\", \"huggingface\"]\n\n\nclass TestBase(unittest.TestCase):\n \"\"\"\n This class implements the base class for all unit tests.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(1234)\n\n cls.n_train = 1000\n cls.n_test = 100\n cls.batch_size = 16\n\n cls.create_image_dataset(n_train=cls.n_train, n_test=cls.n_test)\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris), _, _ = load_dataset(\"iris\")\n\n cls.x_train_iris = x_train_iris\n cls.y_train_iris = y_train_iris\n cls.x_test_iris = x_test_iris\n cls.y_test_iris = y_test_iris\n\n cls._x_train_iris_original = cls.x_train_iris.copy()\n cls._y_train_iris_original = cls.y_train_iris.copy()\n cls._x_test_iris_original = cls.x_test_iris.copy()\n cls._y_test_iris_original = cls.y_test_iris.copy()\n\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes), _, _ = load_dataset(\"diabetes\")\n\n cls.x_train_diabetes = x_train_diabetes\n cls.y_train_diabetes = y_train_diabetes\n cls.x_test_diabetes = x_test_diabetes\n cls.y_test_diabetes = y_test_diabetes\n\n cls._x_train_diabetes_original = cls.x_train_diabetes.copy()\n cls._y_train_diabetes_original = cls.y_train_diabetes.copy()\n cls._x_test_diabetes_original = cls.x_test_diabetes.copy()\n cls._y_test_diabetes_original = cls.y_test_diabetes.copy()\n\n # Filter warning for scipy, removed with scipy 1.4\n warnings.filterwarnings(\"ignore\", \".*the output shape of zoom.*\")\n\n @classmethod\n def create_image_dataset(cls, n_train, n_test):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist), _, _ = load_dataset(\"mnist\")\n cls.x_train_mnist = x_train_mnist[:n_train]\n cls.y_train_mnist = y_train_mnist[:n_train]\n cls.x_test_mnist = x_test_mnist[:n_test]\n cls.y_test_mnist = y_test_mnist[:n_test]\n\n cls._x_train_mnist_original = cls.x_train_mnist.copy()\n cls._y_train_mnist_original = cls.y_train_mnist.copy()\n cls._x_test_mnist_original = cls.x_test_mnist.copy()\n cls._y_test_mnist_original = cls.y_test_mnist.copy()\n\n def setUp(self):\n self.time_start = time.time()\n print(\"\\n\\n\\n----------------------------------------------------------------------\")\n\n def tearDown(self):\n time_end = time.time() - self.time_start\n test_name = \".\".join(self.id().split(\" \")[0].split(\".\")[-2:])\n logger.info(\"%s: completed in %.3f seconds\" % (test_name, time_end))\n\n # Check that the test data has not been modified, only catches changes in attack.generate if self has been used\n np.testing.assert_array_almost_equal(\n self._x_train_mnist_original[0 : self.n_train], self.x_train_mnist, decimal=3\n )\n np.testing.assert_array_almost_equal(\n self._y_train_mnist_original[0 : self.n_train], self.y_train_mnist, decimal=3\n )\n np.testing.assert_array_almost_equal(self._x_test_mnist_original[0 : self.n_test], self.x_test_mnist, decimal=3)\n np.testing.assert_array_almost_equal(self._y_test_mnist_original[0 : self.n_test], self.y_test_mnist, decimal=3)\n\n np.testing.assert_array_almost_equal(self._x_train_iris_original, self.x_train_iris, decimal=3)\n np.testing.assert_array_almost_equal(self._y_train_iris_original, self.y_train_iris, decimal=3)\n np.testing.assert_array_almost_equal(self._x_test_iris_original, self.x_test_iris, decimal=3)\n np.testing.assert_array_almost_equal(self._y_test_iris_original, self.y_test_iris, decimal=3)\n\n\nclass ExpectedValue:\n def __init__(self, value, decimals):\n self.value = value\n self.decimals = decimals\n\n\n# ----------------------------------------------------------------------------------------------- TEST MODELS FOR MNIST\n\n\ndef check_adverse_example_x(x_adv, x_original, max=1.0, min=0.0, bounded=True):\n \"\"\"\n Performs basic checks on generated adversarial inputs (whether x_test or x_train)\n :param x_adv:\n :param x_original:\n :param max:\n :param min:\n :param bounded:\n :return:\n \"\"\"\n assert bool((x_original == x_adv).all()) is False, \"x_test_adv should have been different from x_test\"\n\n if bounded:\n assert np.amax(x_adv) <= max, \"x_test_adv values should have all been below {0}\".format(max)\n assert np.amin(x_adv) >= min, \"x_test_adv values should have all been above {0}\".format(min)\n else:\n assert (x_adv > max).any(), \"some x_test_adv values should have been above {0}\".format(max)\n assert (x_adv < min).any(), \" some x_test_adv values should have all been below {0}\".format(min)\n\n\ndef check_adverse_predicted_sample_y(y_pred_adv, y_non_adv):\n assert bool((y_non_adv == y_pred_adv).all()) is False, \"Adverse predicted sample was not what was expected\"\n\n\ndef is_valid_framework(framework):\n if framework not in art_supported_frameworks:\n raise Exception(\n \"Framework value {0} is unsupported. Please use one of these valid values: {1}\".format(\n framework, \" \".join(art_supported_frameworks)\n )\n )\n return True\n\n\ndef _tf_weights_loader(dataset, weights_type, layer=\"DENSE\", tf_version=1):\n filename = str(weights_type) + \"_\" + str(layer) + \"_\" + str(dataset) + \".npy\"\n\n # pylint: disable=W0613\n if tf_version == 2:\n\n def _tf_initializer(_, dtype):\n import tensorflow as tf\n\n weights = np.load(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", filename)\n )\n return tf.constant(weights, dtype)\n\n else:\n raise ValueError(\"The TensorFlow version tf_version has to be 2.\")\n\n return _tf_initializer\n\n\ndef _kr_weights_loader(dataset, weights_type, layer=\"DENSE\"):\n import keras.backend as k\n\n filename = str(weights_type) + \"_\" + str(layer) + \"_\" + str(dataset) + \".npy\"\n\n def _kr_initializer(_, dtype=None):\n weights = np.load(os.path.join(os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", filename))\n return k.variable(value=weights, dtype=dtype)\n\n return _kr_initializer\n\n\ndef _kr_tf_weights_loader(dataset, weights_type, layer=\"DENSE\"):\n filename = str(weights_type) + \"_\" + str(layer) + \"_\" + str(dataset) + \".npy\"\n weights = np.load(os.path.join(os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", filename))\n return weights\n\n\ndef get_image_classifier_tf(from_logits=False, load_init=True, sess=None, framework=None):\n import tensorflow as tf\n\n if framework is None or framework == \"tensorflow2\":\n # sess is not required but set to None to return 2 values for v1 and v2\n classifier, sess = get_image_classifier_tf_v2(from_logits=from_logits), None\n else:\n raise ValueError(\"Unexpected value for `framework`.\")\n return classifier, sess\n\n\ndef get_image_generator_tf_v2(capacity: int, z_dim: int):\n import tensorflow as tf # lgtm [py/import-and-import-from]\n\n def make_image_generator_model(capacity: int, z_dim: int) -> tf.keras.Sequential():\n model = tf.keras.Sequential()\n\n model.add(tf.keras.layers.Dense(capacity * 7 * 7 * 4, use_bias=False, input_shape=(z_dim,)))\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.LeakyReLU())\n\n model.add(tf.keras.layers.Reshape((7, 7, capacity * 4)))\n assert model.output_shape == (None, 7, 7, capacity * 4)\n\n model.add(tf.keras.layers.Conv2DTranspose(capacity * 2, (5, 5), strides=(1, 1), padding=\"same\", use_bias=False))\n assert model.output_shape == (None, 7, 7, capacity * 2)\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.LeakyReLU())\n\n model.add(tf.keras.layers.Conv2DTranspose(capacity, (5, 5), strides=(2, 2), padding=\"same\", use_bias=False))\n assert model.output_shape == (None, 14, 14, capacity)\n model.add(tf.keras.layers.BatchNormalization())\n model.add(tf.keras.layers.LeakyReLU())\n\n model.add(tf.keras.layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding=\"same\", use_bias=False))\n\n model.add(tf.keras.layers.Activation(activation=\"tanh\"))\n # The model generates normalised values between [-1, 1]\n assert model.output_shape == (None, 28, 28, 1)\n\n return model\n\n generator = TensorFlowV2Generator(encoding_length=z_dim, model=make_image_generator_model(capacity, z_dim))\n\n return generator\n\n\ndef get_image_gan_tf_v2():\n import tensorflow as tf # lgtm [py/import-and-import-from]\n\n noise_dim = 100\n capacity = 64\n generator = get_image_generator_tf_v2(capacity, noise_dim)\n\n def make_image_discriminator_model(capacity: int) -> tf.keras.Sequential():\n model = tf.keras.Sequential()\n\n model.add(tf.keras.layers.Conv2D(capacity, (5, 5), strides=(2, 2), padding=\"same\", input_shape=[28, 28, 1]))\n model.add(tf.keras.layers.LeakyReLU())\n model.add(tf.keras.layers.Dropout(0.3))\n\n model.add(tf.keras.layers.Conv2D(capacity * 2, (5, 5), strides=(2, 2), padding=\"same\"))\n model.add(tf.keras.layers.LeakyReLU())\n model.add(tf.keras.layers.Dropout(0.3))\n\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(1))\n\n return model\n\n discriminator_classifier = TensorFlowV2Classifier(\n model=make_image_discriminator_model(capacity), nb_classes=2, input_shape=(28, 28, 28, 1)\n )\n\n def generator_orig_loss_fct(generated_output):\n loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n return loss_fn(tf.ones_like(generated_output), generated_output)\n\n def discriminator_loss_fct(real_output, generated_output):\n \"\"\"Discriminator loss\n\n The discriminator loss function takes two inputs: real images, and generated images. Here is how to calculate\n the discriminator loss:\n 1. Calculate real_loss which is a sigmoid cross entropy loss of the real images and an array of ones (since\n these are the real images).\n 2. Calculate generated_loss which is a sigmoid cross entropy loss of the generated images and an array of\n zeros (since these are the fake images).\n 3. Calculate the total_loss as the sum of real_loss and generated_loss.\n \"\"\"\n # Binary cross-entropy loss function (logits not passed through sigmoid yet)\n bce = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n\n # Real images: label as 1\n real_loss = bce(tf.ones_like(real_output), real_output)\n\n # Generated (fake) images: label as 0\n generated_loss = bce(tf.zeros_like(generated_output), generated_output)\n\n total_loss = real_loss + generated_loss\n\n return total_loss\n\n # Use native TF 2.x optimizers\n generator_optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4)\n discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4)\n\n gan = TensorFlowV2GAN(\n generator=generator,\n discriminator=discriminator_classifier,\n generator_loss=generator_orig_loss_fct,\n generator_optimizer_fct=generator_optimizer,\n discriminator_loss=discriminator_loss_fct,\n discriminator_optimizer_fct=discriminator_optimizer,\n )\n\n return gan\n\n\ndef get_image_classifier_tf_v2(from_logits=False):\n \"\"\"\n Standard TensorFlow v2 classifier for unit testing.\n\n The following hyperparameters were used to obtain the weights and biases:\n learning_rate: 0.01\n batch size: 10\n number of epochs: 2\n optimizer: tf.train.AdamOptimizer\n\n :return: TensorFlowV2Classifier\n \"\"\"\n # pylint: disable=E0401\n import tensorflow as tf\n from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPool2D\n from tensorflow.keras.models import Sequential\n\n from art.estimators.classification.tensorflow import TensorFlowV2Classifier\n\n model = Sequential()\n model.add(\n Conv2D(\n filters=1,\n kernel_size=7,\n activation=\"relu\",\n kernel_initializer=_tf_weights_loader(\"MNIST\", \"W\", \"CONV2D\", 2),\n bias_initializer=_tf_weights_loader(\"MNIST\", \"B\", \"CONV2D\", 2),\n input_shape=(28, 28, 1),\n )\n )\n model.add(MaxPool2D(pool_size=(4, 4), strides=(4, 4), padding=\"valid\", data_format=None))\n model.add(Flatten())\n if from_logits:\n model.add(\n Dense(\n 10,\n activation=\"linear\",\n kernel_initializer=_tf_weights_loader(\"MNIST\", \"W\", \"DENSE\", 2),\n bias_initializer=_tf_weights_loader(\"MNIST\", \"B\", \"DENSE\", 2),\n )\n )\n else:\n model.add(\n Dense(\n 10,\n activation=\"softmax\",\n kernel_initializer=_tf_weights_loader(\"MNIST\", \"W\", \"DENSE\", 2),\n bias_initializer=_tf_weights_loader(\"MNIST\", \"B\", \"DENSE\", 2),\n )\n )\n\n loss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=from_logits, reduction=tf.keras.losses.Reduction.SUM\n )\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n\n model.compile(optimizer=optimizer, loss=loss_object)\n\n # Create the classifier\n tfc = TensorFlowV2Classifier(\n model=model,\n loss_object=loss_object,\n optimizer=optimizer,\n nb_classes=10,\n input_shape=(28, 28, 1),\n clip_values=(0, 1),\n )\n\n return tfc\n\n\ndef get_image_classifier_kr(\n loss_name=\"categorical_crossentropy\", loss_type=\"function_losses\", from_logits=False, load_init=True\n):\n \"\"\"\n Standard Keras classifier for unit testing\n\n The weights and biases are identical to the TensorFlow model in get_classifier_tf().\n\n :param loss_name: The name of the loss function.\n :type loss_name: `str`\n :param loss_type: The type of loss function definitions: label (loss function defined by string of its name),\n function_losses (loss function imported from keras.losses), function_backend (loss function\n imported from keras.backend)\n :type loss_type: `str`\n :param from_logits: Flag if model should predict logits (True) or probabilities (False).\n :type from_logits: `bool`\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :return: KerasClassifier, tf.Session()\n \"\"\"\n import tensorflow as tf\n from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D\n from tensorflow.keras.models import Sequential\n\n from art.estimators.classification.keras import KerasClassifier\n\n # Create simple CNN\n model = Sequential()\n\n if load_init:\n model.add(\n Conv2D(\n 1,\n kernel_size=(7, 7),\n activation=\"relu\",\n input_shape=(28, 28, 1),\n kernel_initializer=_tf_weights_loader(\"MNIST\", \"W\", \"CONV2D\", 2),\n bias_initializer=_tf_weights_loader(\"MNIST\", \"B\", \"CONV2D\", 2),\n )\n )\n else:\n model.add(Conv2D(1, kernel_size=(7, 7), activation=\"relu\", input_shape=(28, 28, 1)))\n\n model.add(MaxPooling2D(pool_size=(4, 4)))\n model.add(Flatten())\n\n if from_logits:\n if load_init:\n model.add(\n Dense(\n 10,\n activation=\"linear\",\n kernel_initializer=_tf_weights_loader(\"MNIST\", \"W\", \"DENSE\", 2),\n bias_initializer=_tf_weights_loader(\"MNIST\", \"B\", \"DENSE\", 2),\n )\n )\n else:\n model.add(Dense(10, activation=\"linear\"))\n else:\n if load_init:\n model.add(\n Dense(\n 10,\n activation=\"softmax\",\n kernel_initializer=_tf_weights_loader(\"MNIST\", \"W\", \"DENSE\", 2),\n bias_initializer=_tf_weights_loader(\"MNIST\", \"B\", \"DENSE\", 2),\n )\n )\n else:\n model.add(Dense(10, activation=\"softmax\"))\n\n loss = None\n\n if loss_name == \"categorical_hinge\":\n if loss_type == \"label\":\n raise AttributeError(\"This combination of loss function options is not supported.\")\n elif loss_type == \"function_losses\":\n loss = tf.keras.losses.categorical_hinge\n elif loss_name == \"categorical_crossentropy\":\n if loss_type == \"label\":\n if from_logits:\n raise AttributeError(\"This combination of loss function options is not supported.\")\n else:\n loss = loss_name\n elif loss_type == \"function_losses\":\n if from_logits:\n\n def categorical_crossentropy(y_true, y_pred):\n return tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=True)\n\n loss = categorical_crossentropy\n else:\n loss = tf.keras.losses.categorical_crossentropy\n elif loss_type == \"function_backend\":\n if from_logits:\n\n def categorical_crossentropy(y_true, y_pred):\n return tf.keras.backend.categorical_crossentropy(y_true, y_pred, from_logits=True)\n\n loss = categorical_crossentropy\n else:\n loss = tf.keras.backend.categorical_crossentropy\n elif loss_name == \"sparse_categorical_crossentropy\":\n if loss_type == \"label\":\n if from_logits:\n raise AttributeError(\"This combination of loss function options is not supported.\")\n else:\n loss = loss_name\n elif loss_type == \"function_losses\":\n if from_logits:\n\n def sparse_categorical_crossentropy(y_true, y_pred):\n return tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)\n\n loss = sparse_categorical_crossentropy\n else:\n loss = tf.keras.losses.sparse_categorical_crossentropy\n elif loss_type == \"function_backend\":\n if from_logits:\n\n def sparse_categorical_crossentropy(y_true, y_pred):\n return tf.keras.backend.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)\n\n loss = sparse_categorical_crossentropy\n else:\n loss = tf.keras.backend.sparse_categorical_crossentropy\n elif loss_name == \"kullback_leibler_divergence\":\n if loss_type == \"label\":\n raise AttributeError(\"This combination of loss function options is not supported.\")\n elif loss_type == \"function_losses\":\n loss = tf.keras.losses.kullback_leibler_divergence\n elif loss_type == \"function_backend\":\n raise AttributeError(\"This combination of loss function options is not supported.\")\n elif loss_name == \"cosine_similarity\":\n if loss_type == \"label\":\n loss = loss_name\n elif loss_type == \"function_losses\":\n loss = tf.keras.losses.cosine_similarity\n elif loss_type == \"function_backend\":\n loss = tf.keras.backend.cosine_similarity\n\n else:\n raise ValueError(\"Loss name not recognised.\")\n\n model.compile(loss=loss, optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), metrics=[\"accuracy\"])\n\n # Get classifier\n krc = KerasClassifier(model, clip_values=(0, 1), use_logits=from_logits)\n\n return krc\n\n\ndef get_image_classifier_kr_functional(input_layer=1, output_layer=1):\n import keras\n from keras.layers import Conv2D, Dense, Dropout, Flatten, Input, MaxPooling2D\n from keras.models import Model\n\n from art.estimators.classification.keras import KerasClassifier\n\n def _functional_model():\n in_layer = Input(shape=(28, 28, 1), name=\"input0\")\n layer = Conv2D(32, kernel_size=(3, 3), activation=\"relu\")(in_layer)\n layer = Conv2D(64, (3, 3), activation=\"relu\")(layer)\n layer = MaxPooling2D(pool_size=(2, 2))(layer)\n layer = Dropout(0.25)(layer)\n layer = Flatten()(layer)\n layer = Dense(128, activation=\"relu\")(layer)\n layer = Dropout(0.5)(layer)\n out_layer = Dense(10, activation=\"softmax\", name=\"output0\")(layer)\n\n in_layer_2 = Input(shape=(28, 28, 1), name=\"input1\")\n layer = Conv2D(32, kernel_size=(3, 3), activation=\"relu\")(in_layer_2)\n layer = Conv2D(64, (3, 3), activation=\"relu\")(layer)\n layer = MaxPooling2D(pool_size=(2, 2))(layer)\n layer = Dropout(0.25)(layer)\n layer = Flatten()(layer)\n layer = Dense(128, activation=\"relu\")(layer)\n layer = Dropout(0.5)(layer)\n out_layer_2 = Dense(10, activation=\"softmax\", name=\"output1\")(layer)\n\n model = Model(inputs=[in_layer, in_layer_2], outputs=[out_layer, out_layer_2])\n\n model.compile(\n loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=[\"accuracy\"],\n loss_weights=[1.0, 1.0],\n )\n\n return model\n\n functional_model = _functional_model()\n\n return KerasClassifier(functional_model, clip_values=(0, 1), input_layer=input_layer, output_layer=output_layer)\n\n\ndef get_image_classifier_kr_tf_functional(input_layer=1, output_layer=1):\n \"\"\"\n Standard Keras_tf classifier for unit testing built with a functional model\n\n :return: KerasClassifier\n \"\"\"\n import tensorflow as tf\n from tensorflow.keras.layers import Conv2D, Dense, Dropout, Flatten, Input, MaxPooling2D, Identity\n from tensorflow.keras.models import Model\n from keras.losses import CategoricalCrossentropy\n\n from art.estimators.classification.keras import KerasClassifier\n\n def functional_model():\n # First input and branch\n in_layer = Input(shape=(28, 28, 1), name=\"input0\")\n x = Conv2D(32, kernel_size=(3, 3), activation=\"relu\")(in_layer)\n x = Conv2D(64, (3, 3), activation=\"relu\")(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n x = Dropout(0.25)(x)\n x = Flatten()(x)\n x = Dense(128, activation=\"relu\")(x)\n x = Dropout(0.5)(x)\n out_layer = Dense(10, activation=\"softmax\", name=\"output0_dense\")(x)\n out_layer.name = \"output0\"\n\n # Second input and branch\n in_layer_2 = Input(shape=(28, 28, 1), name=\"input1\")\n y = Conv2D(32, kernel_size=(3, 3), activation=\"relu\")(in_layer_2)\n y = Conv2D(64, (3, 3), activation=\"relu\")(y)\n y = MaxPooling2D(pool_size=(2, 2))(y)\n y = Dropout(0.25)(y)\n y = Flatten()(y)\n y = Dense(128, activation=\"relu\")(y)\n y = Dropout(0.5)(y)\n out_layer_2 = Dense(10, activation=\"softmax\", name=\"output1_dense\")(y)\n out_layer_2.name = \"output1\"\n\n # Define model with named outputs\n model = Model(inputs=[in_layer, in_layer_2], outputs=[out_layer, out_layer_2])\n\n loss_fn = CategoricalCrossentropy(reduction=tf.keras.losses.Reduction.NONE)\n\n # Compile\n model.compile(\n loss=[loss_fn, loss_fn],\n optimizer=tf.keras.optimizers.Adadelta(),\n metrics=[\"accuracy\", \"accuracy\"],\n loss_weights=[1.0, 1.0],\n )\n\n return model\n\n return KerasClassifier(functional_model(), clip_values=(0, 1), input_layer=input_layer, output_layer=output_layer)\n\n\ndef get_image_classifier_kr_tf(loss_name=\"categorical_crossentropy\", loss_type=\"function\", from_logits=False):\n \"\"\"\n Standard Keras classifier for unit testing\n\n The weights and biases are identical to the TensorFlow model in get_classifier_tf().\n\n :param loss_name: The name of the loss function.\n :type loss_name: `str`\n :param loss_type: The type of loss function definitions: label (loss function defined by string of its name),\n function_losses (loss function), class (loss function generator)\n :type loss_type: `str`\n :param from_logits: Flag if model should predict logits (True) or probabilities (False).\n :type from_logits: `bool`\n\n\n :return: KerasClassifier\n \"\"\"\n import tensorflow as tf\n\n # pylint: disable=E0401\n from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D, Input\n from tensorflow.keras.models import Sequential\n\n from art.estimators.classification.keras import KerasClassifier\n\n # Create simple CNN\n model = Sequential()\n model.add(Input((28, 28, 1)))\n model.add(Conv2D(1, kernel_size=(7, 7), activation=\"relu\"))\n model.layers[-1].set_weights(\n [_kr_tf_weights_loader(\"MNIST\", \"W\", \"CONV2D\"), _kr_tf_weights_loader(\"MNIST\", \"B\", \"CONV2D\")]\n )\n model.add(MaxPooling2D(pool_size=(4, 4)))\n model.add(Flatten())\n\n if from_logits:\n model.add(Dense(10, activation=\"linear\"))\n else:\n model.add(Dense(10, activation=\"softmax\"))\n\n model.layers[-1].set_weights(\n [_kr_tf_weights_loader(\"MNIST\", \"W\", \"DENSE\"), _kr_tf_weights_loader(\"MNIST\", \"B\", \"DENSE\")]\n )\n\n loss = None\n\n if loss_name == \"categorical_hinge\":\n if loss_type == \"label\":\n loss = loss_name\n elif loss_type == \"function\":\n loss = tf.keras.losses.categorical_hinge\n elif loss_type == \"class\":\n try:\n reduction = tf.keras.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.python.keras.utils.losses_utils.ReductionV2.NONE\n except AttributeError:\n raise ImportError(\"This combination of loss function options is not supported.\")\n loss = tf.keras.losses.CategoricalHinge(reduction=reduction)\n elif loss_name == \"categorical_crossentropy\":\n if loss_type == \"label\":\n if from_logits:\n raise AttributeError\n else:\n loss = loss_name\n elif loss_type == \"function\":\n if from_logits:\n\n def categorical_crossentropy(y_true, y_pred):\n return tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits=True)\n\n loss = categorical_crossentropy\n else:\n loss = tf.keras.losses.categorical_crossentropy\n elif loss_type == \"class\":\n try:\n reduction = tf.keras.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.python.keras.utils.losses_utils.ReductionV2.NONE\n except AttributeError:\n raise ImportError(\"This combination of loss function options is not supported.\")\n loss = tf.keras.losses.CategoricalCrossentropy(from_logits=from_logits, reduction=reduction)\n elif loss_name == \"sparse_categorical_crossentropy\":\n if loss_type == \"label\":\n if from_logits:\n raise AttributeError\n else:\n loss = loss_name\n elif loss_type == \"function\":\n if from_logits:\n\n def sparse_categorical_crossentropy(y_true, y_pred):\n return tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)\n\n loss = sparse_categorical_crossentropy\n else:\n loss = tf.keras.losses.sparse_categorical_crossentropy\n elif loss_type == \"class\":\n try:\n reduction = tf.keras.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.python.keras.utils.losses_utils.ReductionV2.NONE\n except AttributeError:\n raise ImportError(\"This combination of loss function options is not supported.\")\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=from_logits, reduction=reduction)\n elif loss_name == \"kullback_leibler_divergence\":\n if loss_type == \"label\":\n loss = loss_name\n elif loss_type == \"function\":\n loss = tf.keras.losses.kullback_leibler_divergence\n elif loss_type == \"class\":\n try:\n reduction = tf.keras.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.python.keras.utils.losses_utils.ReductionV2.NONE\n except AttributeError:\n raise ImportError(\"This combination of loss function options is not supported.\")\n loss = tf.keras.losses.KLDivergence(reduction=reduction)\n elif loss_name == \"cosine_similarity\":\n if loss_type == \"label\":\n loss = loss_name\n elif loss_type == \"function\":\n loss = tf.keras.losses.cosine_similarity\n elif loss_type == \"class\":\n try:\n reduction = tf.keras.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.losses.Reduction.NONE\n except AttributeError:\n try:\n reduction = tf.python.keras.utils.losses_utils.ReductionV2.NONE\n except AttributeError:\n raise ImportError(\"This combination of loss function options is not supported.\")\n loss = tf.keras.losses.CosineSimilarity(reduction=reduction)\n\n else:\n raise ValueError(\"Loss name not recognised.\")\n\n model.compile(loss=loss, optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), metrics=[\"accuracy\"])\n\n # Get classifier\n krc = KerasClassifier(model, clip_values=(0, 1), use_logits=from_logits)\n\n return krc\n\n\ndef get_image_classifier_kr_tf_binary():\n \"\"\"\n Standard TensorFlow-Keras binary classifier for unit testing\n\n :return: KerasClassifier\n \"\"\"\n # pylint: disable=E0401\n import tensorflow as tf\n from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D\n from tensorflow.keras.models import Sequential\n\n from art.estimators.classification.keras import KerasClassifier\n\n # Create simple CNN\n model = Sequential()\n model.add(Conv2D(1, kernel_size=(7, 7), activation=\"relu\", input_shape=(28, 28, 1)))\n model.layers[-1].set_weights(\n [_kr_tf_weights_loader(\"MNIST_BINARY\", \"W\", \"CONV2D\"), _kr_tf_weights_loader(\"MNIST_BINARY\", \"B\", \"CONV2D\")]\n )\n model.add(MaxPooling2D(pool_size=(4, 4)))\n model.add(Flatten())\n model.add(Dense(1, activation=\"sigmoid\"))\n\n model.layers[-1].set_weights(\n [_kr_tf_weights_loader(\"MNIST_BINARY\", \"W\", \"DENSE\"), _kr_tf_weights_loader(\"MNIST_BINARY\", \"B\", \"DENSE\")]\n )\n\n model.compile(\n loss=\"binary_crossentropy\", optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), metrics=[\"accuracy\"]\n )\n\n # Get classifier\n krc = KerasClassifier(model, clip_values=(0, 1), use_logits=False)\n\n return krc\n\n\ndef get_image_classifier_kr_tf_with_wildcard():\n \"\"\"\n Standard TensorFlow-Keras binary classifier for unit testing\n\n :return: KerasClassifier\n \"\"\"\n # pylint: disable=E0401\n from tensorflow.keras.layers import LSTM, Conv1D, Dense\n from tensorflow.keras.models import Sequential\n\n from art.estimators.classification.keras import KerasClassifier\n\n # Create simple CNN\n model = Sequential()\n model.add(Conv1D(1, 3, activation=\"relu\", input_shape=(None, 1)))\n model.add(LSTM(4))\n model.add(Dense(2, activation=\"softmax\"))\n model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\")\n\n # Get classifier\n krc = KerasClassifier(model)\n\n return krc\n\n\ndef get_image_classifier_hf(from_logits=False, load_init=True, use_maxpool=True):\n \"\"\"\n Standard HF classifier for testing.\n\n :param from_logits: Flag if model should predict logits (True) or probabilities (False).\n :type from_logits: `bool`\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :param use_maxpool: If to use a classifier with maxpool or not\n :type use_maxpool: `bool`\n :return: HuggingFaceClassifierPyTorch\n \"\"\"\n\n import torch\n from transformers.modeling_utils import PreTrainedModel\n from transformers.configuration_utils import PretrainedConfig\n from transformers.modeling_outputs import ImageClassifierOutput\n from art.estimators.classification.hugging_face import HuggingFaceClassifierPyTorch\n\n class ModelConfig(PretrainedConfig):\n def __init__(\n self,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n class Model(PreTrainedModel):\n \"\"\"\n Create model for pytorch.\n\n The weights and biases are identical to the TensorFlow model in get_classifier_tf().\n \"\"\"\n\n def __init__(self, config):\n super().__init__(config)\n\n self.conv = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=7)\n self.relu = torch.nn.ReLU()\n self.pool = torch.nn.MaxPool2d(4, 4)\n self.fullyconnected = torch.nn.Linear(25, 10)\n\n if load_init:\n w_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_CONV2D_MNIST.npy\"\n )\n )\n b_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_CONV2D_MNIST.npy\"\n )\n )\n w_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE_MNIST.npy\"\n )\n )\n b_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE_MNIST.npy\"\n )\n )\n\n w_conv2d_pt = w_conv2d.reshape((1, 1, 7, 7))\n\n self.conv.weight = torch.nn.Parameter(torch.Tensor(w_conv2d_pt))\n self.conv.bias = torch.nn.Parameter(torch.Tensor(b_conv2d))\n self.fullyconnected.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense)))\n self.fullyconnected.bias = torch.nn.Parameter(torch.Tensor(b_dense))\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n Forward function to evaluate the model\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.conv(x)\n x = self.relu(x)\n x = self.pool(x)\n x = x.reshape(-1, 25)\n x = self.fullyconnected(x)\n if not from_logits:\n x = torch.nn.functional.softmax(x, dim=1)\n return ImageClassifierOutput(\n logits=x,\n )\n\n config = ModelConfig()\n pt_model = Model(config=config)\n optimizer = torch.optim.Adam(pt_model.parameters(), lr=0.01)\n\n hf_classifier = HuggingFaceClassifierPyTorch(\n pt_model,\n loss=torch.nn.CrossEntropyLoss(reduction=\"sum\"),\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n clip_values=(0, 1),\n processor=None,\n )\n\n return hf_classifier\n\n\ndef get_image_classifier_pt(from_logits=False, load_init=True, use_maxpool=True):\n \"\"\"\n Standard PyTorch classifier for unit testing.\n\n :param from_logits: Flag if model should predict logits (True) or probabilities (False).\n :type from_logits: `bool`\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :param use_maxpool: If to use a classifier with maxpool or not\n :type use_maxpool: `bool`\n :return: PyTorchClassifier\n \"\"\"\n import torch\n\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n if use_maxpool:\n\n class Model(torch.nn.Module):\n \"\"\"\n Create model for pytorch.\n\n The weights and biases are identical to the TensorFlow model in get_classifier_tf().\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.conv = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=7)\n self.relu = torch.nn.ReLU()\n self.pool = torch.nn.MaxPool2d(4, 4)\n self.fullyconnected = torch.nn.Linear(25, 10)\n\n if load_init:\n w_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_CONV2D_MNIST.npy\"\n )\n )\n b_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_CONV2D_MNIST.npy\"\n )\n )\n w_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE_MNIST.npy\"\n )\n )\n b_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE_MNIST.npy\"\n )\n )\n\n w_conv2d_pt = w_conv2d.reshape((1, 1, 7, 7))\n\n self.conv.weight = torch.nn.Parameter(torch.Tensor(w_conv2d_pt))\n self.conv.bias = torch.nn.Parameter(torch.Tensor(b_conv2d))\n self.fullyconnected.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense)))\n self.fullyconnected.bias = torch.nn.Parameter(torch.Tensor(b_dense))\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n Forward function to evaluate the model\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.conv(x)\n x = self.relu(x)\n x = self.pool(x)\n x = x.reshape(-1, 25)\n x = self.fullyconnected(x)\n if not from_logits:\n x = torch.nn.functional.softmax(x, dim=1)\n return x\n\n else:\n\n class Model(torch.nn.Module):\n \"\"\"\n Create model for pytorch.\n Here the model does not use maxpooling. Needed for certification tests.\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.conv = torch.nn.Conv2d(\n in_channels=1, out_channels=16, kernel_size=(4, 4), dilation=(1, 1), padding=(0, 0), stride=(3, 3)\n )\n\n self.fullyconnected = torch.nn.Linear(in_features=1296, out_features=10)\n\n self.relu = torch.nn.ReLU()\n\n if load_init:\n w_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"W_CONV2D_NO_MPOOL_MNIST.npy\",\n )\n )\n b_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"B_CONV2D_NO_MPOOL_MNIST.npy\",\n )\n )\n w_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"W_DENSE_NO_MPOOL_MNIST.npy\",\n )\n )\n b_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"B_DENSE_NO_MPOOL_MNIST.npy\",\n )\n )\n\n self.conv.weight = torch.nn.Parameter(torch.Tensor(w_conv2d))\n self.conv.bias = torch.nn.Parameter(torch.Tensor(b_conv2d))\n self.fullyconnected.weight = torch.nn.Parameter(torch.Tensor(w_dense))\n self.fullyconnected.bias = torch.nn.Parameter(torch.Tensor(b_dense))\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n Forward function to evaluate the model\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.conv(x)\n x = self.relu(x)\n x = x.reshape(-1, 1296)\n x = self.fullyconnected(x)\n if not from_logits:\n x = torch.nn.functional.softmax(x, dim=1)\n return x\n\n # Define the network\n model = Model()\n\n # Define a loss function and optimizer\n loss_fn = torch.nn.CrossEntropyLoss(reduction=\"sum\")\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n # Get classifier\n ptc = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(1, 28, 28), nb_classes=10, clip_values=(0, 1)\n )\n\n return ptc\n\n\ndef get_cifar10_image_classifier_pt(from_logits=False, load_init=True):\n \"\"\"\n Standard PyTorch classifier for unit testing.\n\n :param from_logits: Flag if model should predict logits (True) or probabilities (False).\n :type from_logits: `bool`\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :return: PyTorchClassifier\n \"\"\"\n import torch\n\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n class Model(torch.nn.Module):\n \"\"\"\n Create model for pytorch.\n Here the model does not use maxpooling. Needed for certification tests.\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.conv = torch.nn.Conv2d(\n in_channels=3, out_channels=16, kernel_size=(4, 4), dilation=(1, 1), padding=(0, 0), stride=(3, 3)\n )\n\n self.fullyconnected = torch.nn.Linear(in_features=1600, out_features=10)\n\n self.relu = torch.nn.ReLU()\n\n if load_init:\n w_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"W_CONV2D_NO_MPOOL_CIFAR10.npy\",\n )\n )\n b_conv2d = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"B_CONV2D_NO_MPOOL_CIFAR10.npy\",\n )\n )\n w_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"W_DENSE_NO_MPOOL_CIFAR10.npy\",\n )\n )\n b_dense = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models\",\n \"B_DENSE_NO_MPOOL_CIFAR10.npy\",\n )\n )\n\n self.conv.weight = torch.nn.Parameter(torch.Tensor(w_conv2d))\n self.conv.bias = torch.nn.Parameter(torch.Tensor(b_conv2d))\n self.fullyconnected.weight = torch.nn.Parameter(torch.Tensor(w_dense))\n self.fullyconnected.bias = torch.nn.Parameter(torch.Tensor(b_dense))\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n Forward function to evaluate the model\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.conv(x)\n x = self.relu(x)\n x = x.reshape(-1, 1600)\n x = self.fullyconnected(x)\n if not from_logits:\n x = torch.nn.functional.softmax(x, dim=1)\n return x\n\n # Define the network\n model = Model()\n\n # Define a loss function and optimizer\n loss_fn = torch.nn.CrossEntropyLoss(reduction=\"sum\")\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n # Get classifier\n ptc = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(3, 32, 32), nb_classes=10, clip_values=(0, 1)\n )\n\n return ptc\n\n\ndef get_image_classifier_pt_functional():\n \"\"\"\n Simple PyTorch functional classifier for unit testing.\n \"\"\"\n import torch.nn as nn\n import torch.optim as optim\n\n from art.estimators.classification import PyTorchClassifier\n\n model = nn.Sequential(\n nn.Conv2d(1, 4, 5),\n nn.ReLU(),\n nn.MaxPool2d(2, 2),\n nn.Conv2d(4, 10, 5),\n nn.ReLU(),\n nn.MaxPool2d(2, 2),\n nn.Flatten(),\n nn.Linear(4 * 4 * 10, 100),\n nn.Linear(100, 10),\n )\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n\n classifier = PyTorchClassifier(\n model=model,\n clip_values=(0, 1),\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n return classifier\n\n\ndef get_classifier_bb(defences=None):\n \"\"\"\n Standard BlackBox classifier for unit testing\n\n :return: BlackBoxClassifier\n \"\"\"\n from art.estimators.classification.blackbox import BlackBoxClassifier\n from art.utils import to_categorical\n\n # define black-box classifier\n def predict(x):\n with open(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"utils/data/mnist\", \"api_output.txt\")\n ) as json_file:\n predictions = json.load(json_file)\n return to_categorical(predictions[\"values\"][: len(x)], nb_classes=10)\n\n bbc = BlackBoxClassifier(predict, (28, 28, 1), 10, clip_values=(0, 255), preprocessing_defences=defences)\n return bbc\n\n\ndef get_classifier_bb_nn(defences=None):\n \"\"\"\n Standard BlackBox Neural Network classifier for unit testing.\n\n :return: BlackBoxClassifierNeuralNetwork\n \"\"\"\n from art.estimators.classification.blackbox import BlackBoxClassifierNeuralNetwork\n from art.utils import to_categorical\n\n # define black-box classifier\n def predict(x):\n with open(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"utils/data/mnist\", \"api_output.txt\")\n ) as json_file:\n predictions = json.load(json_file)\n return to_categorical(predictions[\"values\"][: len(x)], nb_classes=10)\n\n bbc = BlackBoxClassifierNeuralNetwork(\n predict, (28, 28, 1), 10, clip_values=(0, 255), preprocessing_defences=defences\n )\n return bbc\n\n\n# ------------------------------------------------------------------------------------------------ TEST MODELS FOR IRIS\n\n\ndef get_tabular_classifier_tf(load_init=True, sess=None):\n import tensorflow as tf\n\n # sess is not required but set to None to return 2 values for v1 and v2\n classifier, sess = get_tabular_classifier_tf_v2(), None\n\n return classifier, sess\n\n\ndef get_tabular_classifier_tf_v2():\n \"\"\"\n Standard TensorFlow v2 classifier for unit testing.\n\n The following hyperparameters were used to obtain the weights and biases:\n\n * learning_rate: 0.01\n * batch size: 5\n * number of epochs: 200\n * optimizer: tf.train.AdamOptimizer\n\n The model is trained of 70% of the dataset, and 30% of the training set is used as validation split.\n\n :return: The trained model for Iris dataset and the session.\n :rtype: `TensorFlowV2Classifier`\n \"\"\"\n # pylint: disable=E0401\n import tensorflow as tf\n from tensorflow.keras import Model\n from tensorflow.keras.layers import Dense\n\n from art.estimators.classification.tensorflow import TensorFlowV2Classifier\n\n class TensorFlowModel(Model):\n \"\"\"\n Standard TensorFlow model for unit testing\n \"\"\"\n\n def __init__(self):\n super(TensorFlowModel, self).__init__()\n self.dense1 = Dense(\n 10,\n activation=\"linear\",\n kernel_initializer=_tf_weights_loader(\"IRIS\", \"W\", \"DENSE1\", tf_version=2),\n bias_initializer=_tf_weights_loader(\"IRIS\", \"B\", \"DENSE1\", tf_version=2),\n )\n self.dense2 = Dense(\n 10,\n activation=\"linear\",\n kernel_initializer=_tf_weights_loader(\"IRIS\", \"W\", \"DENSE2\", tf_version=2),\n bias_initializer=_tf_weights_loader(\"IRIS\", \"B\", \"DENSE2\", tf_version=2),\n )\n self.logits = Dense(\n 3,\n activation=\"linear\",\n kernel_initializer=_tf_weights_loader(\"IRIS\", \"W\", \"DENSE3\", tf_version=2),\n bias_initializer=_tf_weights_loader(\"IRIS\", \"B\", \"DENSE3\", tf_version=2),\n )\n\n def call(self, x):\n \"\"\"\n Call function to evaluate the model\n\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.dense1(x)\n x = self.dense2(x)\n x = self.logits(x)\n return x\n\n model = TensorFlowModel()\n loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n\n # Create the classifier\n tfc = TensorFlowV2Classifier(\n model=model, loss_object=loss_object, optimizer=optimizer, nb_classes=3, input_shape=(4,), clip_values=(0, 1)\n )\n\n return tfc\n\n\ndef get_tabular_classifier_scikit_list(clipped=False, model_list_names=None):\n from art.estimators.classification.scikitlearn import ( # ScikitlearnExtraTreeClassifier,\n ScikitlearnAdaBoostClassifier,\n ScikitlearnBaggingClassifier,\n ScikitlearnDecisionTreeClassifier,\n ScikitlearnExtraTreesClassifier,\n ScikitlearnGradientBoostingClassifier,\n ScikitlearnLogisticRegression,\n ScikitlearnRandomForestClassifier,\n ScikitlearnSVC,\n )\n\n sklearn_version = list(map(int, sklearn.__version__.split(\".\")))\n if sklearn_version[0] == 1 and sklearn_version[1] == 5:\n suffix = \"-eq-1.5.2\"\n elif sklearn_version[0] == 1 and sklearn_version[1] == 6:\n suffix = \"-eq-1.6.1\"\n else:\n suffix = \"\"\n\n available_models = {\n \"decisionTreeClassifier\": ScikitlearnDecisionTreeClassifier,\n # \"extraTreeClassifier\": ScikitlearnExtraTreeClassifier,\n \"adaBoostClassifier\": ScikitlearnAdaBoostClassifier,\n \"baggingClassifier\": ScikitlearnBaggingClassifier,\n \"extraTreesClassifier\": ScikitlearnExtraTreesClassifier,\n \"gradientBoostingClassifier\": ScikitlearnGradientBoostingClassifier,\n \"randomForestClassifier\": ScikitlearnRandomForestClassifier,\n \"logisticRegression\": ScikitlearnLogisticRegression,\n \"svc\": ScikitlearnSVC,\n \"linearSVC\": ScikitlearnSVC,\n }\n\n if model_list_names is None:\n model_dict_names = available_models\n else:\n model_dict_names = dict()\n for name in model_list_names:\n model_dict_names[name] = available_models[name]\n\n classifier_list = list()\n\n if clipped:\n for model_name, model_class in model_dict_names.items():\n model = pickle.load(\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models/scikit/\",\n \"scikit-\" + model_name + \"-iris-clipped\" + suffix + \".pickle\",\n ),\n \"rb\",\n )\n )\n classifier_list.append(model_class(model=model, clip_values=(0, 1)))\n else:\n for model_name, model_class in model_dict_names.items():\n model = pickle.load(\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"utils/resources/models/scikit/\",\n \"scikit-\" + model_name + \"-iris-unclipped\" + suffix + \".pickle\",\n ),\n \"rb\",\n )\n )\n classifier_list.append(model_class(model=model, clip_values=None))\n\n return classifier_list\n\n\ndef get_tabular_classifier_kr(load_init=True):\n \"\"\"\n Standard Keras classifier for unit testing on Iris dataset. The weights and biases are identical to the TensorFlow\n model in `get_iris_classifier_tf`.\n\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :return: The trained model for Iris dataset and the session.\n :rtype: `tuple(KerasClassifier, tf.Session)`\n \"\"\"\n import tensorflow as tf\n from tensorflow import keras\n from tensorflow.keras.layers import Dense\n from tensorflow.keras.models import Sequential\n\n from art.estimators.classification.keras import KerasClassifier\n\n # Create simple CNN\n model = Sequential()\n\n if load_init:\n model.add(\n Dense(\n 10,\n input_shape=(4,),\n activation=\"relu\",\n kernel_initializer=_tf_weights_loader(\"IRIS\", \"W\", \"DENSE1\", 2),\n bias_initializer=_tf_weights_loader(\"IRIS\", \"B\", \"DENSE1\", 2),\n )\n )\n model.add(\n Dense(\n 10,\n activation=\"relu\",\n kernel_initializer=_tf_weights_loader(\"IRIS\", \"W\", \"DENSE2\", 2),\n bias_initializer=_tf_weights_loader(\"IRIS\", \"B\", \"DENSE2\", 2),\n )\n )\n model.add(\n Dense(\n 3,\n activation=\"softmax\",\n kernel_initializer=_tf_weights_loader(\"IRIS\", \"W\", \"DENSE3\", 2),\n bias_initializer=_tf_weights_loader(\"IRIS\", \"B\", \"DENSE3\", 2),\n )\n )\n else:\n model.add(Dense(10, input_shape=(4,), activation=\"relu\"))\n model.add(Dense(10, activation=\"relu\"))\n model.add(Dense(3, activation=\"softmax\"))\n\n model.compile(\n loss=\"categorical_crossentropy\", optimizer=keras.optimizers.Adam(learning_rate=0.001), metrics=[\"accuracy\"]\n )\n\n # Get classifier\n krc = KerasClassifier(model, clip_values=(0, 1), use_logits=False, channels_first=True)\n\n return krc\n\n\ndef get_tabular_regressor_kr(load_init=True):\n \"\"\"\n Standard Keras regressor for unit testing on Diabetes dataset. Passes loss to compile() as string.\n\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :return: The trained model for Diabetes dataset and the session.\n :rtype: `tuple(KerasRegressor, tf.Session)`\n \"\"\"\n import tensorflow as tf\n from tensorflow import keras\n from tensorflow.keras.layers import Dense\n from tensorflow.keras.models import Sequential\n\n from art.estimators.regression.keras import KerasRegressor\n\n # Create simple regression model\n model = Sequential()\n\n if load_init:\n model.add(\n Dense(\n 100,\n input_shape=(10,),\n activation=\"relu\",\n kernel_initializer=_tf_weights_loader(\"DIABETES\", \"W\", \"DENSE1\", 2),\n bias_initializer=_tf_weights_loader(\"DIABETES\", \"B\", \"DENSE1\", 2),\n )\n )\n model.add(\n Dense(\n 10,\n activation=\"relu\",\n kernel_initializer=_tf_weights_loader(\"DIABETES\", \"W\", \"DENSE2\", 2),\n bias_initializer=_tf_weights_loader(\"DIABETES\", \"B\", \"DENSE2\", 2),\n )\n )\n model.add(\n Dense(\n 1,\n kernel_initializer=_tf_weights_loader(\"DIABETES\", \"W\", \"DENSE3\", 2),\n bias_initializer=_tf_weights_loader(\"DIABETES\", \"B\", \"DENSE3\", 2),\n )\n )\n else:\n model.add(Dense(100, input_shape=(10,), activation=\"relu\"))\n model.add(Dense(10, activation=\"relu\"))\n model.add(Dense(1))\n\n model.compile(loss=\"mean_squared_error\", optimizer=keras.optimizers.Adam(learning_rate=0.001), metrics=[\"accuracy\"])\n\n # Get regressor\n krc = KerasRegressor(model)\n\n return krc\n\n\nclass ARTTestException(Exception):\n def __init__(self, message):\n super().__init__(message)\n\n\nclass ARTTestFixtureNotImplemented(ARTTestException):\n def __init__(self, message, fixture_name, framework, parameters_dict=\"\"):\n super().__init__(\n \"Could NOT run test for framework: {0} due to fixture: {1}. Message was: '\"\n \"{2}' for the following parameters: {3}\".format(framework, fixture_name, message, parameters_dict)\n )\n\n\ndef get_tabular_classifier_hf(load_init=True):\n \"\"\"\n Standard Huggingface classifier for unit testing on Iris dataset.\n\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :return: Huggingface model for Iris dataset.\n :rtype: :class:`.HuggingFaceClassifierPyTorch`\n \"\"\"\n import torch\n from transformers.modeling_utils import PreTrainedModel\n from transformers.configuration_utils import PretrainedConfig\n from transformers.modeling_outputs import ImageClassifierOutput\n from art.estimators.classification.hugging_face import HuggingFaceClassifierPyTorch\n\n class ModelConfig(PretrainedConfig):\n def __init__(\n self,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n class Model(PreTrainedModel):\n \"\"\"\n Create Iris model.\n\n The weights and biases are identical to the TensorFlow model in `get_iris_classifier_tf`.\n \"\"\"\n\n def __init__(self, config):\n super().__init__(config)\n\n self.fully_connected1 = torch.nn.Linear(4, 10)\n self.fully_connected2 = torch.nn.Linear(10, 10)\n self.fully_connected3 = torch.nn.Linear(10, 3)\n\n if load_init:\n w_dense1 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE1_IRIS.npy\"\n )\n )\n b_dense1 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE1_IRIS.npy\"\n )\n )\n w_dense2 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE2_IRIS.npy\"\n )\n )\n b_dense2 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE2_IRIS.npy\"\n )\n )\n w_dense3 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE3_IRIS.npy\"\n )\n )\n b_dense3 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE3_IRIS.npy\"\n )\n )\n\n self.fully_connected1.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense1)))\n self.fully_connected1.bias = torch.nn.Parameter(torch.Tensor(b_dense1))\n self.fully_connected2.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense2)))\n self.fully_connected2.bias = torch.nn.Parameter(torch.Tensor(b_dense2))\n self.fully_connected3.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense3)))\n self.fully_connected3.bias = torch.nn.Parameter(torch.Tensor(b_dense3))\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n x = self.fully_connected1(x)\n x = self.fully_connected2(x)\n logit_output = self.fully_connected3(x)\n return ImageClassifierOutput(logits=logit_output)\n\n config = ModelConfig()\n pt_model = Model(config=config)\n optimizer = torch.optim.Adam(pt_model.parameters(), lr=0.01)\n\n hf_classifier = HuggingFaceClassifierPyTorch(\n pt_model,\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=optimizer,\n input_shape=(4,),\n nb_classes=3,\n clip_values=(0, 1),\n processor=None,\n )\n\n return hf_classifier\n\n\ndef get_tabular_classifier_pt(load_init=True):\n \"\"\"\n Standard PyTorch classifier for unit testing on Iris dataset.\n\n :param load_init: Load the initial weights if True.\n :type load_init: `bool`\n :return: Trained model for Iris dataset.\n :rtype: :class:`.PyTorchClassifier`\n \"\"\"\n import torch\n\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n class Model(torch.nn.Module):\n \"\"\"\n Create Iris model for PyTorch.\n\n The weights and biases are identical to the TensorFlow model in `get_iris_classifier_tf`.\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.fully_connected1 = torch.nn.Linear(4, 10)\n self.fully_connected2 = torch.nn.Linear(10, 10)\n self.fully_connected3 = torch.nn.Linear(10, 3)\n\n if load_init:\n w_dense1 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE1_IRIS.npy\"\n )\n )\n b_dense1 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE1_IRIS.npy\"\n )\n )\n w_dense2 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE2_IRIS.npy\"\n )\n )\n b_dense2 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE2_IRIS.npy\"\n )\n )\n w_dense3 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"W_DENSE3_IRIS.npy\"\n )\n )\n b_dense3 = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models\", \"B_DENSE3_IRIS.npy\"\n )\n )\n\n self.fully_connected1.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense1)))\n self.fully_connected1.bias = torch.nn.Parameter(torch.Tensor(b_dense1))\n self.fully_connected2.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense2)))\n self.fully_connected2.bias = torch.nn.Parameter(torch.Tensor(b_dense2))\n self.fully_connected3.weight = torch.nn.Parameter(torch.Tensor(np.transpose(w_dense3)))\n self.fully_connected3.bias = torch.nn.Parameter(torch.Tensor(b_dense3))\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n x = self.fully_connected1(x)\n x = self.fully_connected2(x)\n logit_output = self.fully_connected3(x)\n\n return logit_output\n\n # Define the network\n model = Model()\n\n # Define a loss function and optimizer\n loss_fn = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n # Get classifier\n ptc = PyTorchClassifier(\n model=model,\n loss=loss_fn,\n optimizer=optimizer,\n input_shape=(4,),\n nb_classes=3,\n clip_values=(0, 1),\n channels_first=True,\n )\n\n return ptc\n\n\ndef get_attack_classifier_pt(num_features):\n \"\"\"\n PyTorch classifier for testing membership inference attacks.\n\n :param num_features: The number of features in the attack model.\n :type num_features: `int`\n :return: Model for attack.\n :rtype: :class:`.PyTorchClassifier`\n \"\"\"\n import torch.nn as nn\n import torch.optim as optim\n\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n class AttackModel(nn.Module):\n def __init__(self, num_features):\n super(AttackModel, self).__init__()\n self.layer = nn.Linear(num_features, 1)\n self.output = nn.Sigmoid()\n\n def forward(self, x):\n return self.output(self.layer(x))\n\n # Create model\n model = AttackModel(num_features)\n\n # Define a loss function and optimizer\n loss_fn = nn.BCELoss()\n optimizer = optim.Adam(model.parameters(), lr=0.0001)\n attack_model = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(num_features,), nb_classes=2\n )\n\n return attack_model\n\n\n# -------------------------------------------------------------------------------------------- RANDOM NUMBER GENERATORS\n\n\ndef master_seed(seed=1234, set_random=True, set_numpy=True, set_tensorflow=False, set_torch=False):\n \"\"\"\n Set the seed for all random number generators used in the library. This ensures experiments reproducibility and\n stable testing.\n\n :param seed: The value to be seeded in the random number generators.\n :type seed: `int`\n :param set_random: The flag to set seed for `random`.\n :type set_random: `bool`\n :param set_numpy: The flag to set seed for `numpy`.\n :type set_numpy: `bool`\n :param set_tensorflow: The flag to set seed for `tensorflow`.\n :type set_tensorflow: `bool`\n :param set_torch: The flag to set seed for `torch`.\n :type set_torch: `bool`\n \"\"\"\n import numbers\n\n if not isinstance(seed, numbers.Integral):\n raise TypeError(\"The seed for random number generators has to be an integer.\")\n\n # Set Python seed\n if set_random:\n import random\n\n random.seed(seed)\n\n # Set Numpy seed\n if set_numpy:\n np.random.seed(seed)\n np.random.RandomState(seed)\n\n # Now try to set seed for all specific frameworks\n if set_tensorflow:\n try:\n import tensorflow as tf\n\n logger.info(\"Setting random seed for TensorFlow.\")\n tf.random.set_seed(seed)\n except ImportError:\n logger.info(\"Could not set random seed for TensorFlow.\")\n\n if set_torch:\n try:\n logger.info(\"Setting random seed for PyTorch.\")\n import torch\n\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n except ImportError:\n logger.info(\"Could not set random seed for PyTorch.\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture\ndef tabular_dl_estimator_for_attack(framework, tabular_dl_estimator):\n def _tabular_dl_estimator_for_attack(attack, clipped=True):\n classifier = tabular_dl_estimator(clipped)\n classifier_list = [classifier]\n\n classifier_tested = [\n potential_classifier\n for potential_classifier in classifier_list\n if attack.is_estimator_valid(\n estimator=potential_classifier, estimator_requirements=attack._estimator_requirements\n )\n ]\n\n if len(classifier_tested) == 0:\n raise ValueError(\"No classifier found in tabular_dl_estimator_for_attack.\")\n return classifier_tested[0]\n\n return _tabular_dl_estimator_for_attack\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_adversarial_embedding.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.attacks.poisoning.adversarial_embedding_attack import PoisoningAttackAdversarialEmbedding\nfrom art.attacks.poisoning.perturbations import add_pattern_bd\nfrom art.utils import load_dataset\n\nfrom tests.utils import master_seed, get_image_classifier_kr_tf\n\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"True\"\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 100\nNB_TRAIN = 5000\nNB_TEST = 10\nNB_EPOCHS = 1\n\n\nclass TestAdversarialEmbedding(unittest.TestCase):\n \"\"\"\n A unittest class for testing Randomized Smoothing as a post-processing step for classifiers.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Get MNIST\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n x_test, y_test = x_test[:NB_TEST], y_test[:NB_TEST]\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=301)\n\n def test_keras(self):\n \"\"\"\n Test with a KerasClassifier.\n :return:\n \"\"\"\n # Build KerasClassifier\n krc = get_image_classifier_kr_tf(loss_type=\"label\")\n\n # Get MNIST\n (x_train, y_train), (_, _) = self.mnist\n target_idx = 9\n target = np.zeros(10)\n target[target_idx] = 1\n target2 = np.zeros(10)\n target2[(target_idx + 1) % 10] = 1\n\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n\n emb_attack = PoisoningAttackAdversarialEmbedding(krc, backdoor, 2, target)\n classifier = emb_attack.poison_estimator(x_train, y_train, nb_epochs=NB_EPOCHS)\n\n data, labels, bd = emb_attack.get_training_data()\n self.assertEqual(x_train.shape, data.shape)\n self.assertEqual(y_train.shape, labels.shape)\n self.assertEqual(bd.shape, (len(x_train), 2))\n\n # Assert successful cloning of classifier model\n self.assertTrue(classifier is not krc)\n\n emb_attack2 = PoisoningAttackAdversarialEmbedding(krc, backdoor, 2, [(target, target2)])\n _ = emb_attack2.poison_estimator(x_train, y_train, nb_epochs=NB_EPOCHS)\n\n data, labels, bd = emb_attack2.get_training_data()\n self.assertEqual(x_train.shape, data.shape)\n self.assertEqual(y_train.shape, labels.shape)\n self.assertEqual(bd.shape, (len(x_train), 2))\n\n _ = PoisoningAttackAdversarialEmbedding(krc, backdoor, 2, [(target, target2)], pp_poison=[0.4])\n\n def test_errors(self):\n krc = get_image_classifier_kr_tf(loss_type=\"function\")\n krc_valid = get_image_classifier_kr_tf(loss_type=\"label\")\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n target_idx = 9\n target = np.zeros(10)\n target[target_idx] = 1\n target2 = np.zeros(10)\n target2[(target_idx + 1) % 10] = 1\n\n # invalid loss function\n with self.assertRaises(TypeError):\n _ = PoisoningAttackAdversarialEmbedding(krc, backdoor, 2, target)\n\n # feature layer not real name\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, \"not a layer\", target)\n\n # feature layer out of range\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, target)\n\n # target misshaped\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, np.expand_dims(target, axis=0))\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, [target])\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, target, regularization=-1)\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, target, discriminator_layer_1=-1)\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, target, discriminator_layer_2=-1)\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, target, pp_poison=-1)\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, [(target, target2)], pp_poison=[])\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackAdversarialEmbedding(krc_valid, backdoor, 20, [(target, target2)], pp_poison=[-1])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_adversarial_patch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport keras\nimport tensorflow as tf\n\nfrom art.attacks.evasion.adversarial_patch.adversarial_patch import (\n AdversarialPatch,\n AdversarialPatchNumpy,\n AdversarialPatchPyTorch,\n)\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.utils import TestBase, master_seed\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr\nfrom tests.utils import get_tabular_classifier_kr, get_image_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestAdversarialPatch(TestBase):\n \"\"\"\n A unittest class for testing Adversarial Patch attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.n_train = 1\n cls.n_test = 1\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def setUp(self):\n master_seed(seed=1234)\n super().setUp()\n\n def test_3_tensorflow_v2_framework(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n tfc, _ = get_image_classifier_tf(from_logits=True)\n\n attack_ap = AdversarialPatch(\n tfc,\n rotation_max=0.5,\n scale_min=0.4,\n scale_max=0.41,\n learning_rate=5.0,\n batch_size=10,\n max_iter=10,\n patch_shape=(28, 28, 1),\n verbose=False,\n )\n\n target = np.zeros(self.x_train_mnist.shape[0])\n patch_adv, _ = attack_ap.generate(self.x_train_mnist, target, shuffle=False)\n\n self.assertAlmostEqual(patch_adv[2, 8, 0], 0.4, delta=0.05)\n self.assertAlmostEqual(patch_adv[14, 14, 0], 0.0, delta=0.05)\n self.assertAlmostEqual(float(np.sum(patch_adv)), 339.1322937011719, delta=1.0)\n\n # insert_transformed_patch\n x_out = attack_ap.insert_transformed_patch(\n self.x_train_mnist[0], np.ones((14, 14, 1)), np.asarray([[2, 13], [2, 18], [12, 22], [8, 13]])\n )\n x_out_expected = np.array(\n [\n 0.0,\n 0.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 0.84313726,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.1764706,\n 0.7294118,\n 0.99215686,\n 0.99215686,\n 0.5882353,\n 0.10588235,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ],\n dtype=np.float32,\n )\n np.testing.assert_almost_equal(x_out[15, :, 0], x_out_expected, decimal=3)\n\n mask = np.ones((1, 28, 28)).astype(bool)\n attack_ap.apply_patch(x=self.x_train_mnist, scale=0.1, mask=mask)\n attack_ap.reset_patch(initial_patch_value=None)\n attack_ap.reset_patch(initial_patch_value=1.0)\n attack_ap.reset_patch(initial_patch_value=patch_adv)\n\n @unittest.skipIf(\n int(keras.__version__.split(\".\")[0]) == 2 and int(keras.__version__.split(\".\")[1]) < 3,\n reason=\"Skip unittests if not Keras>=2.3.\",\n )\n def test_6_keras(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n krc = get_image_classifier_kr(from_logits=True)\n\n attack_ap = AdversarialPatch(\n krc,\n rotation_max=0.5,\n scale_min=0.4,\n scale_max=0.41,\n learning_rate=5.0,\n batch_size=10,\n max_iter=5,\n verbose=False,\n )\n\n target = np.zeros(self.x_train_mnist.shape[0])\n patch_adv, _ = attack_ap.generate(self.x_train_mnist, target)\n\n self.assertAlmostEqual(patch_adv[8, 8, 0], 0.67151666, delta=0.05)\n self.assertAlmostEqual(patch_adv[14, 14, 0], 0.6292826, delta=0.05)\n self.assertAlmostEqual(float(np.sum(patch_adv)), 424.31439208984375, delta=1.0)\n\n # insert_transformed_patch\n x_out = attack_ap.insert_transformed_patch(\n self.x_train_mnist[0], np.ones((14, 14, 1)), np.asarray([[2, 13], [2, 18], [12, 22], [8, 13]])\n )\n x_out_expected = np.array(\n [\n 0.0,\n 0.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 0.84313726,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.1764706,\n 0.7294118,\n 0.99215686,\n 0.99215686,\n 0.5882353,\n 0.10588235,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ],\n dtype=np.float32,\n )\n np.testing.assert_almost_equal(x_out[15, :, 0], x_out_expected, decimal=3)\n\n def test_4_pytorch(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n ptc = get_image_classifier_pt(from_logits=True)\n\n x_train = np.reshape(self.x_train_mnist, (self.n_train, 1, 28, 28)).astype(np.float32)\n\n attack_ap = AdversarialPatch(\n ptc,\n rotation_max=0.5,\n scale_min=0.4,\n scale_max=0.41,\n learning_rate=5.0,\n batch_size=10,\n max_iter=5,\n patch_shape=(1, 28, 28),\n verbose=False,\n )\n\n target = np.zeros(self.x_train_mnist.shape[0])\n patch_adv, _ = attack_ap.generate(x_train, target)\n\n self.assertAlmostEqual(patch_adv[0, 8, 8], 0.5, delta=0.05)\n self.assertAlmostEqual(patch_adv[0, 14, 14], 0.5, delta=0.05)\n self.assertAlmostEqual(float(np.sum(patch_adv)), 380.2155115437587, delta=4.0)\n\n mask = np.ones((1, 28, 28)).astype(bool)\n attack_ap.apply_patch(x=x_train, scale=0.1, mask=mask)\n attack_ap.reset_patch(initial_patch_value=None)\n attack_ap.reset_patch(initial_patch_value=1.0)\n attack_ap.reset_patch(initial_patch_value=patch_adv)\n with self.assertRaises(ValueError):\n attack_ap.reset_patch(initial_patch_value=np.array([1, 2, 3]))\n\n # Numpy\n attack_ap = AdversarialPatchNumpy(\n ptc,\n rotation_max=0.5,\n scale_min=0.4,\n scale_max=0.41,\n learning_rate=5.0,\n batch_size=10,\n max_iter=5,\n verbose=False,\n )\n\n target = np.zeros(self.x_train_mnist.shape[0])\n patch_adv, _ = attack_ap.generate(x_train, target)\n\n self.assertAlmostEqual(patch_adv[0, 8, 8], 0.6715167, delta=0.05)\n self.assertAlmostEqual(patch_adv[0, 14, 14], 0.6292826, delta=0.05)\n self.assertAlmostEqual(float(np.sum(patch_adv)), 424.31439208984375, delta=4.0)\n\n mask = np.ones((1, 28, 28)).astype(bool)\n attack_ap.apply_patch(x=x_train, scale=0.1, mask=mask)\n attack_ap.reset_patch(initial_patch_value=None)\n attack_ap.reset_patch(initial_patch_value=1.0)\n attack_ap.reset_patch(initial_patch_value=patch_adv)\n with self.assertRaises(ValueError):\n attack_ap.reset_patch(initial_patch_value=np.array([1, 2, 3]))\n\n def test_5_failure_feature_vectors(self):\n classifier = get_tabular_classifier_kr()\n classifier._clip_values = (0, 1)\n\n # Assert that value error is raised for feature vectors\n with self.assertRaises(ValueError) as context:\n _ = AdversarialPatch(classifier=classifier)\n\n self.assertIn(\n \"Unexpected input_shape in estimator detected. AdversarialPatch is expecting images or videos as input.\",\n str(context.exception),\n )\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n krc = get_image_classifier_kr(from_logits=True)\n\n # AdversarialPatch\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, rotation_max=\"1\")\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, rotation_max=-1)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, scale_min=\"1\")\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, scale_min=-1.0)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, scale_max=1)\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, scale_max=2.0)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, learning_rate=1)\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(krc, learning_rate=-1.0)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, max_iter=1.0)\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, batch_size=1.0)\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatch(ptc, verbose=\"true\")\n\n # AdversarialPatchPyTorch\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchPyTorch(ptc, distortion_scale_max=\"1\")\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchPyTorch(ptc, patch_type=\"triangle\")\n\n # AdversarialPatchNumpy\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, rotation_max=\"1\")\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, rotation_max=-1)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, scale_min=\"1\")\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, scale_min=-1.0)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, scale_max=1)\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, scale_max=2.0)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, learning_rate=\"1\")\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(krc, learning_rate=-1.0)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, max_iter=1.0)\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, batch_size=1.0)\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = AdversarialPatchNumpy(ptc, verbose=\"true\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(AdversarialPatch, [BaseEstimator, NeuralNetworkMixin, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\n\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_attack_repr(image_dl_estimator):\n\n from art.attacks.evasion import ProjectedGradientDescentNumpy\n\n classifier, _ = image_dl_estimator(from_logits=True)\n\n attack = ProjectedGradientDescentNumpy(\n estimator=classifier,\n targeted=True,\n decay=0.5,\n )\n print(repr(attack))\n assert repr(attack) == (\n \"ProjectedGradientDescentNumpy(norm=inf, eps=0.3, eps_step=0.1, targeted=True, \"\n + \"num_random_init=0, batch_size=32, minimal=False, summary_writer=None, decay=0.5, \"\n + \"max_iter=100, random_eps=False, verbose=True, )\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_backdoor_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_pattern_bd, add_single_bd, insert_image\nfrom art.utils import to_categorical\n\nfrom tests.utils import TestBase, master_seed, get_image_classifier_kr\n\nlogger = logging.getLogger(__name__)\n\nPP_POISON = 0.33\nNB_EPOCHS = 3\n\n\nclass TestBackdoorAttack(TestBase):\n \"\"\"\n A unittest class for testing Backdoor Poisoning attack.\n \"\"\"\n\n def setUp(self):\n master_seed(seed=301)\n self.backdoor_path = os.path.join(\n os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))),\n \"utils\",\n \"data\",\n \"backdoors\",\n \"alert.png\",\n )\n super().setUp()\n\n @staticmethod\n def poison_dataset(x_clean, y_clean, poison_func):\n x_poison = np.copy(x_clean)\n y_poison = np.copy(y_clean)\n is_poison = np.zeros(np.shape(y_poison)[0])\n\n for i in range(10):\n src = i\n tgt = (i + 1) % 10\n n_points_in_tgt = np.round(np.sum(np.argmax(y_clean, axis=1) == tgt))\n num_poison = int((PP_POISON * n_points_in_tgt) / (1 - PP_POISON))\n src_imgs = np.copy(x_clean[np.argmax(y_clean, axis=1) == src])\n\n n_points_in_src = np.shape(src_imgs)[0]\n if num_poison:\n indices_to_be_poisoned = np.random.choice(n_points_in_src, num_poison)\n\n imgs_to_be_poisoned = src_imgs[indices_to_be_poisoned]\n backdoor_attack = PoisoningAttackBackdoor(poison_func)\n poison_images, poison_labels = backdoor_attack.poison(\n imgs_to_be_poisoned, y=to_categorical(np.ones(num_poison) * tgt, 10)\n )\n x_poison = np.append(x_poison, poison_images, axis=0)\n y_poison = np.append(y_poison, poison_labels, axis=0)\n is_poison = np.append(is_poison, np.ones(num_poison))\n\n is_poison = is_poison != 0\n\n return is_poison, x_poison, y_poison\n\n def poison_func_1(self, x):\n max_val = np.max(self.x_train_mnist)\n return np.expand_dims(add_pattern_bd(x.squeeze(3), pixel_value=max_val), axis=3)\n\n def poison_func_2(self, x):\n max_val = np.max(self.x_train_mnist)\n return np.expand_dims(add_single_bd(x.squeeze(3), pixel_value=max_val), axis=3)\n\n def poison_func_3(self, x):\n return insert_image(x, backdoor_path=self.backdoor_path, size=(5, 5), random=False, x_shift=3, y_shift=3)\n\n def poison_func_4(self, x):\n return insert_image(x, backdoor_path=self.backdoor_path, size=(5, 5), random=True)\n\n def poison_func_5(self, x):\n return insert_image(x, backdoor_path=self.backdoor_path, random=True, size=(100, 100))\n\n def poison_func_6(self, x):\n return insert_image(x, backdoor_path=self.backdoor_path, random=True, size=(100, 100))\n\n def test_backdoor_pattern(self):\n \"\"\"\n Test the backdoor attack with a pattern-based perturbation can be trained on classifier\n \"\"\"\n\n krc = get_image_classifier_kr()\n (is_poison_train, x_poisoned_raw, y_poisoned_raw) = self.poison_dataset(\n self.x_train_mnist, self.y_train_mnist, self.poison_func_1\n )\n # Shuffle training data\n n_train = np.shape(y_poisoned_raw)[0]\n shuffled_indices = np.arange(n_train)\n np.random.shuffle(shuffled_indices)\n x_train = x_poisoned_raw[shuffled_indices]\n y_train = y_poisoned_raw[shuffled_indices]\n\n krc.fit(x_train, y_train, nb_epochs=NB_EPOCHS, batch_size=32)\n\n def test_backdoor_pixel(self):\n \"\"\"\n Test the backdoor attack with a pixel-based perturbation can be trained on classifier\n \"\"\"\n\n krc = get_image_classifier_kr()\n (is_poison_train, x_poisoned_raw, y_poisoned_raw) = self.poison_dataset(\n self.x_train_mnist, self.y_train_mnist, self.poison_func_2\n )\n\n # Shuffle training data\n n_train = np.shape(y_poisoned_raw)[0]\n shuffled_indices = np.arange(n_train)\n np.random.shuffle(shuffled_indices)\n x_train = x_poisoned_raw[shuffled_indices]\n y_train = y_poisoned_raw[shuffled_indices]\n\n krc.fit(x_train, y_train, nb_epochs=NB_EPOCHS, batch_size=32)\n\n def test_backdoor_image(self):\n \"\"\"\n Test the backdoor attack with an image-based perturbation can be trained on classifier\n \"\"\"\n krc = get_image_classifier_kr()\n (is_poison_train, x_poisoned_raw, y_poisoned_raw) = self.poison_dataset(\n self.x_train_mnist, self.y_train_mnist, self.poison_func_3\n )\n\n # Shuffle training data\n n_train = np.shape(y_poisoned_raw)[0]\n shuffled_indices = np.arange(n_train)\n np.random.shuffle(shuffled_indices)\n x_train = x_poisoned_raw[shuffled_indices]\n y_train = y_poisoned_raw[shuffled_indices]\n\n krc.fit(x_train, y_train, nb_epochs=NB_EPOCHS, batch_size=32)\n\n def test_multiple_perturbations(self):\n \"\"\"\n Test using multiple perturbation functions in the same attack can be trained on classifier\n \"\"\"\n\n krc = get_image_classifier_kr()\n (is_poison_train, x_poisoned_raw, y_poisoned_raw) = self.poison_dataset(\n self.x_train_mnist, self.y_train_mnist, [self.poison_func_4, self.poison_func_1]\n )\n\n # Shuffle training data\n n_train = np.shape(y_poisoned_raw)[0]\n shuffled_indices = np.arange(n_train)\n np.random.shuffle(shuffled_indices)\n x_train = x_poisoned_raw[shuffled_indices]\n y_train = y_poisoned_raw[shuffled_indices]\n\n krc.fit(x_train, y_train, nb_epochs=NB_EPOCHS, batch_size=32)\n\n def test_image_failure_modes(self):\n \"\"\"\n Tests failure modes for image perturbation functions\n \"\"\"\n backdoor_attack = PoisoningAttackBackdoor(self.poison_func_5)\n adv_target = np.argmax(self.y_train_mnist) + 1 % 10\n with self.assertRaises(ValueError) as context:\n backdoor_attack.poison(self.x_train_mnist, y=adv_target)\n\n self.assertIn(\"Backdoor does not fit inside original image\", str(context.exception))\n\n backdoor_attack = PoisoningAttackBackdoor(self.poison_func_6)\n\n with self.assertRaises(ValueError) as context:\n backdoor_attack.poison(np.zeros(5), y=np.ones(5))\n\n self.assertIn(\"Invalid array shape\", str(context.exception))\n\n def test_check_params(self):\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackBackdoor(\"self.poison_func_5\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_carlini.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\n# import keras\n# import keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion.carlini import CarliniL0Method, CarliniL2Method, CarliniLInfMethod\n\n# from art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.utils import random_targets\n\n# from art.utils import to_categorical\n\nfrom tests.utils import TestBase, master_seed\nfrom tests.utils import get_image_classifier_tf\n\nfrom tests.utils import get_image_classifier_pt\n\n# from test.utils import get_image_classifier_kr\n# from tests.utils import get_tabular_classifier_tf, get_tabular_classifier_kr, get_tabular_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestCarlini(TestBase):\n \"\"\"\n A unittest class for testing the Carlini L2 attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 10\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def setUp(self):\n master_seed(seed=1234)\n super().setUp()\n\n def test_tensorflow_failure_attack_L2(self):\n \"\"\"\n Test the corner case when attack is failed.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowV2Classifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # Failure attack\n cl2m = CarliniL2Method(\n classifier=tfc,\n targeted=True,\n max_iter=0,\n binary_search_steps=0,\n learning_rate=0,\n initial_const=1,\n verbose=False,\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = cl2m.generate(self.x_test_mnist, **params)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n np.testing.assert_array_almost_equal(self.x_test_mnist, x_test_adv, decimal=3)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_tensorflow_mnist_L2(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # First attack\n cl2m = CarliniL2Method(classifier=tfc, targeted=True, max_iter=10, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = cl2m.generate(self.x_test_mnist, **params)\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"CW2 Target: %s\", target)\n logger.debug(\"CW2 Actual: %s\", y_pred_adv)\n logger.info(\"CW2 Success Rate: %.2f\", (np.sum(target == y_pred_adv) / float(len(target))))\n self.assertTrue((target == y_pred_adv).any())\n\n # Second attack, no batching\n cl2m = CarliniL2Method(classifier=tfc, targeted=False, max_iter=10, batch_size=1, verbose=False)\n x_test_adv = cl2m.generate(self.x_test_mnist)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"CW2 Target: %s\", target)\n logger.debug(\"CW2 Actual: %s\", y_pred_adv)\n logger.info(\"CW2 Success Rate: %.2f\", (np.sum(target == y_pred_adv) / float(len(target))))\n self.assertTrue((target != y_pred_adv).any())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n # @unittest.skipIf(\n # not (int(keras.__version__.split(\".\")[0]) == 2 and int(keras.__version__.split(\".\")[1]) >= 3),\n # reason=\"Minimal version of Keras or TensorFlow required.\",\n # )\n # def test_keras_mnist_L2(self):\n # \"\"\"\n # Second test with the KerasClassifier.\n # :return:\n # \"\"\"\n # x_test_original = self.x_test_mnist.copy()\n #\n # # Build KerasClassifier\n # krc = get_image_classifier_kr(from_logits=True)\n #\n # # First attack\n # cl2m = CarliniL2Method(classifier=krc, targeted=True, max_iter=10, verbose=False)\n # y_target = [6, 6, 7, 4, 9, 7, 9, 0, 1, 0]\n # x_test_adv = cl2m.generate(self.x_test_mnist, y=to_categorical(y_target, nb_classes=10))\n # self.assertFalse((self.x_test_mnist == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW2 Target: %s\", y_target)\n # logger.debug(\"CW2 Actual: %s\", y_pred_adv)\n # logger.info(\"CW2 Success Rate: %.2f\", (np.sum(y_target == y_pred_adv) / float(len(y_target))))\n # self.assertTrue((y_target == y_pred_adv).any())\n #\n # # Second attack\n # cl2m = CarliniL2Method(classifier=krc, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = cl2m.generate(self.x_test_mnist)\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW2 Target: %s\", y_target)\n # logger.debug(\"CW2 Actual: %s\", y_pred_adv)\n # logger.info(\"CW2 Success Rate: %.2f\", (np.sum(y_target != y_pred_adv) / float(len(y_target))))\n # self.assertTrue((y_target != y_pred_adv).any())\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n #\n # # Clean-up\n # k.clear_session()\n #\n # def test_pytorch_mnist_L2(self):\n # \"\"\"\n # Third test with the PyTorchClassifier.\n # :return:\n # \"\"\"\n # x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n # x_test_original = x_test.copy()\n #\n # # Build PyTorchClassifier\n # ptc = get_image_classifier_pt(from_logits=True)\n #\n # # First attack\n # cl2m = CarliniL2Method(classifier=ptc, targeted=True, max_iter=10, verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n # x_test_adv = cl2m.generate(x_test, **params)\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target == y_pred_adv).any())\n # logger.info(\"CW2 Success Rate: %.2f\", (sum(target == y_pred_adv) / float(len(target))))\n #\n # # Second attack\n # cl2m = CarliniL2Method(classifier=ptc, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = cl2m.generate(x_test)\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target != y_pred_adv).any())\n # logger.info(\"CW2 Success Rate: %.2f\", (sum(target != y_pred_adv) / float(len(target))))\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_classifier_type_check_fail_L2(self):\n backend_test_classifier_type_check_fail(CarliniL2Method, [BaseEstimator, ClassGradientsMixin])\n\n # def test_keras_iris_clipped_L2(self):\n # classifier = get_tabular_classifier_kr()\n # attack = CarliniL2Method(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n #\n # def test_keras_iris_unbounded_L2(self):\n # classifier = get_tabular_classifier_kr()\n #\n # # Recreate a classifier without clip values\n # classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n # attack = CarliniL2Method(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n\n # def test_tensorflow_iris_L2(self):\n # classifier, _ = get_tabular_classifier_tf()\n #\n # # Test untargeted attack\n # attack = CarliniL2Method(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n #\n # # Test targeted attack\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = CarliniL2Method(classifier, targeted=True, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n # accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Success rate of targeted C&W on Iris: %.2f%%\", (accuracy * 100))\n\n # def test_pytorch_iris_L2(self):\n # classifier = get_tabular_classifier_pt()\n # attack = CarliniL2Method(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n\n # def test_scikitlearn_L2(self):\n # from sklearn.linear_model import LogisticRegression\n # from sklearn.svm import SVC, LinearSVC\n #\n # from art.estimators.classification.scikitlearn import SklearnClassifier\n #\n # scikitlearn_test_cases = [\n # LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n # SVC(gamma=\"auto\"),\n # LinearSVC(),\n # ]\n #\n # x_test_original = self.x_test_iris.copy()\n #\n # for model in scikitlearn_test_cases:\n # classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n # classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n #\n # # Test untargeted attack\n # attack = CarliniL2Method(classifier, targeted=False, max_iter=2, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\n # \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with C&W adversarial examples: \" \"%.2f%%\",\n # (accuracy * 100),\n # )\n #\n # # Test targeted attack\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = CarliniL2Method(classifier, targeted=True, max_iter=2, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n # accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\n # \"Success rate of \" + classifier.__class__.__name__ + \" on targeted C&W on Iris: %.2f%%\",\n # (accuracy * 100),\n # )\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params_L2(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, binary_search_steps=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, binary_search_steps=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, max_iter=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, max_halving=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, max_halving=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, max_doubling=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, max_doubling=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, batch_size=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL2Method(ptc, batch_size=-1)\n\n \"\"\"\n A unittest class for testing the Carlini LInf attack.\n \"\"\"\n\n def test_tensorflow_failure_attack_LInf(self):\n \"\"\"\n Test the corner case when attack is failed.\n :return:\n \"\"\"\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # Failure attack\n clinfm = CarliniLInfMethod(classifier=tfc, targeted=True, max_iter=0, learning_rate=0, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = clinfm.generate(self.x_test_mnist, **params)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n self.assertTrue(np.allclose(self.x_test_mnist, x_test_adv, atol=1e-3))\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_tensorflow_mnist_LInf(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # First attack\n clinfm = CarliniLInfMethod(\n classifier=tfc, targeted=True, max_iter=10, initial_const=1, largest_const=1.1, verbose=False\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = clinfm.generate(self.x_test_mnist, **params)\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"CW0 Target: %s\", target)\n logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target == y_pred_adv) / float(len(target))))\n self.assertTrue((target == y_pred_adv).any())\n\n # Second attack, no batching\n clinfm = CarliniLInfMethod(\n classifier=tfc, targeted=False, max_iter=10, initial_const=1, largest_const=1.1, verbose=False\n )\n x_test_adv = clinfm.generate(self.x_test_mnist)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"CW0 Target: %s\", target)\n logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target != y_pred_adv) / float(len(target))))\n self.assertTrue((target != y_pred_adv).any())\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n # @unittest.skipIf(\n # not (int(keras.__version__.split(\".\")[0]) == 2 and int(keras.__version__.split(\".\")[1]) >= 3),\n # reason=\"Keras 2.3 or later or TensorFlow-Keras required to support selected combination of loss \"\n # \"function and logits.\",\n # )\n # def test_keras_mnist_LInf(self):\n # \"\"\"\n # Second test with the KerasClassifier.\n # :return:\n # \"\"\"\n # # Build KerasClassifier\n # krc = get_image_classifier_kr(from_logits=True)\n #\n # # First attack\n # clinfm = CarliniLInfMethod(classifier=krc, targeted=True, max_iter=10, verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, krc.nb_classes)}\n # x_test_adv = clinfm.generate(self.x_test_mnist, **params)\n # self.assertFalse((self.x_test_mnist == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.000001)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW0 Target: %s\", target)\n # logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n # logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target == y_pred_adv) / float(len(target))))\n # self.assertTrue((target == y_pred_adv).any())\n #\n # # Second attack\n # clinfm = CarliniLInfMethod(classifier=krc, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = clinfm.generate(self.x_test_mnist)\n # self.assertLessEqual(np.amax(x_test_adv), 1.000001)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW0 Target: %s\", target)\n # logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n # logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target != y_pred_adv) / float(len(target))))\n # self.assertTrue((target != y_pred_adv).any())\n #\n # # Clean-up\n # k.clear_session()\n #\n # def test_pytorch_mnist_LInf(self):\n # \"\"\"\n # Third test with the PyTorchClassifier.\n # :return:\n # \"\"\"\n # x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n #\n # # Build PyTorchClassifier\n # ptc = get_image_classifier_pt(from_logits=True)\n #\n # # First attack\n # clinfm = CarliniLInfMethod(classifier=ptc, targeted=True, max_iter=10, verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n # x_test_adv = clinfm.generate(x_test, **params)\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0 + 1e-6)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target == y_pred_adv).any())\n #\n # # Second attack\n # clinfm = CarliniLInfMethod(classifier=ptc, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = clinfm.generate(x_test)\n # self.assertLessEqual(np.amax(x_test_adv), 1.0 + 1e-6)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n #\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target != y_pred_adv).any())\n\n def test_classifier_type_check_fail_LInf(self):\n backend_test_classifier_type_check_fail(CarliniLInfMethod, [BaseEstimator, ClassGradientsMixin])\n\n # def test_keras_iris_clipped_LInf(self):\n # classifier = get_tabular_classifier_kr()\n # attack = CarliniLInfMethod(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n #\n # def test_keras_iris_unbounded_LInf(self):\n # classifier = get_tabular_classifier_kr()\n #\n # # Recreate a classifier without clip values\n # classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n # attack = CarliniLInfMethod(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n\n # def test_tensorflow_iris_LInf(self):\n # classifier, _ = get_tabular_classifier_tf()\n #\n # # Test untargeted attack\n # attack = CarliniLInfMethod(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n #\n # # Test targeted attack\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = CarliniLInfMethod(classifier, targeted=True, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n # accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Success rate of targeted C&W on Iris: %.2f%%\", (accuracy * 100))\n\n # def test_pytorch_iris_LInf(self):\n # classifier = get_tabular_classifier_pt()\n # attack = CarliniLInfMethod(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris.astype(np.float32))\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n\n # def test_scikitlearn_LInf(self):\n # from sklearn.linear_model import LogisticRegression\n # from sklearn.svm import SVC, LinearSVC\n #\n # from art.estimators.classification.scikitlearn import SklearnClassifier\n #\n # scikitlearn_test_cases = [\n # LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n # SVC(gamma=\"auto\"),\n # LinearSVC(),\n # ]\n #\n # x_test_original = self.x_test_iris.copy()\n #\n # for model in scikitlearn_test_cases:\n # classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n # classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n #\n # # Test untargeted attack\n # attack = CarliniLInfMethod(classifier, targeted=False, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\n # \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with C&W adversarial examples: \" \"%.2f%%\",\n # (accuracy * 100),\n # )\n #\n # # Test targeted attack\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = CarliniLInfMethod(classifier, targeted=True, max_iter=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n # accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\n # \"Success rate of \" + classifier.__class__.__name__ + \" on targeted C&W on Iris: %.2f%%\",\n # (accuracy * 100),\n # )\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params_LInf(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, max_iter=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, decrease_factor=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, decrease_factor=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, initial_const=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, initial_const=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, largest_const=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, largest_const=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, const_factor=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniLInfMethod(ptc, const_factor=-1)\n\n \"\"\"\n A unittest class for testing the Carlini L0 attack.\n \"\"\"\n\n def test_tensorflow_failure_attack_L0(self):\n \"\"\"\n Test the corner case when attack is failed.\n :return:\n \"\"\"\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # Failure attack\n cl0m = CarliniL0Method(\n classifier=tfc,\n targeted=False,\n max_iter=1,\n batch_size=10,\n learning_rate=0.01,\n binary_search_steps=1,\n warm_start=True,\n verbose=False,\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n _ = cl0m.generate(self.x_test_mnist, **params)\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # self.assertTrue(np.allclose(self.x_test_mnist, x_test_adv, atol=1e-3))\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_tensorflow_mnist_L0(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # First attack\n cl0m = CarliniL0Method(\n classifier=tfc, targeted=True, max_iter=1, batch_size=10, binary_search_steps=1, verbose=False\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = cl0m.generate(self.x_test_mnist, **params)\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW0 Target: %s\", target)\n # logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n # logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target == y_pred_adv) / float(len(target))))\n # self.assertTrue((target == y_pred_adv).any())\n\n # Second attack, no batching\n cl0m = CarliniL0Method(\n classifier=tfc, targeted=False, max_iter=1, batch_size=10, binary_search_steps=1, verbose=False\n )\n x_test_adv = cl0m.generate(self.x_test_mnist)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"CW0 Target: %s\", target)\n logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target != y_pred_adv) / float(len(target))))\n self.assertTrue((target != y_pred_adv).any())\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n # @unittest.skipIf(\n # not (int(keras.__version__.split(\".\")[0]) == 2 and int(keras.__version__.split(\".\")[1]) >= 3),\n # reason=\"Keras 2.3 or later or TensorFlow-Keras required to support selected combination of loss \"\n # \"function and logits.\",\n # )\n # def test_keras_mnist_L0(self):\n # \"\"\"\n # Second test with the KerasClassifier.\n # :return:\n # \"\"\"\n # # Build KerasClassifier\n # krc = get_image_classifier_kr(from_logits=True)\n #\n # # First attack\n # cl0m = CarliniL0Method(classifier=krc, targeted=True, max_iter=10, eps=0.5, verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, krc.nb_classes)}\n # x_test_adv = cl0m.generate(self.x_test_mnist, **params)\n # self.assertFalse((self.x_test_mnist == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.000001)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW0 Target: %s\", target)\n # logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n # logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target == y_pred_adv) / float(len(target))))\n # self.assertTrue((target == y_pred_adv).any())\n #\n # # Second attack\n # cl0m = CarliniL0Method(classifier=krc, targeted=False, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = cl0m.generate(self.x_test_mnist)\n # self.assertLessEqual(np.amax(x_test_adv), 1.000001)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug(\"CW0 Target: %s\", target)\n # logger.debug(\"CW0 Actual: %s\", y_pred_adv)\n # logger.info(\"CW0 Success Rate: %.2f\", (np.sum(target != y_pred_adv) / float(len(target))))\n # self.assertTrue((target != y_pred_adv).any())\n #\n # # Clean-up\n # k.clear_session()\n #\n # def test_pytorch_mnist_L0(self):\n # \"\"\"\n # Third test with the PyTorchClassifier.\n # :return:\n # \"\"\"\n # x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n #\n # # Build PyTorchClassifier\n # ptc = get_image_classifier_pt(from_logits=True)\n #\n # # First attack\n # cl0m = CarliniL0Method(classifier=ptc, targeted=True, max_iter=10, eps=0.5, verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n # x_test_adv = cl0m.generate(x_test, **params)\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0 + 1e-6)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target == y_pred_adv).any())\n #\n # # Second attack\n # cl0m = CarliniL0Method(classifier=ptc, targeted=False, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = cl0m.generate(x_test)\n # self.assertLessEqual(np.amax(x_test_adv), 1.0 + 1e-6)\n # self.assertGreaterEqual(np.amin(x_test_adv), -1e-6)\n #\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target != y_pred_adv).any())\n\n def test_classifier_type_check_fail_L0(self):\n backend_test_classifier_type_check_fail(CarliniL0Method, [BaseEstimator, ClassGradientsMixin])\n\n # def test_keras_iris_clipped_L0(self):\n # classifier = get_tabular_classifier_kr()\n # attack = CarliniL0Method(classifier, targeted=False, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n #\n # def test_keras_iris_unbounded_L0(self):\n # classifier = get_tabular_classifier_kr()\n #\n # # Recreate a classifier without clip values\n # classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n # attack = CarliniL0Method(classifier, targeted=False, max_iter=10, eps=1, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n\n # def test_tensorflow_iris_L0(self):\n # classifier, _ = get_tabular_classifier_tf()\n #\n # # Test untargeted attack\n # attack = CarliniL0Method(classifier, targeted=False, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n #\n # # Test targeted attack\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = CarliniL0Method(classifier, targeted=True, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n # accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Success rate of targeted C&W on Iris: %.2f%%\", (accuracy * 100))\n\n # def test_pytorch_iris_L0(self):\n # classifier = get_tabular_classifier_pt()\n # attack = CarliniL0Method(classifier, targeted=False, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris.astype(np.float32))\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with C&W adversarial examples: %.2f%%\", (accuracy * 100))\n\n # def test_scikitlearn_L0(self):\n # from sklearn.linear_model import LogisticRegression\n # from sklearn.svm import SVC, LinearSVC\n #\n # from art.estimators.classification.scikitlearn import SklearnClassifier\n #\n # scikitlearn_test_cases = [\n # LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n # SVC(gamma=\"auto\"),\n # LinearSVC(),\n # ]\n #\n # x_test_original = self.x_test_iris.copy()\n #\n # for model in scikitlearn_test_cases:\n # classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n # classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n #\n # # Test untargeted attack\n # attack = CarliniL0Method(classifier, targeted=False, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n # accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\n # \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with C&W adversarial examples: \" \"%.2f%%\",\n # (accuracy * 100),\n # )\n #\n # # Test targeted attack\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = CarliniL0Method(classifier, targeted=True, max_iter=10, eps=0.5, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n #\n # predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n # accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\n # \"Success rate of \" + classifier.__class__.__name__ + \" on targeted C&W on Iris: %.2f%%\",\n # (accuracy * 100),\n # )\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params_L0(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, binary_search_steps=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, binary_search_steps=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, max_iter=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, max_halving=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, max_halving=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, max_doubling=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, max_doubling=-1)\n\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, batch_size=\"1.0\")\n with self.assertRaises(ValueError):\n _ = CarliniL0Method(ptc, batch_size=-1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_copycat_cnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport keras\nimport keras.backend as k\nimport numpy as np\nimport tensorflow as tf\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom keras.layers import Conv2D, Dense, Flatten, MaxPooling2D\nfrom keras.models import Sequential\n\nfrom art.attacks.extraction.copycat_cnn import CopycatCNN\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n master_seed,\n)\n\nlogger = logging.getLogger(__name__)\n\nNB_EPOCHS = 20\nNB_STOLEN = 100\n\n\nclass TestCopycatCNN(TestBase):\n \"\"\"\n A unittest class for testing the CopycatCNN attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n def test_keras_classifier(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n # Build KerasClassifier\n victim_krc = get_image_classifier_kr()\n\n # Create simple CNN\n model = Sequential()\n model.add(Conv2D(1, kernel_size=(7, 7), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(MaxPooling2D(pool_size=(4, 4)))\n model.add(Flatten())\n model.add(Dense(10, activation=\"softmax\"))\n loss = keras.losses.categorical_crossentropy\n try:\n from keras.optimizers import Adam\n\n optimizer = Adam(learning_rate=0.001)\n except ImportError:\n from keras.optimizers import adam_v2\n\n optimizer = adam_v2.Adam(learning_rate=0.001)\n model.compile(loss=loss, optimizer=optimizer, metrics=[\"accuracy\"])\n\n # Get classifier\n thieved_krc = KerasClassifier(model, clip_values=(0, 1), use_logits=False)\n\n # Create attack\n copycat_cnn = CopycatCNN(\n classifier=victim_krc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n )\n thieved_krc = copycat_cnn.extract(x=self.x_train_mnist, thieved_classifier=thieved_krc)\n\n victim_preds = np.argmax(victim_krc.predict(x=self.x_train_mnist[:100]), axis=1)\n thieved_preds = np.argmax(thieved_krc.predict(x=self.x_train_mnist[:100]), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Clean-up\n k.clear_session()\n\n def test_pytorch_classifier(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_train = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n\n # Build PyTorchClassifier\n victim_ptc = get_image_classifier_pt()\n\n class Model(nn.Module):\n \"\"\"\n Create model for pytorch.\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=7)\n self.pool = nn.MaxPool2d(4, 4)\n self.fullyconnected = nn.Linear(25, 10)\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n \"\"\"\n Forward function to evaluate the model\n\n :param x: Input to the model\n :return: Prediction of the model\n \"\"\"\n x = self.conv(x)\n x = torch.nn.functional.relu(x)\n x = self.pool(x)\n x = x.reshape(-1, 25)\n x = self.fullyconnected(x)\n x = torch.nn.functional.softmax(x, dim=1)\n\n return x\n\n # Define the network\n model = Model()\n\n # Define a loss function and optimizer\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n\n # Get classifier\n thieved_ptc = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(1, 28, 28), nb_classes=10, clip_values=(0, 1)\n )\n\n # Create attack\n copycat_cnn = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n )\n\n thieved_ptc = copycat_cnn.extract(x=x_train, thieved_classifier=thieved_ptc)\n victim_preds = np.argmax(victim_ptc.predict(x=x_train[:100]), axis=1)\n thieved_preds = np.argmax(thieved_ptc.predict(x=x_train[:100]), axis=1)\n\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n with self.assertRaises(ValueError):\n _ = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=-1,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n )\n\n with self.assertRaises(ValueError):\n _ = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=self.batch_size,\n batch_size_query=-1,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n )\n\n with self.assertRaises(ValueError):\n _ = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=-1,\n nb_stolen=NB_STOLEN,\n )\n\n with self.assertRaises(ValueError):\n _ = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=-1,\n )\n\n with self.assertRaises(ValueError):\n _ = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n use_probability=\"True\",\n )\n\n\nclass TestCopycatCNNVectors(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n def test_keras_iris(self):\n \"\"\"\n Second test for Keras.\n :return:\n \"\"\"\n # Build KerasClassifier\n victim_krc = get_tabular_classifier_kr()\n\n # Create simple CNN\n model = Sequential()\n model.add(Dense(10, input_shape=(4,), activation=\"relu\"))\n model.add(Dense(10, activation=\"relu\"))\n model.add(Dense(3, activation=\"softmax\"))\n try:\n from keras.optimizers import Adam\n\n optimizer = Adam(learning_rate=0.001)\n except ImportError:\n from keras.optimizers import adam_v2\n\n optimizer = adam_v2.Adam(learning_rate=0.001)\n model.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])\n\n # Get classifier\n thieved_krc = KerasClassifier(model, clip_values=(0, 1), use_logits=False, channels_first=True)\n\n # Create attack\n copycat_cnn = CopycatCNN(\n classifier=victim_krc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n )\n thieved_krc = copycat_cnn.extract(x=self.x_train_iris, thieved_classifier=thieved_krc)\n\n victim_preds = np.argmax(victim_krc.predict(x=self.x_train_iris[:100]), axis=1)\n thieved_preds = np.argmax(thieved_krc.predict(x=self.x_train_iris[:100]), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Clean-up\n k.clear_session()\n\n def test_pytorch_iris(self):\n \"\"\"\n Third test for PyTorch.\n :return:\n \"\"\"\n # Build PyTorchClassifier\n victim_ptc = get_tabular_classifier_pt()\n\n class Model(nn.Module):\n \"\"\"\n Create Iris model for PyTorch.\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.fully_connected1 = nn.Linear(4, 10)\n self.fully_connected2 = nn.Linear(10, 10)\n self.fully_connected3 = nn.Linear(10, 3)\n\n # pylint: disable=W0221\n # disable pylint because of API requirements for function\n def forward(self, x):\n x = self.fully_connected1(x)\n x = self.fully_connected2(x)\n logit_output = self.fully_connected3(x)\n\n return logit_output\n\n # Define the network\n model = Model()\n\n # Define a loss function and optimizer\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n\n # Get classifier\n thieved_ptc = PyTorchClassifier(\n model=model,\n loss=loss_fn,\n optimizer=optimizer,\n input_shape=(4,),\n nb_classes=3,\n clip_values=(0, 1),\n channels_first=True,\n )\n\n # Create attack\n copycat_cnn = CopycatCNN(\n classifier=victim_ptc,\n batch_size_fit=self.batch_size,\n batch_size_query=self.batch_size,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n )\n thieved_ptc = copycat_cnn.extract(x=self.x_train_iris, thieved_classifier=thieved_ptc)\n\n victim_preds = np.argmax(victim_ptc.predict(x=self.x_train_iris[:100]), axis=1)\n thieved_preds = np.argmax(thieved_ptc.predict(x=self.x_train_iris[:100]), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_decision_tree_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.datasets import load_digits\nimport numpy as np\n\nfrom art.attacks.evasion.decision_tree_attack import DecisionTreeAttack\nfrom art.estimators.classification.scikitlearn import SklearnClassifier\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\n\nfrom tests.utils import TestBase, master_seed\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestDecisionTreeAttack(TestBase):\n \"\"\"\n A unittest class for testing the decision tree attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n # Get MNIST\n digits = load_digits()\n cls.X = digits.data\n cls.y = digits.target\n\n def test_scikitlearn(self):\n clf = DecisionTreeClassifier()\n x_original = self.X.copy()\n clf.fit(self.X, self.y)\n clf_art = SklearnClassifier(clf)\n attack = DecisionTreeAttack(clf_art, verbose=False)\n adv = attack.generate(self.X[:25])\n # all crafting should succeed\n self.assertTrue(np.sum(clf.predict(adv) == clf.predict(self.X[:25])) == 0)\n targets = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9])\n adv = attack.generate(self.X[:25], targets)\n # all targeted crafting should succeed as well\n self.assertTrue(np.sum(clf.predict(adv) == targets) == 25.0)\n # Check that X has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_original - self.X))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n clf = DecisionTreeClassifier()\n clf.fit(self.X, self.y)\n clf_art = SklearnClassifier(clf)\n\n with self.assertRaises(ValueError):\n _ = DecisionTreeAttack(clf_art, offset=-1)\n\n with self.assertRaises(ValueError):\n _ = DecisionTreeAttack(clf_art, verbose=\"False\")\n\n def test_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(DecisionTreeAttack, [ScikitlearnDecisionTreeClassifier])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_deepfool.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport keras\nimport numpy as np\n\nfrom art.attacks.evasion.deepfool import DeepFool\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.utils import get_labels_np_array\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestDeepFool(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 11\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n @unittest.skipIf(\n not (int(keras.__version__.split(\".\")[0]) == 2 and int(keras.__version__.split(\".\")[1]) >= 3),\n reason=\"Minimal version of Keras or TensorFlow required.\",\n )\n def test_8_keras_mnist(self):\n x_test_original = self.x_test_mnist.copy()\n\n # Keras classifier\n classifier = get_image_classifier_kr(from_logits=True)\n\n scores = classifier._model.evaluate(self.x_train_mnist, self.y_train_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on training set: %.2f%%\", (scores[1] * 100))\n scores = classifier._model.evaluate(self.x_test_mnist, self.y_test_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on test set: %.2f%%\", (scores[1] * 100))\n\n attack = DeepFool(classifier, max_iter=5, batch_size=11, verbose=False)\n x_train_adv = attack.generate(self.x_train_mnist)\n x_test_adv = attack.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_train_mnist == x_train_adv).all())\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((self.y_train_mnist == train_y_pred).all())\n self.assertFalse((self.y_test_mnist == test_y_pred).all())\n\n sum_0 = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(self.y_train_mnist, axis=1))\n accuracy_0 = sum_0 / self.y_train_mnist.shape[0]\n logger.info(\"Accuracy on adversarial train examples: %.2f%%\", (accuracy_0 * 100))\n\n sum_1 = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1))\n accuracy_1 = sum_1 / self.y_test_mnist.shape[0]\n logger.info(\"Accuracy on adversarial test examples: %.2f%%\", (accuracy_1 * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_3_tensorflow_mnist(self):\n x_test_original = self.x_test_mnist.copy()\n\n # Create basic CNN on MNIST using TensorFlow\n classifier, sess = get_image_classifier_tf(from_logits=True)\n\n scores = get_labels_np_array(classifier.predict(self.x_train_mnist))\n sum2 = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1))\n accuracy = sum2 / self.y_train_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", (accuracy * 100))\n\n scores = get_labels_np_array(classifier.predict(self.x_test_mnist))\n sum3 = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1))\n accuracy = sum3 / self.y_test_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", (accuracy * 100))\n\n attack = DeepFool(classifier, max_iter=5, batch_size=11, verbose=False)\n x_train_adv = attack.generate(self.x_train_mnist)\n x_test_adv = attack.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_train_mnist == x_train_adv).all())\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((self.y_train_mnist == train_y_pred).all())\n self.assertFalse((self.y_test_mnist == test_y_pred).all())\n\n sum4 = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(self.y_train_mnist, axis=1))\n accuracy = sum4 / self.y_train_mnist.shape[0]\n logger.info(\"Accuracy on adversarial train examples: %.2f%%\", (accuracy * 100))\n\n sum5 = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1))\n accuracy = sum5 / self.y_test_mnist.shape[0]\n logger.info(\"Accuracy on adversarial test examples: %.2f%%\", (accuracy * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_5_pytorch_mnist(self):\n x_train = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n x_test_original = x_test.copy()\n\n # Create basic PyTorch model\n classifier = get_image_classifier_pt(from_logits=True)\n\n scores = get_labels_np_array(classifier.predict(x_train))\n sum6 = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1))\n accuracy = sum6 / self.y_train_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", (accuracy * 100))\n\n scores = get_labels_np_array(classifier.predict(x_test))\n sum7 = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1))\n accuracy = sum7 / self.y_test_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on test set: %.2f%%\", (accuracy * 100))\n\n attack = DeepFool(classifier, max_iter=5, batch_size=11, verbose=False)\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train == x_train_adv).all())\n self.assertFalse((x_test == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((self.y_train_mnist == train_y_pred).all())\n self.assertFalse((self.y_test_mnist == test_y_pred).all())\n\n sum8 = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(self.y_train_mnist, axis=1))\n accuracy = sum8 / self.y_train_mnist.shape[0]\n logger.info(\"Accuracy on adversarial train examples: %.2f%%\", (accuracy * 100))\n\n sum9 = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1))\n accuracy = sum9 / self.y_test_mnist.shape[0]\n logger.info(\"Accuracy on adversarial test examples: %.2f%%\", (accuracy * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n @unittest.skipIf(\n not (int(keras.__version__.split(\".\")[0]) == 2 and int(keras.__version__.split(\".\")[1]) >= 3),\n reason=\"Minimal version of Keras or TensorFlow required.\",\n )\n def test_9_keras_mnist_partial_grads(self):\n classifier = get_image_classifier_kr(from_logits=True)\n attack = DeepFool(classifier, max_iter=2, nb_grads=3, verbose=False)\n x_test_adv = attack.generate(self.x_test_mnist)\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((self.y_test_mnist == test_y_pred).all())\n sum10 = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1))\n accuracy = sum10 / self.y_test_mnist.shape[0]\n logger.info(\"Accuracy on adversarial test examples: %.2f%%\", (accuracy * 100))\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(DeepFool, [BaseEstimator, ClassGradientsMixin])\n\n def test_6_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n attack = DeepFool(classifier, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with DeepFool adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_7_keras_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = DeepFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with DeepFool adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_2_tensorflow_iris(self):\n classifier, _ = get_tabular_classifier_tf()\n\n attack = DeepFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with DeepFool adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_4_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n\n attack = DeepFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n accuracy = np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with DeepFool adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = DeepFool(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = DeepFool(ptc, nb_grads=-1)\n\n with self.assertRaises(ValueError):\n _ = DeepFool(ptc, epsilon=-1)\n\n with self.assertRaises(ValueError):\n _ = DeepFool(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = DeepFool(ptc, verbose=\"False\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_elastic_net.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion.elastic_net import ElasticNet\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.utils import random_targets, to_categorical\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n master_seed,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestElasticNet(TestBase):\n \"\"\"\n A unittest class for testing the ElasticNet attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.n_train = 500\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def setUp(self):\n master_seed(seed=1234)\n super().setUp()\n\n def test_2_tensorflow_failure_attack(self):\n \"\"\"\n Test the corner case when attack fails.\n :return:\n \"\"\"\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # Failure attack\n ead = ElasticNet(\n classifier=tfc,\n targeted=True,\n max_iter=0,\n binary_search_steps=0,\n learning_rate=0,\n initial_const=1,\n verbose=False,\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = ead.generate(self.x_test_mnist, **params)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n np.testing.assert_almost_equal(self.x_test_mnist, x_test_adv, 3)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_4_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf(from_logits=True)\n\n # First attack\n ead = ElasticNet(classifier=tfc, targeted=True, max_iter=2, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = ead.generate(self.x_test_mnist, **params)\n expected_x_test_adv = np.asarray(\n [\n 0.45284095,\n 0.43225235,\n 0.577448,\n 1.0,\n 0.16554962,\n 0.3587564,\n 0.19202651,\n 0.04293771,\n 0.0,\n 0.25811037,\n 0.0,\n 0.0290696,\n 0.0,\n 0.136172,\n 0.6153389,\n 0.12244645,\n 0.0,\n 0.7586619,\n 0.8366919,\n 0.22206311,\n 0.12455986,\n 0.02862802,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n np.testing.assert_array_almost_equal(x_test_adv[0, 14, :, 0], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", target)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate on MNIST: %.2f%%\", (100 * sum(target == y_pred_adv) / len(target)))\n self.assertTrue((target == y_pred_adv).any())\n\n # Second attack\n ead = ElasticNet(classifier=tfc, targeted=False, max_iter=2, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = ead.generate(self.x_test_mnist, **params)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", target)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate on MNIST: %.2f%%\", (100 * sum(target != y_pred_adv) / float(len(target))))\n np.testing.assert_array_equal(y_pred_adv, np.asarray([7, 1, 1, 4, 4, 1, 4, 4, 4, 4]))\n\n # Third attack\n ead = ElasticNet(classifier=tfc, targeted=False, max_iter=2, verbose=False)\n params = {}\n x_test_adv = ead.generate(self.x_test_mnist, **params)\n expected_x_test_adv = np.asarray(\n [\n 0.22766514,\n 0.21726893,\n 0.22802338,\n 0.06168516,\n 0.0,\n 0.0,\n 0.04722975,\n 0.0,\n 0.0,\n 0.0,\n 0.05455382,\n 0.0,\n 0.0,\n 0.0,\n 0.38886347,\n 0.10553087,\n 0.32285708,\n 0.9794307,\n 0.7589039,\n 0.16586718,\n 0.15969527,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n np.testing.assert_array_almost_equal(x_test_adv[0, 14, :, 0], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n y_pred = np.argmax(tfc.predict(self.x_test_mnist), axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", y_pred)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate: %.2f%%\", (100 * sum(y_pred != y_pred_adv) / float(len(y_pred))))\n np.testing.assert_array_equal(y_pred_adv, np.asarray([0, 4, 7, 9, 0, 7, 7, 3, 0, 7]))\n\n # First attack without batching\n ead_wob = ElasticNet(classifier=tfc, targeted=True, max_iter=2, batch_size=1, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = ead_wob.generate(self.x_test_mnist, **params)\n expected_x_test_adv = np.asarray(\n [\n 0.32568744,\n 0.31085464,\n 0.43235543,\n 1.0,\n 0.2433605,\n 0.3411813,\n 0.49469775,\n 0.2603619,\n 0.0,\n 0.35584357,\n 0.0,\n 0.2046029,\n 0.0,\n 0.08249304,\n 1.0,\n 0.35813788,\n 0.62945133,\n 1.0,\n 0.32154015,\n 0.3497113,\n 0.7613426,\n 0.36533928,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n np.testing.assert_array_almost_equal(x_test_adv[0, 14, :, 0], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", target)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate: %.2f%%\", (100 * sum(target == y_pred_adv) / float(len(target))))\n self.assertTrue((target == y_pred_adv).any())\n\n # Second attack without batching\n ead_wob = ElasticNet(classifier=tfc, targeted=False, max_iter=2, batch_size=1, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = ead_wob.generate(self.x_test_mnist, **params)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", target)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate: %.2f%%\", (100 * sum(target != y_pred_adv) / float(len(target))))\n np.testing.assert_array_equal(y_pred_adv, np.asarray([7, 1, 1, 4, 4, 1, 4, 4, 4, 4]))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n ead = ElasticNet(classifier=tfc, targeted=False, max_iter=2, verbose=False, decision_rule=\"L1\")\n _ = ead.generate(self.x_test_mnist, **params)\n ead = ElasticNet(classifier=tfc, targeted=False, max_iter=2, verbose=False, decision_rule=\"L2\")\n _ = ead.generate(self.x_test_mnist, **params)\n with self.assertRaises(ValueError):\n _ = ElasticNet(classifier=tfc, targeted=False, max_iter=2, verbose=False, decision_rule=\"L3\")\n\n # Close session\n if sess is not None:\n sess.close()\n\n def test_9a_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # First attack\n ead = ElasticNet(classifier=krc, targeted=True, max_iter=2, verbose=False)\n y_target = to_categorical(np.asarray([6, 6, 7, 4, 9, 7, 9, 0, 1, 0]), nb_classes=10)\n x_test_adv = ead.generate(self.x_test_mnist, y=y_target)\n expected_x_test_adv = np.asarray(\n [\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 7.8193319e-04,\n 5.5843666e-03,\n 0.0000000e00,\n 0.0000000e00,\n 4.9869284e-01,\n 1.0000000e00,\n 6.4663666e-01,\n 3.4855194e-03,\n 3.5087438e-03,\n 0.0000000e00,\n 9.8862723e-03,\n 3.8835173e-03,\n 3.0151173e-02,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n ]\n )\n np.testing.assert_array_almost_equal(x_test_adv[2, 14, :, 0], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(y_target, axis=1)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", target)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate: %.2f%%\", (100 * sum(target == y_pred_adv) / float(len(target))))\n self.assertTrue((target == y_pred_adv).any())\n\n # Second attack\n ead = ElasticNet(classifier=krc, targeted=False, max_iter=2, verbose=False)\n y_target = to_categorical(np.asarray([9, 5, 6, 7, 1, 6, 1, 5, 8, 5]), nb_classes=10)\n x_test_adv = ead.generate(self.x_test_mnist, y=y_target)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n logger.debug(\"EAD target: %s\", y_target)\n logger.debug(\"EAD actual: %s\", y_pred_adv)\n logger.info(\"EAD success rate: %.2f\", (100 * sum(target != y_pred_adv) / float(len(target))))\n self.assertTrue((target != y_pred_adv).any())\n np.testing.assert_array_equal(y_pred_adv, np.asarray([7, 1, 1, 4, 4, 1, 4, 4, 4, 4]))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n k.clear_session()\n\n def test_6_pytorch_mnist(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n x_test_original = x_test.copy()\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt(from_logits=False)\n\n # First attack\n ead = ElasticNet(classifier=ptc, targeted=True, max_iter=2, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n x_test_adv = ead.generate(x_test, **params)\n expected_x_test_adv = np.asarray(\n [\n 0.01758931,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.00698278,\n 0.0,\n 0.11318438,\n 0.36223832,\n 0.54720753,\n 0.93125045,\n 1.0,\n 0.9999359,\n 0.8638486,\n 0.6354147,\n 0.5600332,\n 0.24081531,\n 0.25882354,\n 0.00899846,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n np.testing.assert_array_almost_equal(x_test_adv[2, 0, :, 14], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Second attack\n ead = ElasticNet(classifier=ptc, targeted=False, max_iter=2, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n x_test_adv = ead.generate(x_test, **params)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n self.assertTrue((target != y_pred_adv).any())\n np.testing.assert_array_equal(y_pred_adv, np.asarray([7, 1, 1, 4, 4, 1, 4, 4, 4, 4]))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(ElasticNet, [BaseEstimator, ClassGradientsMixin])\n\n def test_8_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n attack = ElasticNet(classifier, targeted=False, max_iter=10, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n expected_x_test_adv = np.asarray([0.8670352, 0.4624909, 0.6453267, 0.23096858])\n np.testing.assert_array_almost_equal(x_test_adv[0, :], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n np.testing.assert_array_equal(\n predictions_adv,\n np.asarray(\n [\n 1,\n 1,\n 1,\n 2,\n 1,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 1,\n 1,\n 2,\n 1,\n 1,\n 2,\n 2,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 2,\n 1,\n 0,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 1,\n 1,\n 2,\n ]\n ),\n )\n accuracy = 1.0 - np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"EAD success rate on Iris: %.2f%%\", (accuracy * 100))\n\n k.clear_session()\n\n def test_9_keras_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = ElasticNet(classifier, targeted=False, max_iter=10, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n expected_x_test_adv = np.asarray([0.8670352, 0.4624909, 0.6453267, 0.23096858])\n np.testing.assert_array_almost_equal(x_test_adv[0, :], expected_x_test_adv, decimal=6)\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n np.testing.assert_array_equal(\n predictions_adv,\n np.asarray(\n [\n 1,\n 1,\n 1,\n 2,\n 1,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 1,\n 1,\n 2,\n 1,\n 1,\n 2,\n 2,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 2,\n 1,\n 0,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 1,\n 1,\n 2,\n ]\n ),\n )\n accuracy = 1.0 - np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"EAD success rate on Iris: %.2f%%\", (accuracy * 100))\n\n k.clear_session()\n\n def test_3_tensorflow_iris(self):\n classifier, sess = get_tabular_classifier_tf()\n\n # Test untargeted attack\n attack = ElasticNet(classifier, targeted=False, max_iter=10, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n expected_x_test_adv = np.asarray([0.84810126, 0.43320203, 0.70404345, 0.29160658])\n np.testing.assert_array_almost_equal(x_test_adv[0, :], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n np.testing.assert_array_equal(\n predictions_adv,\n np.asarray(\n [\n 1,\n 2,\n 2,\n 2,\n 1,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 2,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 1,\n 2,\n 1,\n 2,\n 1,\n 0,\n 1,\n 2,\n 1,\n 2,\n 0,\n 2,\n 2,\n 1,\n 1,\n 2,\n ]\n ),\n )\n accuracy = 1.0 - np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"EAD success rate on Iris: %.2f%%\", (accuracy * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = ElasticNet(classifier, targeted=True, max_iter=10, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n expected_x_test_adv = np.asarray([0.88713187, 0.5239736, 0.49900988, 0.05677444])\n np.testing.assert_array_almost_equal(x_test_adv[0, :], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n np.testing.assert_array_equal(\n predictions_adv,\n np.asarray(\n [\n 0,\n 0,\n 0,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 0,\n 2,\n 0,\n 0,\n 2,\n 2,\n 0,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 0,\n 0,\n 0,\n 2,\n 0,\n 2,\n 2,\n 2,\n 2,\n 2,\n 0,\n 0,\n 0,\n 2,\n 2,\n 2,\n 2,\n 2,\n 0,\n 2,\n ]\n ),\n )\n\n accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Targeted EAD success rate on Iris: %.2f%%\", (accuracy * 100))\n\n # Close session\n if sess is not None:\n sess.close()\n\n def test_5_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n attack = ElasticNet(classifier, targeted=False, max_iter=10, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris.astype(np.float32))\n expected_x_test_adv = np.asarray([0.84810126, 0.43320203, 0.70404345, 0.29160658])\n np.testing.assert_array_almost_equal(x_test_adv[0, :], expected_x_test_adv, decimal=6)\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n np.testing.assert_array_equal(\n predictions_adv,\n np.asarray(\n [\n 1,\n 2,\n 2,\n 2,\n 1,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 2,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 1,\n 2,\n 1,\n 2,\n 1,\n 0,\n 1,\n 2,\n 1,\n 2,\n 0,\n 2,\n 2,\n 1,\n 1,\n 2,\n ]\n ),\n )\n\n accuracy = 1.0 - np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"EAD success rate on Iris: %.2f%%\", (accuracy * 100))\n\n def test_7_scikitlearn(self):\n from sklearn.linear_model import LogisticRegression\n from sklearn.svm import SVC, LinearSVC\n\n from art.estimators.classification.scikitlearn import SklearnClassifier\n\n scikitlearn_test_cases = [\n LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n SVC(gamma=\"auto\"),\n LinearSVC(),\n ]\n\n x_test_original = self.x_test_iris.copy()\n\n for model in scikitlearn_test_cases:\n classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n\n # Test untargeted attack\n attack = ElasticNet(classifier, targeted=False, max_iter=2, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == predictions_adv).all())\n accuracy = 1.0 - np.sum(predictions_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"EAD success rate of \" + classifier.__class__.__name__ + \" on Iris: %.2f%%\", (accuracy * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = ElasticNet(classifier, targeted=True, max_iter=2, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n\n predictions_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == predictions_adv).any())\n accuracy = np.sum(predictions_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Targeted EAD success rate of \" + classifier.__class__.__name__ + \" on Iris: %.2f%%\", (accuracy * 100)\n )\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, binary_search_steps=\"1.0\")\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, binary_search_steps=-1)\n\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, max_iter=\"1.0\")\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, batch_size=\"1.0\")\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, decision_rule=1.0)\n\n with self.assertRaises(ValueError):\n _ = ElasticNet(ptc, verbose=\"True\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_feature_collision.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.poisoning.feature_collision_attack import FeatureCollisionAttack\n\nfrom tests.utils import TestBase, master_seed, get_image_classifier_pt\n\nlogger = logging.getLogger(__name__)\n\nNB_EPOCHS = 3\n\n\nclass TestFeatureCollision(TestBase):\n \"\"\"\n A unittest class for testing Feature Collision attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.n_train = 10\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train].astype(np.float32)\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test].astype(np.float32)\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def setUp(self):\n master_seed(seed=301)\n super().setUp()\n\n @staticmethod\n def poison_dataset(classifier, x_clean, y_clean):\n x_poison = np.copy(x_clean)\n y_poison = np.copy(y_clean)\n base = np.expand_dims(x_clean[0], axis=0)\n target = np.expand_dims(x_clean[1], axis=0)\n feature_layer = classifier.layer_names[-1]\n attack = FeatureCollisionAttack(classifier, target, feature_layer, max_iter=1)\n attack, attack_label = attack.poison(base)\n x_poison = np.append(x_poison, attack, axis=0)\n y_poison = np.append(y_poison, attack_label, axis=0)\n\n return x_poison, y_poison\n\n def test_pytorch(self):\n \"\"\"\n Test working PyTorch implementation.\n :return:\n \"\"\"\n ptc = get_image_classifier_pt()\n x_train_mnist = np.transpose(self.x_train_mnist, (0, 3, 2, 1))\n x_adv, y_adv = self.poison_dataset(ptc, x_train_mnist, self.y_train_mnist)\n ptc.fit(x_adv, y_adv, nb_epochs=NB_EPOCHS, batch_size=32)\n\n def test_check_params(self):\n\n krc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, learning_rate=-1)\n\n with self.assertRaises(TypeError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1.0)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, decay_coeff=-1)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, stopping_tol=-1)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, obj_threshold=-1)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, watermark=1)\n\n with self.assertRaises(ValueError):\n _ = FeatureCollisionAttack(krc, target=self.x_train_mnist, feature_layer=1, verbose=\"true\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_functionally_equivalent_extraction.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nfrom os.path import dirname, join\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras.models import load_model # noqa: E402\n\nfrom art.attacks.extraction.functionally_equivalent_extraction import FunctionallyEquivalentExtraction # noqa: E402\nfrom art.estimators.classification.keras import KerasClassifier # noqa: E402\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin # noqa: E402\nfrom art.estimators.classification.classifier import ClassifierMixin # noqa: E402\n\nfrom tests.utils import TestBase, master_seed # noqa: E402\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail # noqa: E402\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestFunctionallyEquivalentExtraction(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 11\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n model = load_model(\n join(\n *[\n dirname(dirname(dirname(__file__))),\n \"utils\",\n \"data\",\n \"test_models\",\n \"model_test_functionally_equivalent_extraction.keras\",\n ]\n )\n )\n\n np.random.seed(0)\n num_neurons = 4\n img_rows = 28\n img_cols = 28\n num_channels = 1\n\n x_train = cls.x_train_mnist.reshape(cls.n_train, img_rows, img_cols, num_channels)\n x_test = cls.x_test_mnist.reshape(cls.n_test, img_rows, img_cols, num_channels)\n\n x_train = x_train.reshape((x_train.shape[0], num_channels * img_rows * img_cols)).astype(\"float64\")\n x_test = x_test.reshape((x_test.shape[0], num_channels * img_rows * img_cols)).astype(\"float64\")\n\n mean = np.mean(x_train)\n std = np.std(x_train)\n\n x_train = (x_train - mean) / std\n\n classifier = KerasClassifier(model=model, use_logits=True, clip_values=(0, 1))\n\n cls.fee = FunctionallyEquivalentExtraction(classifier=classifier, num_neurons=num_neurons)\n fee_extracted = cls.fee.extract(\n x_train[0:10],\n delta_0=3.5,\n fraction_true=0.03,\n rel_diff_slope=0.00001,\n rel_diff_value=0.000001,\n delta_init_value=0.1,\n delta_value_max=1,\n d2_min=0.00000000000000000001,\n d_step=0.5,\n delta_sign=0.02,\n unit_vector_scale=10000,\n ftol=1e-8,\n )\n fee_extracted.predict(x=x_test)\n\n def setUp(self):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUp()\n\n def test_critical_points(self):\n critical_points_expected_3 = np.array(\n [\n [\n 8.19612722e00,\n 2.40234234e00,\n 8.11413371e00,\n 7.94101531e00,\n -1.64722226e01,\n -1.53566335e00,\n -9.27154880e00,\n -8.26856781e-01,\n -1.22067410e01,\n 1.81122897e01,\n -1.14411810e01,\n -1.06700356e01,\n 1.76700751e00,\n -1.44054912e01,\n -5.28370124e00,\n -1.08603133e01,\n 2.05269904e01,\n 1.03932195e01,\n -4.62041357e-01,\n -6.13056036e00,\n 1.01374552e01,\n 6.11873056e00,\n 7.58182205e00,\n -1.09542778e00,\n -2.04999226e01,\n -2.97122895e00,\n -7.13609668e00,\n 8.51287487e00,\n 1.51798091e01,\n -7.40462919e00,\n 6.47220303e00,\n 2.37904961e01,\n -9.89343243e00,\n 2.07037990e01,\n -1.18469995e01,\n 4.66014249e-01,\n 1.07996639e00,\n 1.35746905e00,\n -1.16853480e01,\n -8.27577097e00,\n -1.00543017e01,\n 2.98982708e00,\n 2.74501483e00,\n 3.19727707e01,\n 1.79812979e01,\n -7.31448680e00,\n 3.12882099e00,\n 1.42259270e01,\n -1.20116164e00,\n -1.15201765e00,\n -1.99859457e-01,\n 1.20841289e01,\n -1.19523648e01,\n -5.57303640e00,\n 6.31669418e00,\n 4.62891424e00,\n 3.29784354e00,\n -4.68515009e00,\n 1.24825670e01,\n 2.84173957e01,\n 4.80899022e00,\n -2.96498671e00,\n 9.37975526e00,\n -8.99773017e00,\n -9.93387795e00,\n 4.07207263e-02,\n -3.64651703e01,\n -1.51009010e01,\n -5.60036686e00,\n -1.82016261e01,\n -1.31984843e01,\n -5.76157615e00,\n -2.10197772e01,\n -6.71164094e00,\n -6.81701158e00,\n -3.42162237e-01,\n 1.46960376e01,\n 1.74777042e00,\n -2.74825771e-02,\n 1.39753817e00,\n 1.90176640e00,\n -1.28122402e01,\n -1.08234764e00,\n 2.62797920e00,\n -1.69996090e01,\n 1.35712162e01,\n 1.57636305e01,\n -8.69548684e00,\n -4.32574959e00,\n -1.07899713e01,\n 9.02958258e00,\n -1.30905861e01,\n -2.79234084e00,\n -1.06078777e01,\n 1.04360239e00,\n -2.34927485e01,\n 1.79008959e01,\n -1.12240728e01,\n 9.34730092e-01,\n -2.46437426e00,\n -8.39572195e00,\n -1.33215226e01,\n 1.13590100e01,\n -6.12007952e00,\n 2.48423222e00,\n -8.86641364e00,\n -9.14235386e00,\n 5.62188764e00,\n 1.44716474e01,\n -8.84031409e-01,\n -1.73103114e01,\n 2.78530924e01,\n -1.24137695e01,\n -1.88817981e01,\n 3.47237984e01,\n -4.64685133e00,\n -1.87675860e01,\n -9.37277228e00,\n 5.57127034e00,\n 3.48899714e00,\n -1.11111079e01,\n 2.34842326e01,\n -6.73646725e00,\n -1.46518463e01,\n 1.22625993e01,\n 1.77758445e01,\n -1.14609342e01,\n -1.70511379e01,\n 1.45701324e01,\n -2.72054210e01,\n -1.73137394e01,\n 1.35874928e01,\n -1.42088949e00,\n -3.52797358e00,\n 4.12269993e00,\n -1.38408231e00,\n -1.69391961e01,\n 1.70025216e01,\n 1.82668785e01,\n 1.67632189e00,\n -8.82521255e-01,\n 3.19946305e01,\n -3.56166124e00,\n -2.86596310e00,\n 7.29901540e00,\n 2.07886509e01,\n 2.05693665e01,\n -2.37043227e00,\n 2.84265087e00,\n -1.90482199e01,\n -4.27595926e00,\n -9.61991210e00,\n -1.43242041e01,\n 2.18535035e01,\n -1.07842662e01,\n -7.83341055e00,\n 6.06095096e00,\n 1.64242367e01,\n 5.34147892e00,\n 3.67784504e01,\n -1.50510242e00,\n 5.41892020e00,\n 4.66653180e00,\n 1.94425034e01,\n 5.61585211e00,\n -7.23262715e-01,\n -1.37792852e01,\n 1.75211292e00,\n 2.00883982e01,\n -5.21800277e00,\n 8.05488397e00,\n 3.63859853e00,\n 1.25033856e01,\n -1.15049866e01,\n 3.06157069e01,\n -1.65708445e01,\n -5.73370956e00,\n 1.19627926e01,\n 3.54659899e00,\n 1.12117576e01,\n -7.04507856e00,\n -2.38386909e00,\n -4.78641880e-01,\n 1.89416836e01,\n 9.93725990e00,\n 9.14290392e00,\n -9.97803476e00,\n 1.31197830e01,\n 2.30292623e00,\n 2.02788444e01,\n 2.58713914e01,\n -3.87039343e00,\n -5.51921801e00,\n -1.28217338e01,\n -1.41322434e00,\n -5.32404097e00,\n 5.62053688e00,\n -1.12631294e00,\n -2.71376468e00,\n 1.56949149e01,\n -1.30186608e01,\n 5.60208090e00,\n -4.37540124e00,\n 1.04250444e01,\n 1.93235798e01,\n -5.70493534e00,\n 5.92402024e00,\n 1.67340342e00,\n -1.05021310e01,\n 3.14942476e00,\n 4.80963602e00,\n 5.88573386e00,\n -1.88953894e00,\n 8.03981407e-01,\n -1.64226278e01,\n -5.24004429e00,\n 7.48141912e00,\n 1.24162213e01,\n -3.43658088e00,\n 1.37005315e00,\n 2.11988029e00,\n 2.37144019e00,\n 6.82998357e00,\n -2.40394903e01,\n -2.20604591e00,\n 3.28718164e00,\n -1.33352563e01,\n 2.28097408e01,\n 1.58168342e00,\n 2.08481986e01,\n -1.20860879e01,\n -1.27303555e01,\n 2.48169715e00,\n -2.22249358e01,\n 1.74312456e00,\n 2.09242376e00,\n 1.51930744e01,\n 7.38517500e00,\n -5.20438659e00,\n -1.41253667e01,\n 2.24569498e01,\n -1.10807705e01,\n -1.42341916e01,\n -1.49295780e01,\n 1.47604272e01,\n -8.67457034e00,\n -9.01311221e00,\n 2.93668359e00,\n -3.60449117e00,\n -1.06121062e01,\n 1.06903795e01,\n 1.37924495e01,\n 1.34312332e01,\n 1.00243529e01,\n 6.12187303e00,\n -2.32571981e01,\n 2.17881013e01,\n 2.68965734e00,\n 6.61945425e00,\n 1.56482189e01,\n 1.81432065e01,\n 5.13624621e00,\n 5.27803087e00,\n -8.13448929e00,\n -1.48998816e00,\n -1.13315568e01,\n -9.18616820e00,\n -1.19634905e01,\n -2.41522834e00,\n 1.42468424e01,\n 4.31669577e01,\n -2.16752904e-01,\n -1.62305494e01,\n 1.74513123e01,\n -4.70917317e00,\n -9.30078451e00,\n 3.32404618e00,\n -1.68487892e01,\n 9.69744597e-01,\n 8.72545019e-01,\n 1.21631241e00,\n 6.16445096e00,\n 2.18238969e-01,\n 1.75673382e00,\n 4.12098099e00,\n 6.21147975e00,\n -1.49571743e01,\n -1.80755863e01,\n -1.41513189e-01,\n -1.80218977e01,\n 5.52476291e-01,\n 1.21801405e01,\n 1.04922184e01,\n -1.51970122e01,\n -1.17385738e01,\n 5.56479183e00,\n -5.31470187e00,\n -3.68787361e00,\n 7.65121214e00,\n -1.29457832e01,\n -6.71810270e00,\n -9.13282757e00,\n -1.41871722e01,\n -1.22398551e01,\n 9.80352357e00,\n 2.38197732e-01,\n -1.31917681e01,\n -4.46365591e00,\n -2.14093247e01,\n -1.00499887e01,\n 2.88582708e01,\n -1.39402730e-01,\n 8.74128301e00,\n -1.61393960e00,\n 4.31098567e00,\n 9.03991729e00,\n -1.49404750e01,\n -7.04134002e-01,\n 2.12330137e01,\n -1.08364657e01,\n -8.35935279e00,\n -4.96291981e00,\n 3.90292671e00,\n 6.18881347e00,\n 1.59366153e01,\n 6.42459394e00,\n -9.94596595e-01,\n 1.92394976e01,\n 8.79186148e00,\n -1.92294286e01,\n 3.48210932e01,\n 2.26825288e01,\n -1.49550394e00,\n 3.91310905e00,\n 1.52028613e01,\n -1.71620549e00,\n 8.09458848e00,\n 1.53487238e01,\n -1.43712798e01,\n -6.46428403e00,\n 1.34958276e01,\n 5.76176068e00,\n 1.17716905e01,\n -3.00206296e00,\n -4.33882474e00,\n -2.72366204e01,\n -1.58211535e01,\n 7.91498739e-01,\n 1.16995781e01,\n 7.51382034e00,\n -2.49378284e00,\n -5.10325812e00,\n 4.29370030e00,\n 3.65409052e-01,\n 1.82912434e01,\n 1.45390237e00,\n -2.18210891e01,\n -1.76413567e01,\n 2.00043181e01,\n -1.51754428e01,\n 1.10094693e01,\n -3.61585467e00,\n -1.35773391e00,\n -1.46912508e00,\n 1.64575122e01,\n -2.43998884e00,\n -6.40040902e-01,\n -2.10412668e01,\n 2.51996492e00,\n 6.03432217e00,\n 3.50587165e00,\n 1.78607329e01,\n 1.58574428e00,\n 3.78294226e00,\n 2.22833752e01,\n -2.04116810e01,\n -5.50454209e00,\n 1.76644180e01,\n 1.24189579e01,\n 1.00296998e01,\n 9.53211061e00,\n 4.79852296e00,\n 1.97502917e01,\n 4.07244718e00,\n 3.27379193e00,\n 4.87209390e-01,\n 1.61570471e00,\n -1.70768827e01,\n 1.20424393e01,\n -1.59505302e00,\n 2.51400192e01,\n -1.24299625e00,\n 5.32362252e00,\n 1.70952529e00,\n -8.72891735e00,\n 1.26197621e01,\n 2.65521027e01,\n 9.41796963e-01,\n -2.58607101e00,\n -3.93582967e00,\n -2.61215204e01,\n -3.51411750e00,\n 4.15195191e00,\n 1.45821371e01,\n 1.11799205e01,\n -5.26196934e00,\n -2.91907699e00,\n 1.52173819e01,\n -2.52461456e00,\n -7.68657364e00,\n 1.73347896e01,\n 1.47945347e01,\n -5.56637736e-02,\n -8.24192559e00,\n -2.54021270e01,\n 8.63801487e00,\n -1.17187889e01,\n -2.63299080e01,\n 2.28949564e01,\n 1.04589301e01,\n -1.44326485e01,\n -1.57967801e01,\n 9.65232617e00,\n -1.17177376e01,\n 1.73514647e01,\n 8.40832944e00,\n 8.18028828e00,\n 2.71857482e00,\n 2.01284470e00,\n 1.21456295e01,\n -6.59116695e00,\n -2.57645431e-01,\n 1.10106982e01,\n 7.87008727e00,\n -1.70882589e01,\n -6.43436177e00,\n 4.23122429e00,\n -5.49772713e00,\n 2.47359302e01,\n -5.22431779e00,\n -2.58311904e00,\n 9.21812077e00,\n 4.37206593e00,\n -1.76506831e00,\n -9.32722796e00,\n 3.95150529e00,\n 1.44720287e01,\n 5.49709252e00,\n -1.12782295e01,\n 2.33140283e01,\n -2.05650691e01,\n -2.05259198e01,\n 1.34184608e01,\n 3.32507571e00,\n -7.07235165e00,\n -1.27957175e01,\n 3.08324765e01,\n -6.22200706e-01,\n 7.40423557e00,\n 4.23681046e00,\n 5.34686952e00,\n 6.30559012e00,\n 9.43923820e00,\n -4.87940141e00,\n -4.43628180e00,\n -2.10692560e01,\n -1.14847097e01,\n 2.86346425e00,\n 1.18059314e01,\n 8.33091462e00,\n -6.61142898e00,\n -1.75762559e01,\n -3.77347669e01,\n 1.48240621e01,\n -6.20823976e00,\n -5.05419098e00,\n 3.09371542e00,\n -1.98396392e01,\n -3.58902570e00,\n 2.77871890e01,\n 7.58771492e00,\n 5.87474261e00,\n -2.22523526e01,\n 2.98358307e01,\n -1.83270762e01,\n 2.32713657e01,\n -2.70130824e01,\n 1.95077277e01,\n 2.17774913e01,\n -1.08985515e01,\n 4.66953607e00,\n 7.03409537e00,\n -9.87561197e00,\n -1.82466726e01,\n -1.50762347e01,\n 7.22281947e00,\n -1.80653326e00,\n -8.12513543e00,\n 1.20210554e01,\n 6.77461329e00,\n -9.80642554e00,\n -1.62352163e01,\n 8.15373873e00,\n -7.48476791e00,\n 9.90555818e-01,\n 2.06787602e01,\n 5.14242083e00,\n -1.31974278e01,\n 9.87728914e-01,\n -1.15471872e01,\n 2.25898930e01,\n -6.19922113e00,\n 1.46331261e00,\n 2.18185912e00,\n 1.48780369e00,\n -2.62397327e01,\n -1.90096352e01,\n -5.05301504e00,\n 4.59255498e00,\n -1.15601828e-01,\n -1.31319478e01,\n -1.90996924e01,\n -7.09714823e00,\n -7.20745175e00,\n 7.15890088e00,\n -5.28987765e00,\n 9.06564586e00,\n -6.60789650e00,\n -5.82176666e00,\n -3.83015619e00,\n -1.27916278e01,\n 8.83266650e00,\n -9.74834870e00,\n -6.97068326e00,\n -2.26587631e00,\n -1.80835894e01,\n -4.64414309e00,\n -9.77585227e00,\n -5.43805173e00,\n -9.18150170e-01,\n -1.05752008e01,\n -4.17680333e00,\n 1.74083978e01,\n 1.17030809e00,\n 1.50618575e01,\n 4.22944094e00,\n 1.15195394e01,\n -1.30045508e01,\n 2.59629378e00,\n 1.17422099e00,\n -8.09874305e00,\n -1.10014171e01,\n -1.91571992e01,\n 1.99113004e01,\n -1.37931224e01,\n 1.94547432e01,\n -8.66939793e00,\n -1.16123780e01,\n 7.04818155e00,\n -9.27465310e00,\n 9.67823683e00,\n -4.53332999e00,\n 6.67470253e00,\n -1.48397859e01,\n 1.04836426e01,\n 6.77799495e00,\n -1.20488538e01,\n 3.62629729e01,\n 7.29343316e00,\n 3.14192375e01,\n 2.20370858e01,\n -4.37661313e00,\n -5.52343014e00,\n -4.67367560e00,\n -2.40922777e01,\n -9.74880092e00,\n 2.52258270e00,\n 1.94627467e01,\n -1.05536659e01,\n 1.30296483e01,\n -1.88459155e01,\n -8.56777011e00,\n -7.31214180e00,\n 5.79968785e00,\n 5.61356613e00,\n 1.25087612e01,\n 1.01795654e01,\n 3.72507771e00,\n 4.87258297e00,\n 1.83788586e01,\n -6.34770654e00,\n 1.08880419e01,\n -2.46065339e01,\n 4.46375473e00,\n -6.16595499e00,\n 4.13913861e-01,\n 1.35579300e01,\n 2.00387019e00,\n 1.10086399e01,\n 1.96985299e01,\n 3.69740060e00,\n 1.62115096e01,\n -5.34879676e00,\n 1.27373942e-01,\n -8.45469161e00,\n 1.34769017e01,\n 5.47448795e00,\n -8.50192689e00,\n 2.20121397e00,\n 1.36688054e01,\n -2.27197566e00,\n -1.41017912e01,\n 2.38425448e00,\n -2.58169408e01,\n 1.02367373e01,\n -5.27781285e00,\n -6.10589458e00,\n 1.21403997e01,\n -1.71263873e01,\n 2.47541194e01,\n -5.80071128e00,\n -7.43925525e00,\n 1.35493130e01,\n 9.25614123e00,\n 3.26853415e01,\n -4.07479621e00,\n -1.44062214e00,\n -1.82810462e01,\n -4.53529850e00,\n -9.73155065e00,\n -6.73995767e00,\n -2.36418709e01,\n 2.28632910e01,\n -1.94764090e01,\n -3.82479744e01,\n -1.56253809e01,\n -9.06217440e00,\n -1.52518923e01,\n 1.56334792e01,\n -4.99130824e-01,\n 2.52001441e-01,\n 9.60013856e00,\n 4.89194874e00,\n 1.22020253e01,\n -1.61818033e01,\n -7.68950854e00,\n 1.00110391e01,\n -3.42566020e01,\n -1.91481933e01,\n 8.30927939e00,\n -6.19036185e00,\n 1.03049760e01,\n 1.12308240e01,\n -1.56390063e01,\n 5.71031778e00,\n 1.66573804e01,\n 1.92121748e00,\n -1.45017651e01,\n 1.14898984e01,\n 7.62455009e00,\n 6.38561749e00,\n 8.39301954e00,\n -3.99367749e01,\n 1.19793718e01,\n 2.39386641e01,\n 5.23973938e00,\n 2.57597210e00,\n 1.04722772e01,\n 2.55753520e00,\n 9.16765072e00,\n -5.25872142e-01,\n -1.22253699e01,\n -1.54913122e01,\n -1.43757021e01,\n -1.82991373e01,\n -1.40079017e01,\n 2.28157560e01,\n 1.11877410e01,\n -7.00695302e00,\n -4.86925966e00,\n 9.26695345e-01,\n -7.71711810e00,\n 1.66601630e00,\n 1.13551934e01,\n -1.13853691e00,\n 1.69739309e00,\n 1.40731749e01,\n -5.28120303e00,\n 3.80529027e00,\n -1.79192533e00,\n -5.42008793e-02,\n -3.43049041e00,\n -8.63542683e00,\n 5.65238195e-01,\n 7.10846800e00,\n 3.06400276e00,\n 6.38023432e00,\n -1.07473490e01,\n -1.60371792e01,\n 6.70672912e00,\n 7.83272754e00,\n -5.38102716e-01,\n 1.73927036e01,\n 1.33370510e01,\n 3.63885043e01,\n -5.76212734e-01,\n -1.25353350e01,\n -1.00175475e01,\n -6.36196488e00,\n 6.63187858e00,\n -2.98114553e01,\n 1.84636777e01,\n -3.92379332e00,\n -3.61897766e00,\n -1.32296503e01,\n -1.64187660e00,\n -6.24572572e-01,\n -2.10904641e00,\n 5.59478698e00,\n -8.50508924e00,\n -1.24690133e01,\n 6.88517728e00,\n 1.51468377e00,\n 2.27395173e00,\n 1.26815900e01,\n -1.46788212e01,\n -1.24676799e01,\n 1.81998272e01,\n -1.91874296e01,\n -1.70731847e01,\n 1.05253956e01,\n 2.39688766e00,\n 9.11780573e-01,\n -2.28811871e00,\n 2.91891541e00,\n -3.48766605e00,\n 1.88452808e01,\n -6.65449848e00,\n -2.28083797e00,\n 2.32142806e01,\n -8.06597156e-01,\n 2.89636947e01,\n 3.39092662e-01,\n 1.83097577e01,\n -2.30918360e01,\n 2.62803703e00,\n -2.13599326e01,\n 1.21094485e01,\n -1.81825777e01,\n 4.13089110e00,\n -3.03336768e00,\n -1.72826406e01,\n -2.13926105e01,\n -5.19637822e00,\n 2.34615466e01,\n -3.13691720e00,\n 1.30414193e01,\n -1.47686039e00,\n 1.18644502e01,\n -2.62071100e01,\n -5.88922765e00,\n 1.30706121e01,\n -1.47876918e00,\n -1.14143684e00,\n -5.08578837e00,\n 1.43991268e01,\n 3.91097026e00,\n 6.13021353e-01,\n 1.05226655e01,\n 7.71940375e00,\n 2.36821019e00,\n 2.08866405e01,\n -1.73222994e00,\n 3.94331841e00,\n -9.03675391e00,\n 2.33322655e-01,\n 2.13560411e01,\n -8.99335607e00,\n -1.69215381e01,\n 1.33764695e01,\n -5.17098855e-01,\n 1.81614197e00,\n 3.47020068e-03,\n -2.74357718e-01,\n ]\n ]\n )\n np.testing.assert_array_almost_equal(self.fee.critical_points[3], critical_points_expected_3, decimal=2)\n\n # def test_layer_0_biases(self):\n # layer_0_biases_expected = np.array(\n # [\n # [3.52880724],\n # [1.04879517],\n # [1.50037751],\n # [1.28102357],\n # [-0.12998148],\n # [1.31377369],\n # [-0.37855184],\n # [0.31751928],\n # [-0.83950368],\n # [1.00915159],\n # [-0.22809063],\n # [-0.09700302],\n # [0.20176007],\n # [-0.48283775],\n # [0.15261177],\n # [0.40842637],\n # ]\n # )\n # np.testing.assert_array_almost_equal(self.fee.b_0, layer_0_biases_expected, decimal=2)\n\n # def test_layer_1_biases(self):\n # layer_1_biases_expected = np.array(\n # [\n # [0.35597115],\n # [0.16081501],\n # [-0.4898516],\n # [-1.52676063],\n # [0.23123853],\n # [-1.26165748],\n # [-0.74085385],\n # [-1.01602675],\n # [-0.50653434],\n # [1.91474429],\n # ]\n # )\n # np.testing.assert_array_almost_equal(self.fee.b_1, layer_1_biases_expected, decimal=2)\n\n def test_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(\n FunctionallyEquivalentExtraction, [BaseEstimator, NeuralNetworkMixin, ClassifierMixin]\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_graphite.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\nimport keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion import GRAPHITEBlackbox, GRAPHITEWhiteboxPyTorch\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr, get_image_classifier_pt\n\nfrom tests.utils import master_seed\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestGRAPHITE(TestBase):\n \"\"\"\n A unittest class for testing the GRAPHITE attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True, set_torch=True)\n super().setUpClass()\n\n cls.n_test = 2\n cls.x_test_init_mnist = cls.x_test_mnist[1 : cls.n_test + 1]\n cls.y_test_init_mnist = cls.y_test_mnist[1 : cls.n_test + 1]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def setUp(self):\n master_seed(seed=1234, set_tensorflow=True, set_torch=True)\n super().setUp()\n\n def test_3_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # First attack\n graphite = GRAPHITEBlackbox(\n classifier=tfc,\n noise_size=(28, 28),\n net_size=(28, 28),\n heatmap_mode=\"Target\",\n num_xforms_mask=2,\n num_xforms_boost=10,\n rotation_range=(-5, 5),\n gamma_range=(1.0, 1.1),\n crop_percent_range=(-0.001, 0.001),\n off_x_range=(-0.001, 0.001),\n blur_kernels=[0],\n )\n params = {\"y\": self.y_test_init_mnist, \"x_tar\": self.x_test_init_mnist}\n x_test_adv = graphite.generate(self.x_test_mnist, **params)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n params.update(mask=mask)\n x_test_adv = graphite.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test passing in points\n pts = np.zeros((4, 3, 1))\n pts[0, :, 0] = np.array([0.05, 0.05, 1])\n pts[1, :, 0] = np.array([0.05, 0.95, 1])\n pts[2, :, 0] = np.array([0.95, 0.05, 1])\n pts[3, :, 0] = np.array([0.95, 0.95, 1])\n\n params.update(pts=pts)\n x_test_adv = graphite.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_8_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # First attack\n graphite = GRAPHITEBlackbox(\n classifier=krc,\n noise_size=(28, 28),\n net_size=(28, 28),\n heatmap_mode=\"Target\",\n num_xforms_mask=2,\n num_xforms_boost=10,\n rotation_range=(-5, 5),\n gamma_range=(1.0, 1.1),\n crop_percent_range=(-0.001, 0.001),\n off_x_range=(-0.001, 0.001),\n blur_kernels=[0],\n )\n params = {\"y\": self.y_test_init_mnist, \"x_tar\": self.x_test_init_mnist}\n x_test_adv = graphite.generate(self.x_test_mnist, **params)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n params.update(mask=mask)\n x_test_adv = graphite.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test passing in points\n pts = np.zeros((4, 3, 1))\n pts[0, :, 0] = np.array([0.05, 0.05, 1])\n pts[1, :, 0] = np.array([0.05, 0.95, 1])\n pts[2, :, 0] = np.array([0.95, 0.05, 1])\n pts[3, :, 0] = np.array([0.95, 0.95, 1])\n\n params.update(pts=pts)\n x_test_adv = graphite.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n k.clear_session()\n\n def test_4_pytorch_classifier(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_test = np.transpose(self.x_test_mnist, (0, 3, 1, 2)).astype(np.float32)\n x_test_init = np.transpose(self.x_test_init_mnist, (0, 3, 1, 2)).astype(np.float32)\n x_test_original = x_test.copy()\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt()\n\n # BLACKBOX\n # First attack\n graphite = GRAPHITEBlackbox(\n classifier=ptc,\n noise_size=(28, 28),\n net_size=(28, 28),\n heatmap_mode=\"Target\",\n num_xforms_mask=2,\n num_xforms_boost=10,\n rotation_range=(-5, 5),\n gamma_range=(1.0, 1.1),\n crop_percent_range=(-0.001, 0.001),\n off_x_range=(-0.001, 0.001),\n blur_kernels=[0],\n )\n params = {\"y\": self.y_test_init_mnist, \"x_tar\": x_test_init}\n x_test_adv = graphite.generate(x_test, **params)\n\n self.assertFalse((x_test == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n mask = mask.reshape(x_test.shape)\n\n params.update(mask=mask)\n x_test_adv = graphite.generate(x_test, **params)\n mask_diff = (1 - mask) * (x_test_adv - x_test)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - x_test)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test passing in points\n pts = np.zeros((4, 3, 1))\n pts[0, :, 0] = np.array([0.05, 0.05, 1])\n pts[1, :, 0] = np.array([0.05, 0.95, 1])\n pts[2, :, 0] = np.array([0.95, 0.05, 1])\n pts[3, :, 0] = np.array([0.95, 0.95, 1])\n\n params.update(pts=pts)\n x_test_adv = graphite.generate(x_test, **params)\n mask_diff = (1 - mask) * (x_test_adv - x_test)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - x_test)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n # WHITEBOX\n # First attack\n graphite = GRAPHITEWhiteboxPyTorch(classifier=ptc, net_size=(28, 28), num_xforms=10)\n params = {\"y\": self.y_test_init_mnist}\n x_test_adv = graphite.generate(x_test, **params)\n\n self.assertFalse((x_test == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n mask = mask.reshape(x_test.shape)\n\n params.update(mask=mask)\n x_test_adv = graphite.generate(x_test, **params)\n mask_diff = (1 - mask) * (x_test_adv - x_test)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - x_test)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test passing in points\n pts = np.zeros((4, 3, 1))\n pts[0, :, 0] = np.array([0.05, 0.05, 1])\n pts[1, :, 0] = np.array([0.05, 0.95, 1])\n pts[2, :, 0] = np.array([0.95, 0.05, 1])\n pts[3, :, 0] = np.array([0.95, 0.95, 1])\n\n params.update(pts=pts)\n x_test_adv = graphite.generate(x_test, **params)\n mask_diff = (1 - mask) * (x_test_adv - x_test)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - x_test)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(1, 1), net_size=(1, 1), heat_patch_size=(2, 2))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), heat_patch_size=(0, 1))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), heat_patch_size=(1.0, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), heat_patch_stride=(0, 1))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), heat_patch_stride=(1.0, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), heatmap_mode=\"asdf\")\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), tr_lo=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), tr_lo=1.1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), tr_hi=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), tr_hi=1.1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), num_xforms_mask=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), num_xforms_mask=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), num_xforms_boost=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), num_xforms_boost=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), num_boost_queries=0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), num_boost_queries=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), rotation_range=(-90, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), rotation_range=(90, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), rotation_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), dist_range=(-1, 1))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), dist_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), gamma_range=(0, 1))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), gamma_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), crop_percent_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), off_x_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), off_y_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEBlackbox(ptc, noise_size=(28, 28), net_size=(28, 28), blur_kernels=[-1])\n\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), min_tr=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), min_tr=1.1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), num_xforms=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), num_xforms=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), step_size=0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), step_size=-1)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), first_steps=0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), first_steps=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), steps=0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), steps=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), patch_removal_size=0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), num_patches_to_remove=0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), num_patches_to_remove=1.0)\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), rotation_range=(-90, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), rotation_range=(90, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), rotation_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), dist_range=(-1, 1))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), dist_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), gamma_range=(0, 1))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), gamma_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), crop_percent_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), off_x_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), off_y_range=(1, 0))\n with self.assertRaises(ValueError):\n _ = GRAPHITEWhiteboxPyTorch(ptc, net_size=(28, 28), blur_kernels=[-1])\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(\n GRAPHITEBlackbox, [BaseEstimator, ClassifierMixin], noise_size=(28, 28), net_size=(28, 28)\n )\n backend_test_classifier_type_check_fail(\n GRAPHITEWhiteboxPyTorch, [BaseEstimator, ClassifierMixin], net_size=(28, 28)\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_hclu.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport GPy\n\nfrom art.attacks.evasion.hclu import HighConfidenceLowUncertainty\nfrom art.estimators.classification.GPy import GPyGaussianProcessClassifier\n\nfrom tests.utils import TestBase\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestHCLU(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n # change iris to a binary problem\n cls.x_train = cls.x_train_iris[0:35]\n cls.y_train = cls.y_train_iris[0:35, 1]\n cls.x_test = cls.x_train\n cls.y_test = cls.y_train\n\n def test_GPy(self):\n x_test_original = self.x_test.copy()\n # set up GPclassifier\n gpkern = GPy.kern.RBF(np.shape(self.x_train)[1])\n m = GPy.models.GPClassification(self.x_train, self.y_train.reshape(-1, 1), kernel=gpkern)\n m.inference_method = GPy.inference.latent_function_inference.laplace.Laplace()\n m.optimize(messages=True, optimizer=\"lbfgs\")\n # get ART classifier + clean accuracy\n m_art = GPyGaussianProcessClassifier(m)\n clean_acc = np.mean(np.argmin(m_art.predict(self.x_test), axis=1) == self.y_test)\n # get adversarial examples, accuracy, and uncertainty\n attack = HighConfidenceLowUncertainty(m_art, conf=0.9, min_val=-0.0, max_val=1.0, verbose=False)\n adv = attack.generate(self.x_test)\n adv_acc = np.mean(np.argmin(m_art.predict(adv), axis=1) == self.y_test)\n unc_f = m_art.predict_uncertainty(adv)\n # not all attacks succeed due to the decision surface landscape of GP, some should\n self.assertGreater(clean_acc, adv_acc)\n\n # now take into account uncertainty\n attack = HighConfidenceLowUncertainty(\n m_art, unc_increase=0.9, conf=0.9, min_val=0.0, max_val=1.0, verbose=False\n )\n adv = attack.generate(self.x_test)\n adv_acc = np.mean(np.argmin(m_art.predict(adv), axis=1) == self.y_test)\n unc_o = m_art.predict_uncertainty(adv)\n # same above\n self.assertGreater(clean_acc, adv_acc)\n # uncertainty should indeed be lower when used as a constraint\n # however, same as above, crafting might fail\n self.assertGreater(np.mean(unc_f > unc_o), 0.6)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n gpkern = GPy.kern.RBF(np.shape(self.x_train)[1])\n m = GPy.models.GPClassification(self.x_train, self.y_train.reshape(-1, 1), kernel=gpkern)\n m_art = GPyGaussianProcessClassifier(m)\n\n with self.assertRaises(ValueError):\n _ = HighConfidenceLowUncertainty(\n m_art, conf=0.1, unc_increase=100.0, min_val=0.0, max_val=1.0, verbose=False\n )\n\n with self.assertRaises(ValueError):\n _ = HighConfidenceLowUncertainty(\n m_art, conf=0.75, unc_increase=-100.0, min_val=0.0, max_val=1.0, verbose=False\n )\n\n with self.assertRaises(ValueError):\n _ = HighConfidenceLowUncertainty(\n m_art, conf=0.75, unc_increase=100.0, min_val=1.0, max_val=0.0, verbose=False\n )\n\n with self.assertRaises(ValueError):\n _ = HighConfidenceLowUncertainty(\n m_art, conf=0.75, unc_increase=100.0, min_val=0.0, max_val=1.0, verbose=\"False\"\n )\n\n def test_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(HighConfidenceLowUncertainty, [GPyGaussianProcessClassifier])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_hop_skip_jump.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\nimport keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion.hop_skip_jump import HopSkipJump\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\n\n# from art.estimators.classification.keras import KerasClassifier\nfrom art.utils import random_targets\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr, get_image_classifier_pt\n\n# from tests.utils import get_tabular_classifier_tf, get_tabular_classifier_kr\nfrom tests.utils import get_tabular_classifier_pt, master_seed\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestHopSkipJump(TestBase):\n \"\"\"\n A unittest class for testing the HopSkipJump attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True, set_torch=True)\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def setUp(self):\n master_seed(seed=1234, set_tensorflow=True, set_torch=True)\n super().setUp()\n\n def test_3_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # First targeted attack and norm=2\n hsj = HopSkipJump(classifier=tfc, targeted=True, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # First targeted attack and norm=np.inf\n hsj = HopSkipJump(\n classifier=tfc, targeted=True, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Second untargeted attack and norm=2\n hsj = HopSkipJump(classifier=tfc, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n x_test_adv = hsj.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n y_pred = np.argmax(tfc.predict(self.x_test_mnist), axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertTrue((y_pred != y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Second untargeted attack and norm=np.inf\n hsj = HopSkipJump(\n classifier=tfc, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n )\n x_test_adv = hsj.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n y_pred = np.argmax(tfc.predict(self.x_test_mnist), axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertTrue((y_pred != y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_8_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # First targeted attack and norm=2\n hsj = HopSkipJump(classifier=krc, targeted=True, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n params = {\"y\": random_targets(self.y_test_mnist, krc.nb_classes)}\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # First targeted attack and norm=np.inf\n hsj = HopSkipJump(\n classifier=krc, targeted=True, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n )\n params = {\"y\": random_targets(self.y_test_mnist, krc.nb_classes)}\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertTrue((target == y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n params.update(mask=mask)\n x_test_adv = hsj.generate(self.x_test_mnist, **params)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Second untargeted attack and norm=2\n hsj = HopSkipJump(classifier=krc, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n x_test_adv = hsj.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n y_pred = np.argmax(krc.predict(self.x_test_mnist), axis=1)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertTrue((y_pred != y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Second untargeted attack and norm=np.inf\n hsj = HopSkipJump(\n classifier=krc, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n )\n x_test_adv = hsj.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1.0001).all())\n self.assertTrue((x_test_adv >= -0.0001).all())\n\n y_pred = np.argmax(krc.predict(self.x_test_mnist), axis=1)\n y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertTrue((y_pred != y_pred_adv).any())\n\n # Test the masking 1\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape)\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Test the masking 2\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:])\n\n x_test_adv = hsj.generate(self.x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - self.x_test_mnist)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n unmask_diff = mask * (x_test_adv - self.x_test_mnist)\n self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n k.clear_session()\n\n # def test_4_pytorch_classifier(self):\n # \"\"\"\n # Third test with the PyTorchClassifier.\n # :return:\n # \"\"\"\n # x_test = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n # x_test_original = x_test.copy()\n #\n # # Build PyTorchClassifier\n # ptc = get_image_classifier_pt()\n #\n # # First targeted attack and norm=2\n # hsj = HopSkipJump(classifier=ptc, targeted=True, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n # x_test_adv = hsj.generate(x_test, **params)\n #\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1.0001).all())\n # self.assertTrue((x_test_adv >= -0.0001).all())\n #\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target == y_pred_adv).any())\n #\n # # Test the masking 1\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n # mask = mask.reshape(x_test.shape)\n #\n # params.update(mask=mask)\n # x_test_adv = hsj.generate(x_test, **params)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Test the masking 2\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape[1:]))\n # mask = mask.reshape(x_test.shape[1:])\n #\n # params.update(mask=mask)\n # x_test_adv = hsj.generate(x_test, **params)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # First targeted attack and norm=np.inf\n # hsj = HopSkipJump(classifier=ptc, targeted=True, max_iter=5, max_eval=100, init_eval=10, norm=np.Inf,\n # verbose=False)\n # params = {\"y\": random_targets(self.y_test_mnist, ptc.nb_classes)}\n # x_test_adv = hsj.generate(x_test, **params)\n #\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1.0001).all())\n # self.assertTrue((x_test_adv >= -0.0001).all())\n #\n # target = np.argmax(params[\"y\"], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((target == y_pred_adv).any())\n #\n # # Test the masking 1\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n # mask = mask.reshape(x_test.shape)\n #\n # params.update(mask=mask)\n # x_test_adv = hsj.generate(x_test, **params)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Test the masking 2\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape[1:]))\n # mask = mask.reshape(x_test.shape[1:])\n #\n # params.update(mask=mask)\n # x_test_adv = hsj.generate(x_test, **params)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Second untargeted attack and norm=2\n # hsj = HopSkipJump(classifier=ptc, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n # x_test_adv = hsj.generate(x_test)\n #\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1.0001).all())\n # self.assertTrue((x_test_adv >= -0.0001).all())\n #\n # y_pred = np.argmax(ptc.predict(x_test), axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((y_pred != y_pred_adv).any())\n #\n # # Test the masking 1\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n # mask = mask.reshape(x_test.shape)\n #\n # x_test_adv = hsj.generate(x_test, mask=mask)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Test the masking 2\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape[1:]))\n # mask = mask.reshape(x_test.shape[1:])\n #\n # x_test_adv = hsj.generate(x_test, mask=mask)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Second untargeted attack and norm=np.inf\n # hsj = HopSkipJump(classifier=ptc, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf,\n # verbose=False)\n # x_test_adv = hsj.generate(x_test)\n #\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1.0001).all())\n # self.assertTrue((x_test_adv >= -0.0001).all())\n #\n # y_pred = np.argmax(ptc.predict(x_test), axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # self.assertTrue((y_pred != y_pred_adv).any())\n #\n # # Test the masking 1\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n # mask = mask.reshape(x_test.shape)\n #\n # x_test_adv = hsj.generate(x_test, mask=mask)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Test the masking 2\n # mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape[1:]))\n # mask = mask.reshape(x_test.shape[1:])\n #\n # x_test_adv = hsj.generate(x_test, mask=mask)\n # mask_diff = (1 - mask) * (x_test_adv - x_test)\n # self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n #\n # unmask_diff = mask * (x_test_adv - x_test)\n # self.assertGreater(float(np.sum(np.abs(unmask_diff))), 0.0)\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_5_pytorch_resume(self):\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt()\n\n # HSJ attack\n hsj = HopSkipJump(classifier=ptc, targeted=True, max_iter=10, max_eval=100, init_eval=10, verbose=False)\n\n params = {\"y\": self.y_test_mnist[2:3], \"x_adv_init\": x_test[2:3]}\n x_test_adv1 = hsj.generate(x_test[0:1], **params)\n diff1 = np.linalg.norm(x_test_adv1 - x_test)\n\n params.update(resume=True, x_adv_init=x_test_adv1)\n x_test_adv2 = hsj.generate(x_test[0:1], **params)\n params.update(x_adv_init=x_test_adv2)\n x_test_adv2 = hsj.generate(x_test[0:1], **params)\n diff2 = np.linalg.norm(x_test_adv2 - x_test)\n\n self.assertGreater(diff1, diff2)\n\n # def test_7_keras_iris_clipped(self):\n # classifier = get_tabular_classifier_kr()\n #\n # # Norm=2\n # attack = HopSkipJump(classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n #\n # # Norm=np.inf\n # attack = HopSkipJump(\n # classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n # )\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n #\n # # Clean-up session\n # k.clear_session()\n #\n # def test_7_keras_iris_unbounded(self):\n # classifier = get_tabular_classifier_kr()\n #\n # # Recreate a classifier without clip values\n # classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n #\n # # Norm=2\n # attack = HopSkipJump(classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n #\n # # Norm=np.inf\n # attack = HopSkipJump(\n # classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n # )\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n #\n # # Clean-up session\n # k.clear_session()\n\n # def test_2_tensorflow_iris(self):\n # classifier, sess = get_tabular_classifier_tf()\n #\n # # Test untargeted attack and norm=2\n # attack = HopSkipJump(classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n #\n # # Test untargeted attack and norm=np.inf\n # attack = HopSkipJump(\n # classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n # )\n # x_test_adv = attack.generate(self.x_test_iris)\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n #\n # # Test targeted attack and norm=2\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = HopSkipJump(classifier, targeted=True, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n # acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Success rate of targeted HopSkipJump on Iris: %.2f%%\", (acc * 100))\n #\n # # Test targeted attack and norm=np.inf\n # targets = random_targets(self.y_test_iris, nb_classes=3)\n # attack = HopSkipJump(\n # classifier, targeted=True, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n # )\n # x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n # self.assertFalse((self.x_test_iris == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n # acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n # logger.info(\"Success rate of targeted HopSkipJump on Iris: %.2f%%\", (acc * 100))\n #\n # # Clean-up session\n # if sess is not None:\n # sess.close()\n\n def test_4_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n x_test = self.x_test_iris.astype(np.float32)\n\n # Norm=2\n attack = HopSkipJump(classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n\n # Norm=np.inf\n attack = HopSkipJump(\n classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n )\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with HopSkipJump adversarial examples: %.2f%%\", (acc * 100))\n\n def test_6_scikitlearn(self):\n # from sklearn.linear_model import LogisticRegression\n from sklearn.svm import SVC # , LinearSVC\n\n # from sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier\n # from sklearn.ensemble import AdaBoostClassifier, BaggingClassifier, ExtraTreesClassifier\n # from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\n\n from art.estimators.classification.scikitlearn import SklearnClassifier\n\n scikitlearn_test_cases = [\n # DecisionTreeClassifier(),\n # ExtraTreeClassifier(),\n # AdaBoostClassifier(),\n # BaggingClassifier(),\n # ExtraTreesClassifier(n_estimators=10),\n # GradientBoostingClassifier(n_estimators=10),\n # RandomForestClassifier(n_estimators=10),\n # LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n SVC(gamma=\"auto\"),\n # LinearSVC(),\n ]\n\n x_test_original = self.x_test_iris.copy()\n\n for model in scikitlearn_test_cases:\n classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n\n # Norm=2\n attack = HopSkipJump(classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with HopSkipJump adversarial \"\n \"examples: %.2f%%\",\n (acc * 100),\n )\n\n # Norm=np.inf\n attack = HopSkipJump(\n classifier, targeted=False, max_iter=20, max_eval=100, init_eval=10, norm=np.Inf, verbose=False\n )\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with HopSkipJump adversarial \"\n \"examples: %.2f%%\",\n (acc * 100),\n )\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, norm=1)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, max_iter=1.0)\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, max_eval=1.0)\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, max_eval=-1)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, init_eval=1.0)\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, init_eval=-1)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, init_eval=10, max_eval=1)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, init_size=1.0)\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, init_size=-1)\n\n with self.assertRaises(ValueError):\n _ = HopSkipJump(ptc, verbose=\"true\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(HopSkipJump, [BaseEstimator, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_input_filter.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport unittest\n\n# import numpy as np\nimport pandas as pd\n\n# from art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n# from art.estimators.classification.keras import KerasClassifier\n# from art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.utils import load_dataset # , get_labels_np_array\n\n# from tests.utils import get_image_classifier_tf, get_image_classifier_pt, get_tabular_classifier_pt\n# from tests.utils import get_tabular_classifier_tf, get_tabular_classifier_kr\nfrom tests.utils import master_seed\n\n# from tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 10\nNB_TEST = 11\n\n\nclass TestInputFilter(unittest.TestCase):\n \"\"\"\n A unittest class for testing the input filtering using\n PGD tests.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # MNIST\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_train = list(x_train[:NB_TRAIN])\n y_train = list(y_train[:NB_TRAIN])\n x_test = list(x_test[:NB_TEST])\n y_test = list(y_test[:NB_TEST])\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n # Iris\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"iris\")\n x_train = pd.DataFrame(x_train)\n y_train = pd.DataFrame(y_train)\n x_test = pd.DataFrame(x_test)\n y_test = pd.DataFrame(y_test)\n cls.iris = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(1234)\n\n def test_2_tensorflow_mnist(self):\n pass\n\n\n# (x_train, y_train), (x_test, y_test) = self.mnist\n# classifier, sess = get_image_classifier_tf()\n#\n# scores = get_labels_np_array(classifier.predict(x_train))\n# acc = np.sum(np.argmax(scores, axis=1) == np.argmax(y_train, axis=1)) / len(y_train)\n# logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", acc * 100)\n#\n# scores = get_labels_np_array(classifier.predict(x_test))\n# acc = np.sum(np.argmax(scores, axis=1) == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", acc * 100)\n#\n# self._test_backend_mnist(classifier, x_train, y_train, x_test, y_test)\n#\n# def test_4_pytorch_mnist(self):\n# (x_train, y_train), (x_test, y_test) = self.mnist\n# x_train = np.swapaxes(x_train, 1, 3).astype(np.float32)\n# x_test = np.swapaxes(x_test, 1, 3).astype(np.float32)\n# classifier = get_image_classifier_pt()\n#\n# scores = get_labels_np_array(classifier.predict(x_train))\n# acc = np.sum(np.argmax(scores, axis=1) == np.argmax(y_train, axis=1)) / len(y_train)\n# logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", acc * 100)\n#\n# scores = get_labels_np_array(classifier.predict(x_test))\n# acc = np.sum(np.argmax(scores, axis=1) == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"[PyTorch, MNIST] Accuracy on test set: %.2f%%\", acc * 100)\n#\n# self._test_backend_mnist(classifier, x_train, y_train, x_test, y_test)\n#\n# def _test_backend_mnist(self, classifier, x_train, y_train, x_test, y_test):\n# x_test_original = x_test.copy()\n#\n# # Test PGD with np.inf norm\n# attack = ProjectedGradientDescent(classifier, eps=1, eps_step=0.1, max_iter=5, verbose=False)\n# x_train_adv = attack.generate(x_train)\n# x_test_adv = attack.generate(x_test)\n#\n# self.assertFalse((x_train == x_train_adv).all())\n# self.assertFalse((x_test == x_test_adv).all())\n#\n# train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n# test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n#\n# self.assertFalse((y_train == train_y_pred).all())\n# self.assertFalse((y_test == test_y_pred).all())\n#\n# acc = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(y_train, axis=1)) / len(y_train)\n# logger.info(\"Accuracy on adversarial train examples: %.2f%%\", acc * 100)\n#\n# acc = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"Accuracy on adversarial test examples: %.2f%%\", acc * 100)\n#\n# # Test PGD with 3 random initialisations\n# attack = ProjectedGradientDescent(classifier, num_random_init=3, max_iter=5, verbose=False)\n# x_train_adv = attack.generate(x_train)\n# x_test_adv = attack.generate(x_test)\n#\n# self.assertFalse((x_train == x_train_adv).all())\n# self.assertFalse((x_test == x_test_adv).all())\n#\n# train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n# test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n#\n# self.assertFalse((y_train == train_y_pred).all())\n# self.assertFalse((y_test == test_y_pred).all())\n#\n# acc = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(y_train, axis=1)) / len(y_train)\n# logger.info(\"Accuracy on adversarial train examples with 3 random initialisations: %.2f%%\", acc * 100)\n#\n# acc = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"Accuracy on adversarial test examples with 3 random initialisations: %.2f%%\", acc * 100)\n#\n# # Check that x_test has not been modified by attack and classifier\n# self.assertAlmostEqual(float(np.max(np.abs(np.array(x_test_original) - np.array(x_test)))), 0.0,\n# delta=0.00001)\n#\n# def test_1_classifier_type_check_fail(self):\n# backend_test_classifier_type_check_fail(ProjectedGradientDescent, [BaseEstimator, LossGradientsMixin])\n#\n# def test_6_keras_iris_clipped(self):\n# (_, _), (x_test, y_test) = self.iris\n# classifier = get_tabular_classifier_kr()\n#\n# # Test untargeted attack\n# attack = ProjectedGradientDescent(classifier, eps=1, eps_step=0.1, max_iter=5, verbose=False)\n# x_test_adv = attack.generate(x_test)\n# self.assertFalse((np.array(x_test) == x_test_adv).all())\n# self.assertTrue((x_test_adv <= 1).all())\n# self.assertTrue((x_test_adv >= 0).all())\n#\n# preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n# self.assertFalse((np.argmax(np.array(y_test), axis=1) == preds_adv).all())\n# acc = np.sum(preds_adv == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n#\n# def test_7_keras_iris_unbounded(self):\n# (_, _), (x_test, y_test) = self.iris\n# classifier = get_tabular_classifier_kr()\n#\n# # Recreate a classifier without clip values\n# classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n# attack = ProjectedGradientDescent(classifier, eps=1, eps_step=0.2, max_iter=5, verbose=False)\n# x_test_adv = attack.generate(x_test)\n# self.assertFalse((np.array(x_test) == x_test_adv).all())\n# self.assertTrue((x_test_adv > 1).any())\n# self.assertTrue((x_test_adv < 0).any())\n#\n# preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n# self.assertFalse((np.argmax(np.array(y_test), axis=1) == preds_adv).all())\n# acc = np.sum(preds_adv == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n#\n# def test_2_tensorflow_iris(self):\n# (_, _), (x_test, y_test) = self.iris\n# classifier, _ = get_tabular_classifier_tf()\n#\n# # Test untargeted attack\n# attack = ProjectedGradientDescent(classifier, eps=1, eps_step=0.1, max_iter=5, verbose=False)\n# x_test_adv = attack.generate(x_test)\n# self.assertFalse((np.array(x_test) == x_test_adv).all())\n# self.assertTrue((x_test_adv <= 1).all())\n# self.assertTrue((x_test_adv >= 0).all())\n#\n# preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n# self.assertFalse((np.argmax(np.array(y_test), axis=1) == preds_adv).all())\n# acc = np.sum(preds_adv == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n#\n# def test_3_pytorch_iris_pt(self):\n# (_, _), (x_test, y_test) = self.iris\n# classifier = get_tabular_classifier_pt()\n#\n# # Test untargeted attack\n# attack = ProjectedGradientDescent(classifier, eps=1, eps_step=0.1, max_iter=5, verbose=False)\n# x_test_adv = attack.generate(x_test)\n# self.assertFalse((np.array(x_test) == x_test_adv).all())\n# self.assertTrue((x_test_adv <= 1).all())\n# self.assertTrue((x_test_adv >= 0).all())\n#\n# preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n# self.assertFalse((np.argmax(np.array(y_test), axis=1) == preds_adv).all())\n# acc = np.sum(preds_adv == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n#\n# def test_5_scikitlearn(self):\n# from sklearn.linear_model import LogisticRegression\n# from sklearn.svm import SVC, LinearSVC\n#\n# from art.estimators.classification.scikitlearn import ScikitlearnLogisticRegression, ScikitlearnSVC\n#\n# scikitlearn_test_cases = {\n# LogisticRegression: ScikitlearnLogisticRegression,\n# SVC: ScikitlearnSVC,\n# LinearSVC: ScikitlearnSVC,\n# }\n#\n# (_, _), (x_test, y_test) = self.iris\n#\n# for (model_class, classifier_class) in scikitlearn_test_cases.items():\n# model = model_class()\n# classifier = classifier_class(model=model, clip_values=(0, 1))\n# classifier.fit(x=x_test, y=y_test)\n#\n# # Test untargeted attack\n# attack = ProjectedGradientDescent(classifier, eps=1, eps_step=0.1, max_iter=5, verbose=False)\n# x_test_adv = attack.generate(x_test)\n# self.assertFalse((np.array(x_test) == x_test_adv).all())\n# self.assertTrue((x_test_adv <= 1).all())\n# self.assertTrue((x_test_adv >= 0).all())\n#\n# preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n# self.assertFalse((np.argmax(np.array(y_test), axis=1) == preds_adv).all())\n# acc = np.sum(preds_adv == np.argmax(np.array(y_test), axis=1)) / len(y_test)\n# logger.info(\n# \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with PGD adversarial examples: \" \"%.2f%%\",\n# (acc * 100),\n# )\n#\n#\n# if __name__ == \"__main__\":\n# unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_iterative_method.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.iterative_method import BasicIterativeMethod\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.utils import get_labels_np_array, random_targets\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestIterativeAttack(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 11\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_9b_keras_mnist(self):\n classifier = get_image_classifier_kr()\n\n scores = classifier._model.evaluate(self.x_train_mnist, self.y_train_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on training set: %.2f%%\", (scores[1] * 100))\n scores = classifier._model.evaluate(self.x_test_mnist, self.y_test_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on test set: %.2f%%\", (scores[1] * 100))\n\n self._test_backend_mnist(\n classifier, self.x_train_mnist, self.y_train_mnist, self.x_test_mnist, self.y_test_mnist\n )\n\n def test_3_tensorflow_mnist(self):\n classifier, sess = get_image_classifier_tf()\n\n scores = get_labels_np_array(classifier.predict(self.x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", (acc * 100))\n\n scores = get_labels_np_array(classifier.predict(self.x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", (acc * 100))\n\n self._test_backend_mnist(\n classifier, self.x_train_mnist, self.y_train_mnist, self.x_test_mnist, self.y_test_mnist\n )\n\n def test_6_pytorch_mnist(self):\n classifier = get_image_classifier_pt()\n x_train = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n\n scores = get_labels_np_array(classifier.predict(x_train))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", (acc * 100))\n\n scores = get_labels_np_array(classifier.predict(x_test))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on test set: %.2f%%\", (acc * 100))\n\n self._test_backend_mnist(classifier, x_train, self.y_train_mnist, x_test, self.y_test_mnist)\n\n def _test_backend_mnist(self, classifier, x_train, y_train, x_test, y_test):\n x_test_original = x_test.copy()\n\n # Test BIM with np.inf norm\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.1, batch_size=128, verbose=False)\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train == x_train_adv).all())\n self.assertFalse((x_test == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((y_train == train_y_pred).all())\n self.assertFalse((y_test == test_y_pred).all())\n\n acc = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(y_train, axis=1)) / y_train.shape[0]\n logger.info(\"Accuracy on adversarial train examples: %.2f%%\", (acc * 100))\n\n acc = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(y_test, axis=1)) / y_test.shape[0]\n logger.info(\"Accuracy on adversarial test examples: %.2f%%\", (acc * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n # Test eps of array type 1\n eps = np.ones(shape=x_test.shape) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n # Test eps of array type 2\n eps = np.ones(shape=x_test.shape[1:]) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n # Test eps of array type 3\n eps = np.ones(shape=x_test.shape[2:]) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n # Test eps of array type 4\n eps = np.ones(shape=x_test.shape[3:]) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n def _test_mnist_targeted(self, classifier, x_test):\n x_test_original = x_test.copy()\n\n # Test FGSM with np.inf norm\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.01, targeted=True, batch_size=128, verbose=False)\n # y_test_adv = to_categorical((np.argmax(y_test, axis=1) + 1) % 10, 10)\n pred_sort = classifier.predict(x_test).argsort(axis=1)\n y_test_adv = np.zeros((x_test.shape[0], 10))\n for i in range(x_test.shape[0]):\n y_test_adv[i, pred_sort[i, -2]] = 1.0\n x_test_adv = attack.generate(x_test, y=y_test_adv)\n\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertEqual(y_test_adv.shape, test_y_pred.shape)\n # This doesn't work all the time, especially with small networks\n self.assertGreaterEqual((y_test_adv == test_y_pred).sum(), x_test.shape[0] // 2)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_9c_keras_mnist_targeted(self):\n classifier = get_image_classifier_kr()\n self._test_mnist_targeted(classifier, self.x_test_mnist)\n\n def test_4_tensorflow_mnist_targeted(self):\n classifier, sess = get_image_classifier_tf()\n self._test_mnist_targeted(classifier, self.x_test_mnist)\n\n def test_7_pytorch_mnist_targeted(self):\n classifier = get_image_classifier_pt()\n x_test = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n self._test_mnist_targeted(classifier, x_test)\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(BasicIterativeMethod, [BaseEstimator, LossGradientsMixin])\n\n def test_9_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n # Test untargeted attack\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.1, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with BIM adversarial examples: %.2f%%\", (acc * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = BasicIterativeMethod(classifier, targeted=True, eps=1.0, eps_step=0.1, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Success rate of targeted BIM on Iris: %.2f%%\", (acc * 100))\n\n def test_9a_keras_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.2, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv > 1).any())\n self.assertTrue((x_test_adv < 0).any())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with BIM adversarial examples: %.2f%%\", (acc * 100))\n\n def test_2_tensorflow_iris(self):\n classifier, _ = get_tabular_classifier_tf()\n\n # Test untargeted attack\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with BIM adversarial examples: %.2f%%\", (acc * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = BasicIterativeMethod(classifier, targeted=True, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Success rate of targeted BIM on Iris: %.2f%%\", (acc * 100))\n\n def test_5_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n\n # Test untargeted attack\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.1, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with BIM adversarial examples: %.2f%%\", (acc * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = BasicIterativeMethod(classifier, targeted=True, eps=1.0, eps_step=0.1, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Success rate of targeted BIM on Iris: %.2f%%\", (acc * 100))\n\n def test_8_scikitlearn(self):\n from sklearn.linear_model import LogisticRegression\n from sklearn.svm import SVC, LinearSVC\n\n from art.estimators.classification.scikitlearn import SklearnClassifier\n\n scikitlearn_test_cases = [\n LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n SVC(gamma=\"auto\"),\n LinearSVC(),\n ]\n\n x_test_original = self.x_test_iris.copy()\n\n for model in scikitlearn_test_cases:\n classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n\n # Test untargeted attack\n attack = BasicIterativeMethod(classifier, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with BIM adversarial examples: \" \"%.2f%%\",\n (acc * 100),\n )\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = BasicIterativeMethod(\n classifier, targeted=True, eps=1.0, eps_step=0.1, batch_size=128, max_iter=5, verbose=False\n )\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Success rate of \" + classifier.__class__.__name__ + \" on targeted BIM on Iris: %.2f%%\", (acc * 100)\n )\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_knockoff_nets.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport keras.backend as k\n\nfrom art.attacks.extraction.knockoff_nets import KnockoffNets\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.utils import TestBase, master_seed\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr, get_image_classifier_pt\nfrom tests.utils import get_tabular_classifier_tf, get_tabular_classifier_kr, get_tabular_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 100\nNB_EPOCHS = 10\nNB_STOLEN = 100\n\n\nclass TestKnockoffNets(TestBase):\n \"\"\"\n A unittest class for testing the KnockoffNets attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUpClass()\n\n def setUp(self):\n super().setUp()\n\n def test_3_tensorflow_classifier(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n # Build TensorFlowClassifier\n victim_tfc, sess = get_image_classifier_tf()\n\n # Create the thieved classifier\n thieved_tfc, _ = get_image_classifier_tf(load_init=False, sess=sess)\n\n # Create random attack\n attack = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"random\",\n verbose=False,\n )\n thieved_tfc = attack.extract(x=self.x_train_mnist, thieved_classifier=thieved_tfc)\n\n victim_preds = np.argmax(victim_tfc.predict(x=self.x_train_mnist), axis=1)\n thieved_preds = np.argmax(thieved_tfc.predict(x=self.x_train_mnist), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Create adaptive attack\n attack = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n thieved_tfc = attack.extract(x=self.x_train_mnist, y=self.y_train_mnist, thieved_classifier=thieved_tfc)\n\n victim_preds = np.argmax(victim_tfc.predict(x=self.x_train_mnist), axis=1)\n thieved_preds = np.argmax(thieved_tfc.predict(x=self.x_train_mnist), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.4)\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=-1,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=-1,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=-1,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=-1,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"test\",\n reward=\"all\",\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"test\",\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=\"False\",\n )\n\n with self.assertRaises(ValueError):\n _ = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n use_probability=\"True\",\n )\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_7_keras_classifier(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n # Build KerasClassifier\n victim_krc = get_image_classifier_kr()\n\n # Create the thieved classifier\n thieved_krc = get_image_classifier_kr(load_init=False)\n\n # Create random attack\n attack = KnockoffNets(\n classifier=victim_krc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"random\",\n verbose=False,\n )\n thieved_krc = attack.extract(x=self.x_train_mnist, thieved_classifier=thieved_krc)\n\n victim_preds = np.argmax(victim_krc.predict(x=self.x_train_mnist), axis=1)\n thieved_preds = np.argmax(thieved_krc.predict(x=self.x_train_mnist), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Create adaptive attack\n attack = KnockoffNets(\n classifier=victim_krc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n thieved_krc = attack.extract(x=self.x_train_mnist, y=self.y_train_mnist, thieved_classifier=thieved_krc)\n\n victim_preds = np.argmax(victim_krc.predict(x=self.x_train_mnist), axis=1)\n thieved_preds = np.argmax(thieved_krc.predict(x=self.x_train_mnist), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.4)\n\n # Clean-up\n k.clear_session()\n\n def test_5_pytorch_classifier(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n self.x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n\n # Build PyTorchClassifier\n victim_ptc = get_image_classifier_pt()\n\n # Create the thieved classifier\n thieved_ptc = get_image_classifier_pt(load_init=False)\n\n # Create random attack\n attack = KnockoffNets(\n classifier=victim_ptc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"random\",\n verbose=False,\n )\n\n thieved_ptc = attack.extract(x=self.x_train_mnist, thieved_classifier=thieved_ptc)\n\n victim_preds = np.argmax(victim_ptc.predict(x=self.x_train_mnist), axis=1)\n thieved_preds = np.argmax(thieved_ptc.predict(x=self.x_train_mnist), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Create adaptive attack\n attack = KnockoffNets(\n classifier=victim_ptc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n thieved_ptc = attack.extract(x=self.x_train_mnist, y=self.y_train_mnist, thieved_classifier=thieved_ptc)\n\n victim_preds = np.argmax(victim_ptc.predict(x=self.x_train_mnist), axis=1)\n thieved_preds = np.argmax(thieved_ptc.predict(x=self.x_train_mnist), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.4)\n\n self.x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 28, 28, 1)).astype(np.float32)\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(KnockoffNets, [BaseEstimator, ClassifierMixin])\n\n def test_2_tensorflow_iris(self):\n \"\"\"\n First test for TensorFlow.\n :return:\n \"\"\"\n # Get the TensorFlow classifier\n victim_tfc, sess = get_tabular_classifier_tf()\n\n # Create the thieved classifier\n thieved_tfc, _ = get_tabular_classifier_tf(load_init=False, sess=sess)\n\n # Create random attack\n attack = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"random\",\n verbose=False,\n )\n thieved_tfc = attack.extract(x=self.x_train_iris, thieved_classifier=thieved_tfc)\n\n victim_preds = np.argmax(victim_tfc.predict(x=self.x_train_iris), axis=1)\n thieved_preds = np.argmax(thieved_tfc.predict(x=self.x_train_iris), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Create adaptive attack\n attack = KnockoffNets(\n classifier=victim_tfc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n thieved_tfc = attack.extract(x=self.x_train_iris, y=self.y_train_iris, thieved_classifier=thieved_tfc)\n\n victim_preds = np.argmax(victim_tfc.predict(x=self.x_train_iris), axis=1)\n thieved_preds = np.argmax(thieved_tfc.predict(x=self.x_train_iris), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.4)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_6_keras_iris(self):\n \"\"\"\n Second test for Keras.\n :return:\n \"\"\"\n # Build KerasClassifier\n victim_krc = get_tabular_classifier_kr()\n\n # Create the thieved classifier\n thieved_krc = get_tabular_classifier_kr(load_init=False)\n\n # Create random attack\n attack = KnockoffNets(\n classifier=victim_krc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"random\",\n verbose=False,\n )\n thieved_krc = attack.extract(x=self.x_train_iris, thieved_classifier=thieved_krc)\n\n victim_preds = np.argmax(victim_krc.predict(x=self.x_train_iris), axis=1)\n thieved_preds = np.argmax(thieved_krc.predict(x=self.x_train_iris), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.3)\n\n # Create adaptive attack\n attack = KnockoffNets(\n classifier=victim_krc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n thieved_krc = attack.extract(x=self.x_train_iris, y=self.y_train_iris, thieved_classifier=thieved_krc)\n\n victim_preds = np.argmax(victim_krc.predict(x=self.x_train_iris), axis=1)\n thieved_preds = np.argmax(thieved_krc.predict(x=self.x_train_iris), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.33)\n\n # Clean-up\n k.clear_session()\n\n def test_4_pytorch_iris(self):\n \"\"\"\n Third test for PyTorch.\n :return:\n \"\"\"\n # Build PyTorchClassifier\n victim_ptc = get_tabular_classifier_pt()\n\n # Create the thieved classifier\n thieved_ptc = get_tabular_classifier_pt(load_init=False)\n\n # Create random attack\n attack = KnockoffNets(\n classifier=victim_ptc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"random\",\n verbose=False,\n )\n thieved_ptc = attack.extract(x=self.x_train_iris, thieved_classifier=thieved_ptc)\n\n victim_preds = np.argmax(victim_ptc.predict(x=self.x_train_iris), axis=1)\n thieved_preds = np.argmax(thieved_ptc.predict(x=self.x_train_iris), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.25)\n\n # Create adaptive attack\n attack = KnockoffNets(\n classifier=victim_ptc,\n batch_size_fit=BATCH_SIZE,\n batch_size_query=BATCH_SIZE,\n nb_epochs=NB_EPOCHS,\n nb_stolen=NB_STOLEN,\n sampling_strategy=\"adaptive\",\n reward=\"all\",\n verbose=False,\n )\n thieved_ptc = attack.extract(x=self.x_train_iris, y=self.y_train_iris, thieved_classifier=thieved_ptc)\n\n victim_preds = np.argmax(victim_ptc.predict(x=self.x_train_iris), axis=1)\n thieved_preds = np.argmax(thieved_ptc.predict(x=self.x_train_iris), axis=1)\n acc = np.sum(victim_preds == thieved_preds) / len(victim_preds)\n\n self.assertGreater(acc, 0.4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_newtonfool.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.newtonfool import NewtonFool\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestNewtonFool(TestBase):\n \"\"\"\n A unittest class for testing the NewtonFool attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n def test_3_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # Attack\n nf = NewtonFool(tfc, max_iter=5, batch_size=100, verbose=False)\n x_test_adv = nf.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n y_pred = tfc.predict(self.x_test_mnist)\n y_pred_adv = tfc.predict(x_test_adv)\n y_pred_bool = y_pred.max(axis=1, keepdims=1) == y_pred\n y_pred_max = y_pred.max(axis=1)\n y_pred_adv_max = y_pred_adv[y_pred_bool]\n self.assertTrue((y_pred_max >= 0.9 * y_pred_adv_max).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_9_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # Attack\n nf = NewtonFool(krc, max_iter=5, batch_size=100, verbose=False)\n x_test_adv = nf.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n y_pred = krc.predict(self.x_test_mnist)\n y_pred_adv = krc.predict(x_test_adv)\n y_pred_bool = y_pred.max(axis=1, keepdims=1) == y_pred\n y_pred_max = y_pred.max(axis=1)\n y_pred_adv_max = y_pred_adv[y_pred_bool]\n self.assertTrue((y_pred_max >= 0.9 * y_pred_adv_max).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_5_pytorch_mnist(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_test = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n x_test_original = x_test.copy()\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt()\n\n # Attack\n nf = NewtonFool(ptc, max_iter=5, batch_size=100, verbose=False)\n x_test_adv = nf.generate(x_test)\n\n self.assertFalse((x_test == x_test_adv).all())\n\n y_pred = ptc.predict(x_test)\n y_pred_adv = ptc.predict(x_test_adv)\n y_pred_bool = y_pred.max(axis=1, keepdims=1) == y_pred\n y_pred_max = y_pred.max(axis=1)\n y_pred_adv_max = y_pred_adv[y_pred_bool]\n self.assertTrue((y_pred_max >= 0.9 * y_pred_adv_max).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_7_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n attack = NewtonFool(classifier, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with NewtonFool adversarial examples: %.2f%%\", (acc * 100))\n\n def test_8_keras_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = NewtonFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with NewtonFool adversarial examples: %.2f%%\", (acc * 100))\n\n def test_2_tensorflow_iris(self):\n classifier, _ = get_tabular_classifier_tf()\n\n attack = NewtonFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with NewtonFool adversarial examples: %.2f%%\", (acc * 100))\n\n def test_4_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n\n attack = NewtonFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with NewtonFool adversarial examples: %.2f%%\", (acc * 100))\n\n def test_6_scikitlearn(self):\n from sklearn.linear_model import LogisticRegression\n from sklearn.svm import SVC, LinearSVC\n\n from art.estimators.classification.scikitlearn import SklearnClassifier\n\n scikitlearn_test_cases = [\n LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n SVC(gamma=\"auto\"),\n LinearSVC(),\n ]\n\n x_test_original = self.x_test_iris.copy()\n\n for model in scikitlearn_test_cases:\n classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n\n attack = NewtonFool(classifier, max_iter=5, batch_size=128, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with NewtonFool adversarial examples\"\n \": %.2f%%\",\n (acc * 100),\n )\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = NewtonFool(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = NewtonFool(ptc, eta=-1)\n\n with self.assertRaises(ValueError):\n _ = NewtonFool(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = NewtonFool(ptc, verbose=\"False\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(NewtonFool, [BaseEstimator, ClassGradientsMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_overload_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion.overload.overload import OverloadPyTorch\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_generate(art_warning, get_pytorch_detector_yolo):\n try:\n from io import BytesIO\n from PIL import Image\n import requests\n import torch\n\n threshold = 0.85\n\n object_detector = get_pytorch_detector_yolo\n object_detector.set_params(input_shape=(3, 640, 640))\n\n # Download a sample image\n target = \"https://ultralytics.com/images/zidane.jpg\"\n response = requests.get(target)\n org_img = np.asarray(Image.open(BytesIO(response.content)).resize((640, 640)))\n x_255 = np.stack([org_img.transpose((2, 0, 1))], axis=0).astype(np.uint8)\n x = x_255.astype(np.float32) / 255.0\n\n y_pred = object_detector.predict(x=x)\n\n attack = OverloadPyTorch(\n object_detector, eps=16.0 / 255.0, max_iter=10, num_grid=10, batch_size=1, threshold=threshold\n )\n\n x_adv = attack.generate(x=x, y=y_pred)\n\n assert x.shape == x_adv.shape\n assert np.min(x_adv) >= 0.0\n assert np.max(x_adv) <= 1.0\n\n y_pred_adv = object_detector.predict(x=x_adv)\n\n scores_list = list(y_pred[0][\"scores\"])\n scores_list_adv = list(y_pred_adv[0][\"scores\"])\n\n scores_list_filtered = [scores_list.index(x) for x in scores_list if x > threshold]\n scores_list_adv_filtered = [scores_list_adv.index(x) for x in scores_list_adv if x > threshold]\n\n assert len(scores_list_filtered) == 11\n assert len(scores_list_adv_filtered) > 170\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning, get_pytorch_detector_yolo):\n try:\n object_detector = get_pytorch_detector_yolo\n object_detector.set_params(input_shape=(3, 640, 640))\n\n with pytest.raises(ValueError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=-1.0, max_iter=5, num_grid=10, batch_size=1, threshold=0.5\n )\n with pytest.raises(ValueError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=2.0, max_iter=5, num_grid=10, batch_size=1, threshold=0.5\n )\n with pytest.raises(TypeError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=1.0, num_grid=10, batch_size=1, threshold=0.5\n )\n with pytest.raises(ValueError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=0, num_grid=10, batch_size=1, threshold=0.5\n )\n with pytest.raises(TypeError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=1.0, batch_size=1, threshold=0.5\n )\n with pytest.raises(ValueError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=0, batch_size=1, threshold=0.5\n )\n with pytest.raises(TypeError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=10, batch_size=1.0, threshold=0.5\n )\n with pytest.raises(ValueError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=0, batch_size=0, threshold=0.5\n )\n with pytest.raises(ValueError):\n _ = OverloadPyTorch(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=0, batch_size=1, threshold=1.5\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_pixel_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module tests the Pixel Attack.\nThe Pixel Attack is a generalisation of One Pixel Attack.\n\n| One Pixel Attack Paper link:\n https://ieeexplore.ieee.org/abstract/document/8601309/citations#citations\n (arXiv link: https://arxiv.org/pdf/1710.08864.pdf)\n| Pixel Attack Paper link:\n https://arxiv.org/abs/1906.06026\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.pixel_threshold import PixelAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_pt # , get_image_classifier_kr\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestPixelAttack(TestBase):\n \"\"\"\n A unittest class for testing the Pixel Attack.\n\n This module tests the Pixel Attack.\n The Pixel Attack is a generalisation of One Pixel Attack.\n\n | One Pixel Attack Paper link:\n https://ieeexplore.ieee.org/abstract/document/8601309/citations#citations\n (arXiv link: https://arxiv.org/pdf/1710.08864.pdf)\n | Pixel Attack Paper link:\n https://arxiv.org/abs/1906.06026\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_test = 2\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n # def test_6_keras_mnist(self):\n # \"\"\"\n # Test with the KerasClassifier. (Untargeted Attack)\n # :return:\n # \"\"\"\n #\n # classifier = get_image_classifier_kr()\n # self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, False)\n\n # def test_2_tensorflow_mnist(self):\n # \"\"\"\n # Test with the TensorFlowClassifier. (Untargeted Attack)\n # :return:\n # \"\"\"\n # classifier, sess = get_image_classifier_tf()\n # self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, False)\n\n def test_4_pytorch_mnist(self):\n \"\"\"\n Test with the PyTorchClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n classifier = get_image_classifier_pt()\n self._test_attack(classifier, x_test, self.y_test_mnist, False)\n\n def test_8_pytorch_mnist_single_sample(self):\n \"\"\"\n Test with the PyTorchClassifier on a single sample. (Untargeted Attack)\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist[1], (1, 1, 28, 28)).astype(np.float32)\n classifier = get_image_classifier_pt()\n self._test_attack(classifier, x_test, self.y_test_mnist[[1]], False)\n\n # def test_7_keras_mnist_targeted(self):\n # \"\"\"\n # Test with the KerasClassifier. (Targeted Attack)\n # :return:\n # \"\"\"\n # classifier = get_image_classifier_kr()\n # self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, True)\n\n def test_3_tensorflow_mnist_targeted(self):\n \"\"\"\n Test with the TensorFlowClassifier. (Targeted Attack)\n :return:\n \"\"\"\n classifier, sess = get_image_classifier_tf()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, True)\n\n # def test_5_pytorch_mnist_targeted(self):\n # \"\"\"\n # Test with the PyTorchClassifier. (Targeted Attack)\n # :return:\n # \"\"\"\n # x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n # classifier = get_image_classifier_pt()\n # self._test_attack(classifier, x_test, self.y_test_mnist, True)\n\n def _test_attack(self, classifier, x_test, y_test, targeted):\n \"\"\"\n Test with the Pixel Attack\n :return:\n \"\"\"\n x_test_original = x_test.copy()\n\n if targeted:\n # Generate random target classes\n class_y_test = np.argmax(y_test, axis=1)\n nb_classes = np.unique(class_y_test).shape[0]\n targets = np.random.randint(nb_classes, size=self.n_test)\n for i in range(self.n_test):\n if class_y_test[i] == targets[i]:\n targets[i] -= 1\n else:\n targets = y_test\n\n for th in [None, 128]:\n for es in [0, 1]:\n df = PixelAttack(classifier, th=th, es=es, max_iter=20, targeted=targeted, verbose=False)\n x_test_adv = df.generate(x_test_original, targets)\n\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, x_test, x_test_adv)\n self.assertFalse((0.0 == x_test_adv).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = PixelAttack(ptc, th=-1)\n\n with self.assertRaises(ValueError):\n _ = PixelAttack(ptc, es=1.0)\n\n with self.assertRaises(ValueError):\n _ = PixelAttack(ptc, targeted=\"true\")\n\n with self.assertRaises(ValueError):\n _ = PixelAttack(ptc, verbose=\"true\")\n\n with self.assertRaises(ValueError):\n ptc._clip_values = None\n _ = PixelAttack(ptc)\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(PixelAttack, [BaseEstimator, NeuralNetworkMixin, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_poisoning_attack_svm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nfrom sklearn.svm import NuSVC, SVC\n\nfrom art.attacks.poisoning import PoisoningAttackSVM\nfrom art.estimators.classification.scikitlearn import SklearnClassifier, ScikitlearnSVC\nfrom art.utils import load_iris\n\nfrom tests.utils import master_seed\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 10\nNB_VALID = 10\nNB_TEST = 10\n\n\nclass TestSVMAttack(unittest.TestCase):\n \"\"\"\n A unittest class for testing Poisoning Attack on SVMs.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n cls.setUpIRIS()\n\n @staticmethod\n def find_duplicates(x_train):\n \"\"\"\n Returns an array of booleans that is true if that element was previously in the array\n\n :param x_train: training data\n :type x_train: `np.ndarray`\n :return: duplicates array\n :rtype: `np.ndarray`\n \"\"\"\n dup = np.zeros(x_train.shape[0])\n for idx, x in enumerate(x_train):\n dup[idx] = np.isin(x_train[:idx], x).all(axis=1).any()\n return dup\n\n @classmethod\n def setUpIRIS(cls):\n (x_train, y_train), (x_test, y_test), min_, max_ = load_iris()\n # Naturally IRIS has labels 0, 1, and 2. For binary classification use only classes 1 and 2.\n no_zero = np.where(np.argmax(y_train, axis=1) != 0)\n x_train = x_train[no_zero, :2][0]\n y_train = y_train[no_zero]\n no_zero = np.where(np.argmax(y_test, axis=1) != 0)\n x_test = x_test[no_zero, :2][0]\n y_test = y_test[no_zero]\n labels = np.zeros((y_train.shape[0], 2))\n labels[np.argmax(y_train, axis=1) == 2] = np.array([1, 0])\n labels[np.argmax(y_train, axis=1) == 1] = np.array([0, 1])\n y_train = labels\n te_labels = np.zeros((y_test.shape[0], 2))\n te_labels[np.argmax(y_test, axis=1) == 2] = np.array([1, 0])\n te_labels[np.argmax(y_test, axis=1) == 1] = np.array([0, 1])\n y_test = te_labels\n n_sample = len(x_train)\n\n order = np.random.permutation(n_sample)\n x_train = x_train[order]\n y_train = y_train[order].astype(float)\n\n x_train = x_train[: int(0.9 * n_sample)]\n y_train = y_train[: int(0.9 * n_sample)]\n train_dups = cls.find_duplicates(x_train)\n x_train = x_train[np.logical_not(train_dups)]\n y_train = y_train[np.logical_not(train_dups)]\n test_dups = cls.find_duplicates(x_test)\n x_test = x_test[np.logical_not(test_dups)]\n y_test = y_test[np.logical_not(test_dups)]\n cls.iris = (x_train, y_train), (x_test, y_test), min_, max_\n\n def setUp(self):\n super().setUp()\n\n # def test_linearSVC(self):\n # \"\"\"\n # Test using a attack on LinearSVC\n # \"\"\"\n # (x_train, y_train), (x_test, y_test), min_, max_ = self.iris\n # x_test_original = x_test.copy()\n #\n # # Build Scikitlearn Classifier\n # clip_values = (min_, max_)\n # clean = SklearnClassifier(model=LinearSVC(), clip_values=clip_values)\n # clean.fit(x_train, y_train)\n # poison = SklearnClassifier(model=LinearSVC(), clip_values=clip_values)\n # poison.fit(x_train, y_train)\n # attack = PoisoningAttackSVM(poison, 0.01, 1.0, x_train, y_train, x_test, y_test, 100)\n # attack_y = np.array([1, 1]) - y_train[0]\n # attack_point, _ = attack.poison(np.array([x_train[0]]), y=np.array([attack_y]))\n # poison.fit(x=np.vstack([x_train, attack_point]), y=np.vstack([y_train, np.copy(y_train[0].reshape((1, 2)))]))\n #\n # acc = np.average(np.all(clean.predict(x_test) == y_test, axis=1)) * 100\n # poison_acc = np.average(np.all(poison.predict(x_test) == y_test, axis=1)) * 100\n # logger.info(\"Clean Accuracy {}%\".format(acc))\n # logger.info(\"Poison Accuracy {}%\".format(poison_acc))\n # self.assertGreaterEqual(acc, poison_acc)\n #\n # # Check that x_test has not been modified by attack and classifier\n # self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_unsupported_kernel(self):\n (x_train, y_train), (x_test, y_test), min_, max_ = self.iris\n model = SVC(kernel=\"sigmoid\", gamma=\"auto\")\n with self.assertRaises(TypeError):\n _ = PoisoningAttackSVM(\n classifier=model, step=0.01, eps=1.0, x_train=x_train, y_train=y_train, x_val=x_test, y_val=y_test\n )\n\n def test_unsupported_SVC(self):\n (x_train, y_train), (x_test, y_test), _, _ = self.iris\n model = NuSVC()\n with self.assertRaises(TypeError):\n _ = PoisoningAttackSVM(\n classifier=model, step=0.01, eps=1.0, x_train=x_train, y_train=y_train, x_val=x_test, y_val=y_test\n )\n\n def test_SVC_kernels(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n # Get MNIST\n (x_train, y_train), (x_test, y_test), min_, max_ = self.iris\n x_test_original = x_test.copy()\n\n # Build Scikitlearn Classifier\n clip_values = (min_, max_)\n for kernel in [\"linear\"]: # [\"linear\", \"poly\", \"rbf\"]\n clean = SklearnClassifier(model=SVC(kernel=kernel, gamma=\"auto\"), clip_values=clip_values)\n clean.fit(x_train, y_train)\n poison = SklearnClassifier(model=SVC(kernel=kernel, gamma=\"auto\"), clip_values=clip_values)\n poison.fit(x_train, y_train)\n attack = PoisoningAttackSVM(\n poison, step=0.01, eps=1.0, x_train=x_train, y_train=y_train, x_val=x_test, y_val=y_test, max_iter=100\n )\n attack_y = np.array([1, 1]) - y_train[0]\n attack_point, _ = attack.poison(np.array([x_train[0]]), y=np.array([attack_y]))\n poison.fit(\n x=np.vstack([x_train, attack_point]),\n y=np.vstack([y_train, np.array([1, 1]) - np.copy(y_train[0].reshape((1, 2)))]),\n )\n\n acc = np.average(np.all(clean.predict(x_test) == y_test, axis=1)) * 100\n poison_acc = np.average(np.all(poison.predict(x_test) == y_test, axis=1)) * 100\n logger.info(\"Clean Accuracy {}%\".format(acc))\n logger.info(\"Poison Accuracy {}%\".format(poison_acc))\n self.assertGreaterEqual(acc, poison_acc)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_classifier_type_check_fail(self):\n (x_train, y_train), (x_test, y_test), min_, max_ = self.iris\n backend_test_classifier_type_check_fail(\n PoisoningAttackSVM,\n [ScikitlearnSVC],\n step=0.01,\n eps=1.0,\n x_train=x_train,\n y_train=y_train,\n x_val=x_test,\n y_val=y_test,\n max_iter=100,\n )\n\n def test_check_params(self):\n (x_train, y_train), (x_test, y_test), min_, max_ = self.iris\n clip_values = (min_, max_)\n poison = SklearnClassifier(model=SVC(kernel=\"linear\", gamma=\"auto\"), clip_values=clip_values)\n poison.fit(x_train, y_train)\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackSVM(\n poison,\n step=-0.01,\n eps=1.0,\n x_train=x_train,\n y_train=y_train,\n x_val=x_test,\n y_val=y_test,\n max_iter=100,\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackSVM(\n poison,\n step=0.01,\n eps=-1.0,\n x_train=x_train,\n y_train=y_train,\n x_val=x_test,\n y_val=y_test,\n max_iter=100,\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackSVM(\n poison,\n step=0.01,\n eps=1.0,\n x_train=x_train,\n y_train=y_train,\n x_val=x_test,\n y_val=y_test,\n max_iter=-1,\n verbose=False,\n )\n\n with self.assertRaises(ValueError):\n _ = PoisoningAttackSVM(\n poison,\n step=0.01,\n eps=1.0,\n x_train=x_train,\n y_train=y_train,\n x_val=x_test,\n y_val=y_test,\n max_iter=100,\n verbose=\"False\",\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_projected_gradient_descent.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_numpy import (\n ProjectedGradientDescentNumpy,\n ProjectedGradientDescentCommon,\n)\nfrom art.estimators.classification import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.utils import get_labels_np_array, random_targets\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n master_seed,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestPGD(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 10\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_9a_keras_mnist(self):\n classifier = get_image_classifier_kr()\n\n scores = classifier._model.evaluate(self.x_train_mnist, self.y_train_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on training set: %.2f%%\", scores[1] * 100)\n scores = classifier._model.evaluate(self.x_test_mnist, self.y_test_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on test set: %.2f%%\", scores[1] * 100)\n\n self._test_backend_mnist(\n classifier, self.x_train_mnist, self.y_train_mnist, self.x_test_mnist, self.y_test_mnist\n )\n\n def test_check_params(self):\n\n krc = get_image_classifier_kr(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, norm=-1)\n\n with self.assertRaises(TypeError):\n _ = ProjectedGradientDescentCommon(krc, eps=\"1\", eps_step=0.1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, eps=-1)\n\n with self.assertRaises(TypeError):\n _ = ProjectedGradientDescentCommon(krc, eps=np.array([-1]))\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, eps_step=-1)\n\n with self.assertRaises(TypeError):\n _ = ProjectedGradientDescentCommon(krc, eps_step=np.array([-1]))\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, eps=np.array([1.0, 1.0]), eps_step=np.array([1.0]))\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, targeted=\"False\")\n\n with self.assertRaises(TypeError):\n _ = ProjectedGradientDescentCommon(krc, num_random_init=\"1\")\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, num_random_init=-1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescentCommon(krc, verbose=\"False\")\n\n def test_3_tensorflow_mnist(self):\n classifier, sess = get_image_classifier_tf()\n\n scores = get_labels_np_array(classifier.predict(self.x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", acc * 100)\n\n scores = get_labels_np_array(classifier.predict(self.x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", acc * 100)\n\n self._test_backend_mnist(\n classifier, self.x_train_mnist, self.y_train_mnist, self.x_test_mnist, self.y_test_mnist\n )\n\n def test_5_pytorch_mnist(self):\n x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n classifier = get_image_classifier_pt()\n\n scores = get_labels_np_array(classifier.predict(x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", acc * 100)\n\n scores = get_labels_np_array(classifier.predict(x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on test set: %.2f%%\", acc * 100)\n\n self._test_backend_mnist(classifier, x_train_mnist, self.y_train_mnist, x_test_mnist, self.y_test_mnist)\n\n # Test with clip values of array type\n classifier.set_params(clip_values=(np.zeros_like(x_test_mnist[0]), np.ones_like(x_test_mnist[0])))\n self._test_backend_mnist(classifier, x_train_mnist, self.y_train_mnist, x_test_mnist, self.y_test_mnist)\n\n classifier.set_params(clip_values=(np.zeros_like(x_test_mnist[0][0]), np.ones_like(x_test_mnist[0][0])))\n self._test_backend_mnist(classifier, x_train_mnist, self.y_train_mnist, x_test_mnist, self.y_test_mnist)\n\n classifier.set_params(clip_values=(np.zeros_like(x_test_mnist[0][0][0]), np.ones_like(x_test_mnist[0][0][0])))\n self._test_backend_mnist(classifier, x_train_mnist, self.y_train_mnist, x_test_mnist, self.y_test_mnist)\n\n def _test_backend_mnist(self, classifier, x_train, y_train, x_test, y_test):\n x_test_original = x_test.copy()\n\n # Test PGD with np.inf norm\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.1, verbose=False)\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train == x_train_adv).all())\n self.assertFalse((x_test == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((y_train == train_y_pred).all())\n self.assertFalse((y_test == test_y_pred).all())\n\n acc = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(y_train, axis=1)) / y_train.shape[0]\n logger.info(\"Accuracy on adversarial train examples: %.2f%%\", acc * 100)\n\n acc = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(y_test, axis=1)) / y_test.shape[0]\n logger.info(\"Accuracy on adversarial test examples: %.2f%%\", acc * 100)\n\n # Test PGD with 3 random initialisations\n attack = ProjectedGradientDescent(classifier, num_random_init=3, verbose=False)\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train == x_train_adv).all())\n self.assertFalse((x_test == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((y_train == train_y_pred).all())\n self.assertFalse((y_test == test_y_pred).all())\n\n acc = np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(y_train, axis=1)) / y_train.shape[0]\n logger.info(\"Accuracy on adversarial train examples with 3 random initialisations: %.2f%%\", acc * 100)\n\n acc = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(y_test, axis=1)) / y_test.shape[0]\n logger.info(\"Accuracy on adversarial test examples with 3 random initialisations: %.2f%%\", acc * 100)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n # Test the masking\n attack = ProjectedGradientDescent(classifier, num_random_init=1, verbose=False)\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test.shape))\n mask = mask.reshape(x_test.shape).astype(np.float32)\n\n x_test_adv = attack.generate(x_test, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - x_test)\n self.assertAlmostEqual(float(np.max(np.abs(mask_diff))), 0.0, delta=0.00001)\n\n # Test eps of array type 1\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.1, verbose=False)\n\n eps = np.ones(shape=x_test.shape) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n # Test eps of array type 2\n eps = np.ones(shape=x_test.shape[1:]) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n # Test eps of array type 3\n eps = np.ones(shape=x_test.shape[2:]) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n # Test eps of array type 4\n eps = np.ones(shape=x_test.shape[3:]) * 1.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == test_y_pred).all())\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(ProjectedGradientDescent, [BaseEstimator, LossGradientsMixin])\n\n def test_8_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n # Test untargeted attack\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = ProjectedGradientDescent(classifier, targeted=True, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Success rate of targeted PGD on Iris: %.2f%%\", (acc * 100))\n\n def test_keras_9_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.2, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv > 1).any())\n self.assertTrue((x_test_adv < 0).any())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n\n def test_2_tensorflow_iris(self):\n classifier, _ = get_tabular_classifier_tf()\n\n # Test untargeted attack\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = ProjectedGradientDescent(classifier, targeted=True, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Success rate of targeted PGD on Iris: %.2f%%\", (acc * 100))\n\n def test_4_pytorch_iris_pt(self):\n classifier = get_tabular_classifier_pt()\n\n # Test untargeted attack\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with PGD adversarial examples: %.2f%%\", (acc * 100))\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = ProjectedGradientDescent(classifier, targeted=True, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Success rate of targeted PGD on Iris: %.2f%%\", (acc * 100))\n\n def test_7_scikitlearn(self):\n from sklearn.linear_model import LogisticRegression\n from sklearn.svm import SVC, LinearSVC\n\n from art.estimators.classification.scikitlearn import SklearnClassifier\n\n scikitlearn_test_cases = [\n LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n SVC(gamma=\"auto\"),\n LinearSVC(),\n ]\n\n x_test_original = self.x_test_iris.copy()\n\n for model in scikitlearn_test_cases:\n classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n\n # Test untargeted attack\n attack = ProjectedGradientDescent(classifier, eps=1.0, eps_step=0.1, max_iter=5, verbose=False)\n x_test_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with PGD adversarial examples: \" \"%.2f%%\",\n (acc * 100),\n )\n\n # Test targeted attack\n targets = random_targets(self.y_test_iris, nb_classes=3)\n attack = ProjectedGradientDescent(\n classifier, targeted=True, eps=1.0, eps_step=0.1, max_iter=5, verbose=False\n )\n x_test_adv = attack.generate(self.x_test_iris, **{\"y\": targets})\n self.assertFalse((self.x_test_iris == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertTrue((np.argmax(targets, axis=1) == preds_adv).any())\n acc = np.sum(preds_adv == np.argmax(targets, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Success rate of \" + classifier.__class__.__name__ + \" on targeted PGD on Iris: %.2f%%\", (acc * 100)\n )\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_4_framework_tensorflow_v2_mnist(self):\n classifier, _ = get_image_classifier_tf()\n self._test_framework_vs_numpy(classifier)\n\n def test_6_framework_pytorch_mnist(self):\n self.x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n self.x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n\n classifier = get_image_classifier_pt()\n self._test_framework_vs_numpy(classifier)\n\n self.x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n self.x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n\n def _test_framework_vs_numpy(self, classifier):\n # Test PGD with np.inf norm\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_np = attack_np.generate(self.x_train_mnist)\n x_test_adv_np = attack_np.generate(self.x_test_mnist)\n\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test PGD with L1 norm\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=1,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_np = attack_np.generate(self.x_train_mnist)\n x_test_adv_np = attack_np.generate(self.x_test_mnist)\n\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=1,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test PGD with L2 norm\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=2,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_np = attack_np.generate(self.x_train_mnist)\n x_test_adv_np = attack_np.generate(self.x_test_mnist)\n\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=2,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test PGD with True targeted\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=True,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_np = attack_np.generate(self.x_train_mnist, self.y_train_mnist)\n x_test_adv_np = attack_np.generate(self.x_test_mnist, self.y_test_mnist)\n\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=True,\n num_random_init=0,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist, self.y_train_mnist)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist, self.y_test_mnist)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test PGD with num_random_init=2\n master_seed(1234)\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=2,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_np = attack_np.generate(self.x_train_mnist)\n x_test_adv_np = attack_np.generate(self.x_test_mnist)\n\n master_seed(1234)\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=2,\n batch_size=3,\n random_eps=False,\n verbose=False,\n )\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test PGD with random_eps=True\n master_seed(1234)\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=True,\n verbose=False,\n )\n x_train_adv_np = attack_np.generate(self.x_train_mnist)\n x_test_adv_np = attack_np.generate(self.x_test_mnist)\n\n master_seed(1234)\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=0,\n batch_size=3,\n random_eps=True,\n verbose=False,\n )\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test the masking 1\n master_seed(1234)\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=1,\n batch_size=3,\n random_eps=True,\n verbose=False,\n )\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_train_mnist.shape))\n mask = mask.reshape(self.x_train_mnist.shape).astype(np.float32)\n x_train_adv_np = attack_np.generate(self.x_train_mnist, mask=mask)\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape).astype(np.float32)\n x_test_adv_np = attack_np.generate(self.x_test_mnist, mask=mask)\n\n master_seed(1234)\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=1,\n batch_size=3,\n random_eps=True,\n verbose=False,\n )\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_train_mnist.shape))\n mask = mask.reshape(self.x_train_mnist.shape).astype(np.float32)\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist, mask=mask)\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape))\n mask = mask.reshape(self.x_test_mnist.shape).astype(np.float32)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist, mask=mask)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n # Test the masking 2\n master_seed(1234)\n attack_np = ProjectedGradientDescentNumpy(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=1,\n batch_size=3,\n random_eps=True,\n verbose=False,\n )\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_train_mnist.shape[1:]))\n mask = mask.reshape(self.x_train_mnist.shape[1:]).astype(np.float32)\n x_train_adv_np = attack_np.generate(self.x_train_mnist, mask=mask)\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:]).astype(np.float32)\n x_test_adv_np = attack_np.generate(self.x_test_mnist, mask=mask)\n\n master_seed(1234)\n attack_fw = ProjectedGradientDescent(\n classifier,\n eps=1.0,\n eps_step=0.1,\n max_iter=5,\n norm=np.inf,\n targeted=False,\n num_random_init=1,\n batch_size=3,\n random_eps=True,\n verbose=False,\n )\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_train_mnist.shape[1:]))\n mask = mask.reshape(self.x_train_mnist.shape[1:]).astype(np.float32)\n x_train_adv_fw = attack_fw.generate(self.x_train_mnist, mask=mask)\n\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(self.x_test_mnist.shape[1:]))\n mask = mask.reshape(self.x_test_mnist.shape[1:]).astype(np.float32)\n x_test_adv_fw = attack_fw.generate(self.x_test_mnist, mask=mask)\n\n # Test\n self.assertAlmostEqual(\n np.mean(x_train_adv_np - self.x_train_mnist), np.mean(x_train_adv_fw - self.x_train_mnist), places=6\n )\n self.assertAlmostEqual(\n np.mean(x_test_adv_np - self.x_test_mnist), np.mean(x_test_adv_fw - self.x_test_mnist), places=6\n )\n\n def test_check_params_pt(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(TypeError):\n _ = ProjectedGradientDescent(ptc, eps=np.array([1, 1, 1]), eps_step=1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, norm=0)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, eps=-1, eps_step=1)\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, eps=np.array([-1, -1, -1]), eps_step=np.array([1, 1, 1]))\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, eps=1, eps_step=-1)\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, eps=np.array([1, 1, 1]), eps_step=np.array([-1, -1, -1]))\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, targeted=\"true\")\n\n with self.assertRaises(TypeError):\n _ = ProjectedGradientDescent(ptc, num_random_init=1.0)\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, num_random_init=-1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = ProjectedGradientDescent(ptc, verbose=\"true\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_saliency_map.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.saliency_map import SaliencyMapMethod\nfrom art.estimators.classification.classifier import ClassGradientsMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom art.utils import get_labels_np_array, to_categorical\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestSaliencyMap(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 2\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_9_keras_mnist(self):\n x_test_original = self.x_test_mnist.copy()\n\n # Keras classifier\n classifier = get_image_classifier_kr()\n\n scores = classifier._model.evaluate(self.x_train_mnist, self.y_train_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on training set: %.2f%%\", (scores[1] * 100))\n\n scores = classifier._model.evaluate(self.x_test_mnist, self.y_test_mnist)\n logger.info(\"[Keras, MNIST] Accuracy on test set: %.2f%%\", (scores[1] * 100))\n\n # targeted\n\n # Generate random target classes\n nb_classes = np.unique(np.argmax(self.y_test_mnist, axis=1)).shape[0]\n targets = np.random.randint(nb_classes, size=self.n_test)\n while (targets == np.argmax(self.y_test_mnist, axis=1)).any():\n targets = np.random.randint(nb_classes, size=self.n_test)\n\n # Perform attack\n df = SaliencyMapMethod(classifier, theta=1, batch_size=100, verbose=False)\n x_test_adv = df.generate(self.x_test_mnist, y=to_categorical(targets, nb_classes))\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((self.y_test_mnist == y_pred).all())\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # untargeted\n df = SaliencyMapMethod(classifier, theta=1, batch_size=100, verbose=False)\n x_test_adv = df.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((self.y_test_mnist == y_pred).all())\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_3_tensorflow_mnist(self):\n x_test_original = self.x_test_mnist.copy()\n\n # Create basic CNN on MNIST using TensorFlow\n classifier, sess = get_image_classifier_tf()\n\n scores = get_labels_np_array(classifier.predict(self.x_train_mnist))\n accuracy = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.n_train\n logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", (accuracy * 100))\n\n scores = get_labels_np_array(classifier.predict(self.x_test_mnist))\n accuracy = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_train\n logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", (accuracy * 100))\n\n # targeted\n # Generate random target classes\n nb_classes = np.unique(np.argmax(self.y_test_mnist, axis=1)).shape[0]\n targets = np.random.randint(nb_classes, size=self.n_test)\n while (targets == np.argmax(self.y_test_mnist, axis=1)).any():\n targets = np.random.randint(nb_classes, size=self.n_test)\n\n # Perform attack\n df = SaliencyMapMethod(classifier, theta=1, batch_size=100, verbose=False)\n x_test_adv = df.generate(self.x_test_mnist, y=to_categorical(targets, nb_classes))\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((self.y_test_mnist == y_pred).all())\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # untargeted\n df = SaliencyMapMethod(classifier, theta=1, batch_size=100, verbose=False)\n x_test_adv = df.generate(self.x_test_mnist)\n\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((self.y_test_mnist == y_pred).all())\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_5_pytorch_mnist(self):\n x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n x_test_original = x_test_mnist.copy()\n\n # Create basic PyTorch model\n classifier = get_image_classifier_pt()\n\n scores = get_labels_np_array(classifier.predict(x_train_mnist))\n accuracy = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.n_train\n logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", (accuracy * 100))\n\n scores = get_labels_np_array(classifier.predict(x_test_mnist))\n accuracy = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"\\n[PyTorch, MNIST] Accuracy on test set: %.2f%%\", (accuracy * 100))\n\n # targeted\n # Generate random target classes\n nb_classes = np.unique(np.argmax(self.y_test_mnist, axis=1)).shape[0]\n targets = np.random.randint(nb_classes, size=self.n_test)\n while (targets == np.argmax(self.y_test_mnist, axis=1)).any():\n targets = np.random.randint(nb_classes, size=self.n_test)\n\n # Perform attack\n df = SaliencyMapMethod(classifier, theta=1, batch_size=100, verbose=False)\n x_test_mnist_adv = df.generate(x_test_mnist, y=to_categorical(targets, nb_classes))\n\n self.assertFalse((x_test_mnist == x_test_mnist_adv).all())\n self.assertFalse((0.0 == x_test_mnist_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_mnist_adv))\n self.assertFalse((self.y_test_mnist == y_pred).all())\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # untargeted\n df = SaliencyMapMethod(classifier, theta=1, batch_size=100, verbose=False)\n x_test_mnist_adv = df.generate(x_test_mnist)\n\n self.assertFalse((x_test_mnist == x_test_mnist_adv).all())\n self.assertFalse((0.0 == x_test_mnist_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_mnist_adv))\n self.assertFalse((self.y_test_mnist == y_pred).all())\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test_mnist))), 0.0, delta=0.00001)\n\n def test_7_keras_iris_vector_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n attack = SaliencyMapMethod(classifier, theta=1, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n accuracy = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with JSMA adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_8_keras_iris_vector_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = SaliencyMapMethod(classifier, theta=1, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n\n def test_2_tensorflow_iris_vector(self):\n classifier, _ = get_tabular_classifier_tf()\n\n attack = SaliencyMapMethod(classifier, theta=1, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n accuracy = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with JSMA adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_4_pytorch_iris_vector(self):\n classifier = get_tabular_classifier_pt()\n\n attack = SaliencyMapMethod(classifier, theta=1, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n accuracy = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with JSMA adversarial examples: %.2f%%\", (accuracy * 100))\n\n def test_6_scikitlearn(self):\n from sklearn.linear_model import LogisticRegression\n from sklearn.svm import SVC, LinearSVC\n\n from art.estimators.classification.scikitlearn import SklearnClassifier\n\n scikitlearn_test_cases = [\n LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n SVC(gamma=\"auto\"),\n LinearSVC(),\n ]\n\n x_test_original = self.x_test_iris.copy()\n\n for model in scikitlearn_test_cases:\n classifier = SklearnClassifier(model=model, clip_values=(0, 1))\n classifier.fit(x=self.x_test_iris, y=self.y_test_iris)\n\n attack = SaliencyMapMethod(classifier, theta=1, batch_size=128, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n accuracy = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\n \"Accuracy of \" + classifier.__class__.__name__ + \" on Iris with JSMA adversarial examples: \" \"%.2f%%\",\n (accuracy * 100),\n )\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_iris))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = SaliencyMapMethod(ptc, gamma=-1)\n\n with self.assertRaises(ValueError):\n _ = SaliencyMapMethod(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = SaliencyMapMethod(ptc, verbose=\"False\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(SaliencyMapMethod, [BaseEstimator, ClassGradientsMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_simba.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.simba import SimBA\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import get_labels_np_array\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr, get_image_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestSimBA(TestBase):\n \"\"\"\n A unittest class for testing the Simple Black-box Adversarial Attacks (SimBA).\n\n This module tests SimBA.\n\n | Paper link: https://arxiv.org/abs/1905.07121\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_test = 2\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_5_keras_mnist(self):\n \"\"\"\n Test with the KerasClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n classifier = get_image_classifier_kr()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, False)\n\n def test_2_tensorflow_mnist(self):\n \"\"\"\n Test with the TensorFlowClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n classifier, sess = get_image_classifier_tf()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, False)\n\n def test_3_pytorch_mnist(self):\n \"\"\"\n Test with the PyTorchClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n classifier = get_image_classifier_pt()\n self._test_attack(classifier, x_test, self.y_test_mnist, False)\n\n def test_6_keras_mnist_targeted(self):\n \"\"\"\n Test with the KerasClassifier. (Targeted Attack)\n :return:\n \"\"\"\n classifier = get_image_classifier_kr()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, True)\n\n def test_2_tensorflow_mnist_targeted(self):\n \"\"\"\n Test with the TensorFlowClassifier. (Targeted Attack)\n :return:\n \"\"\"\n classifier, sess = get_image_classifier_tf()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, True)\n\n def test_4_pytorch_mnist_targeted(self):\n \"\"\"\n Test with the PyTorchClassifier. (Targeted Attack)\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n classifier = get_image_classifier_pt()\n self._test_attack(classifier, x_test, self.y_test_mnist, True)\n\n def _test_attack(self, classifier, x_test, y_test, targeted):\n \"\"\"\n Test with SimBA\n :return:\n \"\"\"\n x_test_original = x_test.copy()\n\n # set the targeted label\n if targeted:\n y_target = np.zeros(10)\n y_target[8] = 1.0\n\n #######\n # dct #\n #######\n\n df = SimBA(classifier, attack=\"dct\", targeted=targeted)\n\n x_i = x_test_original[0][None, ...]\n if targeted:\n x_test_adv = df.generate(x_i, y=y_target.reshape(1, 10))\n else:\n x_test_adv = df.generate(x_i)\n\n for i in range(1, len(x_test_original)):\n x_i = x_test_original[i][None, ...]\n if targeted:\n tmp_x_test_adv = df.generate(x_i, y=y_target.reshape(1, 10))\n x_test_adv = np.concatenate([x_test_adv, tmp_x_test_adv])\n else:\n tmp_x_test_adv = df.generate(x_i)\n x_test_adv = np.concatenate([x_test_adv, tmp_x_test_adv])\n\n self.assertFalse((x_test == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n ######\n # px #\n ######\n df_px = SimBA(classifier, attack=\"px\", targeted=targeted)\n\n x_i = x_test_original[0][None, ...]\n if targeted:\n x_test_adv = df_px.generate(x_i, y=y_target.reshape(1, 10))\n else:\n x_test_adv = df_px.generate(x_i)\n\n for i in range(1, len(x_test_original)):\n x_i = x_test_original[i][None, ...]\n if targeted:\n tmp_x_test_adv = df_px.generate(x_i, y=y_target.reshape(1, 10))\n x_test_adv = np.concatenate([x_test_adv, tmp_x_test_adv])\n else:\n tmp_x_test_adv = df_px.generate(x_i)\n x_test_adv = np.concatenate([x_test_adv, tmp_x_test_adv])\n\n self.assertFalse((x_test == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n #############\n # px - diag #\n #############\n df_px = SimBA(classifier, attack=\"px\", targeted=targeted, order=\"diag\")\n\n x_i = x_test_original[0][None, ...]\n if targeted:\n x_test_adv = df_px.generate(x_i, y=y_target.reshape(1, 10))\n else:\n x_test_adv = df_px.generate(x_i)\n\n for i in range(1, len(x_test_original)):\n x_i = x_test_original[i][None, ...]\n if targeted:\n tmp_x_test_adv = df_px.generate(x_i, y=y_target.reshape(1, 10))\n x_test_adv = np.concatenate([x_test_adv, tmp_x_test_adv])\n else:\n tmp_x_test_adv = df_px.generate(x_i)\n x_test_adv = np.concatenate([x_test_adv, tmp_x_test_adv])\n\n self.assertFalse((x_test == x_test_adv).all())\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, max_iter=1.0)\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, epsilon=-1)\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, batch_size=2)\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, stride=1.0)\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, stride=-1)\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, freq_dim=1.0)\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, freq_dim=-1)\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, order=\"test\")\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, attack=\"test\")\n\n with self.assertRaises(ValueError):\n _ = SimBA(ptc, targeted=\"test\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(SimBA, (BaseEstimator, ClassifierMixin, NeuralNetworkMixin))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_spatial_transformation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion.spatial_transformation import SpatialTransformation\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr\nfrom tests.utils import get_image_classifier_pt, get_tabular_classifier_kr\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestSpatialTransformation(TestBase):\n \"\"\"\n A unittest class for testing Spatial attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_2_tensorflow_classifier(self):\n \"\"\"\n First test with the TensorFlowV2Classifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowV2Classifier\n tfc, sess = get_image_classifier_tf()\n\n # Attack\n attack_st = SpatialTransformation(\n tfc, max_translation=10.0, num_translations=3, max_rotation=30.0, num_rotations=3, verbose=False\n )\n x_train_adv = attack_st.generate(self.x_train_mnist)\n\n self.assertAlmostEqual(x_train_adv[0, 8, 13, 0], 0.49004024, delta=0.01)\n self.assertAlmostEqual(attack_st.fooling_rate, 0.71, delta=0.02)\n\n self.assertEqual(attack_st.attack_trans_x, 3)\n self.assertEqual(attack_st.attack_trans_y, 3)\n self.assertEqual(attack_st.attack_rot, 30.0)\n\n x_test_adv = attack_st.generate(self.x_test_mnist)\n\n self.assertAlmostEqual(x_test_adv[0, 14, 14, 0], 0.013572651, delta=0.01)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n if sess is not None:\n sess.close()\n\n def test_4_keras_classifier(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # Attack\n attack_st = SpatialTransformation(\n krc, max_translation=10.0, num_translations=3, max_rotation=30.0, num_rotations=3, verbose=False\n )\n x_train_adv = attack_st.generate(self.x_train_mnist)\n\n self.assertAlmostEqual(x_train_adv[0, 8, 13, 0], 0.49004024, delta=0.01)\n self.assertAlmostEqual(attack_st.fooling_rate, 0.71, delta=0.02)\n\n self.assertEqual(attack_st.attack_trans_x, 3)\n self.assertEqual(attack_st.attack_trans_y, 3)\n self.assertEqual(attack_st.attack_rot, 30.0)\n\n x_test_adv = attack_st.generate(self.x_test_mnist)\n\n self.assertAlmostEqual(x_test_adv[0, 14, 14, 0], 0.013572651, delta=0.01)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n k.clear_session()\n\n def test_3_pytorch_classifier(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n x_test_mnist = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n x_test_original = x_test_mnist.copy()\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt(from_logits=True)\n\n # Attack\n attack_st = SpatialTransformation(\n ptc, max_translation=10.0, num_translations=3, max_rotation=30.0, num_rotations=3, verbose=False\n )\n x_train__mnistadv = attack_st.generate(x_train_mnist)\n\n self.assertAlmostEqual(x_train__mnistadv[0, 0, 13, 18], 0.627451, delta=0.01)\n self.assertAlmostEqual(attack_st.fooling_rate, 0.57, delta=0.03)\n\n self.assertEqual(attack_st.attack_trans_x, 0)\n self.assertEqual(attack_st.attack_trans_y, 3)\n self.assertEqual(attack_st.attack_rot, 0.0)\n\n x_test_adv = attack_st.generate(x_test_mnist)\n\n self.assertLessEqual(abs(x_test_adv[0, 0, 14, 14] - 0.008591662), 0.01)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test_mnist))), 0.0, delta=0.00001)\n\n def test_5_failure_feature_vectors(self):\n attack_params = {\"max_translation\": 10.0, \"num_translations\": 3, \"max_rotation\": 30.0, \"num_rotations\": 3}\n classifier = get_tabular_classifier_kr()\n attack = SpatialTransformation(classifier=classifier, verbose=False)\n attack.set_params(**attack_params)\n data = np.random.rand(10, 4)\n\n # Assert that value error is raised for feature vectors\n with self.assertRaises(ValueError) as context:\n attack.generate(data)\n\n self.assertIn(\"Feature vectors detected.\", str(context.exception))\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = SpatialTransformation(ptc, max_translation=-1)\n\n with self.assertRaises(ValueError):\n _ = SpatialTransformation(ptc, num_translations=-1)\n\n with self.assertRaises(ValueError):\n _ = SpatialTransformation(ptc, max_rotation=-1)\n\n with self.assertRaises(ValueError):\n _ = SpatialTransformation(ptc, verbose=\"False\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(SpatialTransformation, [BaseEstimator, NeuralNetworkMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_steal_now_attack_later.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import SNAL\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_generate(art_warning, get_pytorch_detector_yolo):\n try:\n import glob\n from io import BytesIO\n import os\n from PIL import Image\n import requests\n import time\n import torch\n from torchvision import transforms\n from torchvision.datasets.vision import VisionDataset\n\n object_detector = get_pytorch_detector_yolo\n object_detector.set_params(input_shape=(3, 640, 640))\n\n # Define a custom function to collect patches from images\n def collect_patches_from_images(detector, imgs):\n bs = imgs.shape[0]\n pred = detector.predict(x=imgs)\n y = []\n for obj in pred:\n y.append(obj[\"boxes\"])\n\n candidates_patch = []\n candidates_position = []\n for i in range(bs):\n patch = []\n if y[i].shape[0] == 0:\n candidates_patch.append(patch)\n candidates_position.append(torch.zeros((0, 4), device=object_detector.device))\n continue\n\n pos_matrix = torch.from_numpy(y[i][:, :4]).int()\n pos_matrix[:, 0] = torch.clamp_min(pos_matrix[:, 0], 0)\n pos_matrix[:, 1] = torch.clamp_min(pos_matrix[:, 1], 0)\n pos_matrix[:, 2] = torch.clamp_max(pos_matrix[:, 2], imgs.shape[3])\n pos_matrix[:, 3] = torch.clamp_max(pos_matrix[:, 3], imgs.shape[2])\n for pos_m in pos_matrix:\n if pos_m[3] - pos_m[1] == 0 or pos_m[2] - pos_m[0] == 0:\n continue\n p = imgs[i, :, pos_m[1] : pos_m[3], pos_m[0] : pos_m[2]]\n patch.append(p.to(detector.device))\n\n candidates_patch.append(patch)\n candidates_position.append(pos_matrix)\n\n return candidates_patch, candidates_position\n\n # Download a sample image\n target = \"https://farm2.staticflickr.com/1065/705706084_39a7f28fc9_z.jpg\" # val2017/000000552842.jpg\n headers = {\"User-Agent\": \"Mozilla/5.0\", \"Referer\": \"https://www.flickr.com/\"}\n response = requests.get(target, headers=headers)\n org_img = np.asarray(Image.open(BytesIO(response.content)).resize((640, 640)))\n x = np.stack([org_img.transpose((2, 0, 1)) / 255.0], axis=0).astype(np.float32)\n\n # Prepare dataset\n # Select images randomly from COCO dataset\n list_url = [\n \"http://farm4.staticflickr.com/3572/5744200926_082c11c43c_z.jpg\", # 000000460229\n \"http://farm4.staticflickr.com/3010/2749181045_ed450e5d36_z.jpg\", # 000000057760\n \"http://farm4.staticflickr.com/3826/9451771633_f14cef3a8b_z.jpg\", # 000000468332\n \"http://farm7.staticflickr.com/6194/6106161903_e505cbc192_z.jpg\", # 000000190841\n \"http://farm1.staticflickr.com/48/140268688_947e2bcc96_z.jpg\", # 000000078420\n \"http://farm6.staticflickr.com/5011/5389083366_fdf13f2ee6_z.jpg\", # 000000309655\n \"http://farm4.staticflickr.com/3552/5812461870_eb24c8eac5_z.jpg\", # 000000293324\n \"http://farm4.staticflickr.com/3610/3361019695_1005dd49fd_z.jpg\", # 000000473821\n \"http://farm8.staticflickr.com/7323/9725958435_3359641442_z.jpg\", # 000000025386\n \"http://farm4.staticflickr.com/3317/3427794620_9db24fe462_z.jpg\", # 000000347693\n \"http://farm6.staticflickr.com/5143/5589997131_22f51b308c_z.jpg\", # 000000058029\n \"http://farm5.staticflickr.com/4061/4376326145_7ef66603e3_z.jpg\", # 000000389933\n \"http://farm3.staticflickr.com/2028/2188480725_5fbf27a5b3_z.jpg\", # 000000311789\n \"http://farm1.staticflickr.com/172/421715600_666b0f6a2b_z.jpg\", # 000000506004\n \"http://farm9.staticflickr.com/8331/8100320407_6044d243a5_z.jpg\", # 000000076648\n \"http://farm4.staticflickr.com/3236/2487649513_1ef6a6d5c9_z.jpg\", # 000000201646\n \"http://farm4.staticflickr.com/3094/2684280938_a5b59c0fac_z.jpg\", # 000000447187\n \"http://farm1.staticflickr.com/42/100911501_005e4d3aa8_z.jpg\", # 000000126107\n \"http://farm1.staticflickr.com/56/147795701_40d7bc8331_z.jpg\", # 000000505942\n \"http://farm5.staticflickr.com/4103/5074895283_71a73d77e5_z.jpg\", # 000000360951\n \"http://farm1.staticflickr.com/160/404335548_3bdc1f2ed9_z.jpg\", # 000000489764\n \"http://farm9.staticflickr.com/8446/7857456044_401a257790_z.jpg\", # 000000407574\n ]\n\n root_mscoco = \"datasets\"\n os.makedirs(root_mscoco, exist_ok=True)\n for idx, img_url in enumerate(list_url):\n response = requests.get(img_url, headers=headers)\n with open(f\"{root_mscoco}/{idx:03d}.jpg\", \"wb\") as f:\n f.write(response.content)\n time.sleep(0.5)\n\n # Collect patches\n\n class CustomDatasetFolder(VisionDataset):\n def __init__(self, root, transform=None):\n super(CustomDatasetFolder, self).__init__(root)\n self.transform = transform\n samples = glob.glob(f\"{root}/*.jpg\")\n\n self.samples = samples\n\n def __getitem__(self, index):\n sample = self._loader(self.samples[index])\n if self.transform is not None:\n sample = self.transform(sample)\n return sample\n\n def __len__(self):\n return len(self.samples)\n\n @staticmethod\n def _loader(path):\n return Image.open(path).convert(\"RGB\")\n\n img_dataset = CustomDatasetFolder(\n root_mscoco,\n transforms.Compose(\n [\n transforms.RandomResizedCrop((640, 640)),\n transforms.AutoAugment(),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ]\n ),\n )\n img_loader = torch.utils.data.DataLoader(img_dataset, batch_size=1, shuffle=True)\n\n candidates_list = []\n max_imgs = 25\n img_count = 0\n for x_i in iter(img_loader):\n img_count = img_count + 1\n if img_count == max_imgs:\n break\n\n candidates, _ = collect_patches_from_images(object_detector, x_i.to(object_detector.device))\n candidates_list = candidates_list + candidates[0]\n\n attack = SNAL(\n object_detector,\n eps=16.0 / 255.0,\n max_iter=5,\n num_grid=10,\n candidates=candidates_list,\n collector=collect_patches_from_images,\n )\n\n x_adv = attack.generate(x=x)\n assert x.shape == x_adv.shape\n assert np.min(x_adv) >= 0.0\n assert np.max(x_adv) <= 1.0\n\n y_pred_adv = object_detector.predict(x=x_adv)\n assert y_pred_adv[0][\"boxes\"].shape[0] == 25200\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning, get_pytorch_detector_yolo):\n try:\n import torch\n import requests\n\n object_detector = get_pytorch_detector_yolo\n object_detector.set_params(input_shape=(3, 640, 640))\n\n def dummy_func(model, imags):\n candidates_patch = []\n candidates_position = []\n return candidates_patch, candidates_position\n\n dummy_list = [[], []]\n\n with pytest.raises(ValueError):\n _ = SNAL(\n estimator=object_detector,\n eps=-1.0,\n max_iter=5,\n num_grid=10,\n candidates=dummy_list,\n collector=dummy_func,\n )\n with pytest.raises(ValueError):\n _ = SNAL(\n estimator=object_detector, eps=2.0, max_iter=5, num_grid=10, candidates=dummy_list, collector=dummy_func\n )\n with pytest.raises(TypeError):\n _ = SNAL(\n estimator=object_detector,\n eps=8 / 255.0,\n max_iter=1.0,\n num_grid=10,\n candidates=dummy_list,\n collector=dummy_func,\n )\n with pytest.raises(ValueError):\n _ = SNAL(\n estimator=object_detector,\n eps=8 / 255.0,\n max_iter=0,\n num_grid=10,\n candidates=dummy_list,\n collector=dummy_func,\n )\n with pytest.raises(TypeError):\n _ = SNAL(\n estimator=object_detector,\n eps=8 / 255.0,\n max_iter=5,\n num_grid=1.0,\n candidates=dummy_list,\n collector=dummy_func,\n )\n with pytest.raises(ValueError):\n _ = SNAL(\n estimator=object_detector,\n eps=8 / 255.0,\n max_iter=5,\n num_grid=0,\n candidates=dummy_list,\n collector=dummy_func,\n )\n with pytest.raises(TypeError):\n _ = SNAL(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=10, candidates=1.0, collector=dummy_func\n )\n with pytest.raises(ValueError):\n _ = SNAL(\n estimator=object_detector, eps=8 / 255.0, max_iter=5, num_grid=10, candidates=[], collector=dummy_func\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_targeted_universal_perturbation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.targeted_universal_perturbation import TargetedUniversalPerturbation\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.estimator import BaseEstimator\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestTargetedUniversalPerturbation(TestBase):\n \"\"\"\n A unittest class for testing the TargetedUniversalPerturbation attack.\n\n This module tests the Targeted Universal Perturbation.\n\n | Paper link: https://arxiv.org/abs/1911.06502\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 500\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_2_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # set target label\n target = 0\n y_target = np.zeros([len(self.x_train_mnist), 10])\n for i in range(len(self.x_train_mnist)):\n y_target[i, target] = 1.0\n\n # Attack\n up = TargetedUniversalPerturbation(\n tfc,\n max_iter=1,\n attacker=\"fgsm\",\n attacker_params={\n \"eps\": 0.3,\n \"targeted\": True,\n },\n )\n x_train_adv = up.generate(self.x_train_mnist, y=y_target)\n self.assertTrue((up.fooling_rate >= 0.2) or not up.converged)\n\n x_test_adv = self.x_test_mnist + up.noise\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n train_y_pred = np.argmax(tfc.predict(x_train_adv), axis=1)\n test_y_pred = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_mnist, axis=1) == test_y_pred).all())\n self.assertFalse((np.argmax(self.y_train_mnist, axis=1) == train_y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_4_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # set target label\n target = 0\n y_target = np.zeros([len(self.x_train_mnist), 10])\n for i in range(len(self.x_train_mnist)):\n y_target[i, target] = 1.0\n\n # Attack\n up = TargetedUniversalPerturbation(\n krc,\n max_iter=1,\n attacker=\"fgsm\",\n attacker_params={\n \"eps\": 0.3,\n \"targeted\": True,\n },\n )\n x_train_adv = up.generate(self.x_train_mnist, y=y_target)\n self.assertTrue((up.fooling_rate >= 0.2) or not up.converged)\n\n x_test_adv = self.x_test_mnist + up.noise\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n train_y_pred = np.argmax(krc.predict(x_train_adv), axis=1)\n test_y_pred = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_mnist, axis=1) == test_y_pred).all())\n self.assertFalse((np.argmax(self.y_train_mnist, axis=1) == train_y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_3_pytorch_mnist(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n x_test_original = x_test_mnist.copy()\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt()\n\n # set target label\n target = 0\n y_target = np.zeros([len(self.x_train_mnist), 10])\n for i in range(len(self.x_train_mnist)):\n y_target[i, target] = 1.0\n\n # Attack\n up = TargetedUniversalPerturbation(\n ptc,\n max_iter=1,\n attacker=\"fgsm\",\n attacker_params={\n \"eps\": 0.3,\n \"targeted\": True,\n },\n )\n x_train_mnist_adv = up.generate(x_train_mnist, y=y_target)\n self.assertTrue((up.fooling_rate >= 0.2) or not up.converged)\n\n x_test_mnist_adv = x_test_mnist + up.noise\n self.assertFalse((x_test_mnist == x_test_mnist_adv).all())\n\n train_y_pred = np.argmax(ptc.predict(x_train_mnist_adv), axis=1)\n test_y_pred = np.argmax(ptc.predict(x_test_mnist_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_mnist, axis=1) == test_y_pred).all())\n self.assertFalse((np.argmax(self.y_train_mnist, axis=1) == train_y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test_mnist))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = TargetedUniversalPerturbation(ptc, delta=-1)\n\n with self.assertRaises(ValueError):\n _ = TargetedUniversalPerturbation(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = TargetedUniversalPerturbation(ptc, eps=-1)\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(TargetedUniversalPerturbation, (BaseEstimator, ClassifierMixin))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_threshold_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module tests the Threshold Attack.\n\n| Paper link:\n https://arxiv.org/abs/1906.06026\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.pixel_threshold import ThresholdAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import get_labels_np_array\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr, get_image_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestThresholdAttack(TestBase):\n \"\"\"\n A unittest class for testing the Threshold Attack.\n\n This module tests the Threshold Attack.\n\n | Paper link:\n https://arxiv.org/abs/1906.06026\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_test = 2\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_6_keras_mnist(self):\n \"\"\"\n Test with the KerasClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n classifier = get_image_classifier_kr()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, False)\n\n def test_2_tensorflow_mnist(self):\n \"\"\"\n Test with the TensorFlowClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n classifier, sess = get_image_classifier_tf()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, False)\n\n def test_4_pytorch_mnist(self):\n \"\"\"\n Test with the PyTorchClassifier. (Untargeted Attack)\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n classifier = get_image_classifier_pt()\n self._test_attack(classifier, x_test, self.y_test_mnist, False)\n\n def test_7_keras_mnist_targeted(self):\n \"\"\"\n Test with the KerasClassifier. (Targeted Attack)\n :return:\n \"\"\"\n classifier = get_image_classifier_kr()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, True)\n\n def test_3_tensorflow_mnist_targeted(self):\n \"\"\"\n Test with the TensorFlowClassifier. (Targeted Attack)\n :return:\n \"\"\"\n classifier, sess = get_image_classifier_tf()\n self._test_attack(classifier, self.x_test_mnist, self.y_test_mnist, True)\n\n def test_5_pytorch_mnist_targeted(self):\n \"\"\"\n Test with the PyTorchClassifier. (Targeted Attack)\n :return:\n \"\"\"\n x_test = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n classifier = get_image_classifier_pt()\n self._test_attack(classifier, x_test, self.y_test_mnist, True)\n\n def _test_attack(self, classifier, x_test, y_test, targeted):\n \"\"\"\n Test with the Threshold Attack\n :return:\n \"\"\"\n x_test_original = x_test.copy()\n\n if targeted:\n # Generate random target classes\n class_y_test = np.argmax(y_test, axis=1)\n nb_classes = np.unique(class_y_test).shape[0]\n np.random.seed(seed=487)\n targets = np.random.randint(nb_classes, size=self.n_test)\n for i in range(self.n_test):\n if class_y_test[i] == targets[i]:\n targets[i] -= 1\n else:\n targets = y_test\n\n for es in [1]: # Option 0 is not easy to reproduce reliably, we should consider it at a later time\n df = ThresholdAttack(classifier, th=128, es=es, max_iter=10, targeted=targeted, verbose=False)\n x_test_adv = df.generate(x_test_original, targets)\n\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, x_test, x_test_adv)\n self.assertFalse((0.0 == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n accuracy = np.sum(np.argmax(y_pred, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.n_test\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (accuracy * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(ThresholdAttack, [BaseEstimator, NeuralNetworkMixin, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_universal_perturbation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.universal_perturbation import UniversalPerturbation\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import (\n TestBase,\n get_image_classifier_kr,\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_tabular_classifier_kr,\n get_tabular_classifier_pt,\n get_tabular_classifier_tf,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestUniversalPerturbation(TestBase):\n \"\"\"\n A unittest class for testing the UniversalPerturbation attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 500\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_3_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # Attack\n up = UniversalPerturbation(\n tfc, max_iter=1, attacker=\"newtonfool\", attacker_params={\"max_iter\": 5, \"verbose\": False}, verbose=False\n )\n x_train_adv = up.generate(self.x_train_mnist)\n self.assertTrue((up.fooling_rate >= 0.2) or not up.converged)\n\n x_test_adv = self.x_test_mnist + up.noise\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n train_y_pred = np.argmax(tfc.predict(x_train_adv), axis=1)\n test_y_pred = np.argmax(tfc.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_mnist, axis=1) == test_y_pred).all())\n self.assertFalse((np.argmax(self.y_train_mnist, axis=1) == train_y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_8_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # Attack\n up = UniversalPerturbation(\n krc,\n max_iter=1,\n attacker=\"ead\",\n attacker_params={\"max_iter\": 2, \"targeted\": False, \"verbose\": False},\n verbose=False,\n )\n x_train_adv = up.generate(self.x_train_mnist)\n self.assertTrue((up.fooling_rate >= 0.2) or not up.converged)\n\n x_test_adv = self.x_test_mnist + up.noise\n self.assertFalse((self.x_test_mnist == x_test_adv).all())\n\n train_y_pred = np.argmax(krc.predict(x_train_adv), axis=1)\n test_y_pred = np.argmax(krc.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_mnist, axis=1) == test_y_pred).all())\n self.assertFalse((np.argmax(self.y_train_mnist, axis=1) == train_y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n def test_5_pytorch_mnist(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n x_test_original = x_test_mnist.copy()\n\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt()\n\n # Attack\n up = UniversalPerturbation(\n ptc, max_iter=1, attacker=\"newtonfool\", attacker_params={\"max_iter\": 5, \"verbose\": False}, verbose=False\n )\n x_train_mnist_adv = up.generate(x_train_mnist)\n self.assertTrue((up.fooling_rate >= 0.2) or not up.converged)\n\n x_test_mnist_adv = x_test_mnist + up.noise\n self.assertFalse((x_test_mnist == x_test_mnist_adv).all())\n\n train_y_pred = np.argmax(ptc.predict(x_train_mnist_adv), axis=1)\n test_y_pred = np.argmax(ptc.predict(x_test_mnist_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_mnist, axis=1) == test_y_pred).all())\n self.assertFalse((np.argmax(self.y_train_mnist, axis=1) == train_y_pred).all())\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test_mnist))), 0.0, delta=0.00001)\n\n def test_6_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n # Test untargeted attack\n attack_params = {\"max_iter\": 1, \"attacker\": \"newtonfool\", \"attacker_params\": {\"max_iter\": 5, \"verbose\": False}}\n attack = UniversalPerturbation(classifier, verbose=False)\n attack.set_params(**attack_params)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with universal adversarial examples: %.2f%%\", (acc * 100))\n\n def test_7_keras_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack_params = {\"max_iter\": 1, \"attacker\": \"newtonfool\", \"attacker_params\": {\"max_iter\": 5, \"verbose\": False}}\n attack = UniversalPerturbation(classifier, verbose=False)\n attack.set_params(**attack_params)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with universal adversarial examples: %.2f%%\", (acc * 100))\n\n def test_2_tensorflow_iris(self):\n classifier, _ = get_tabular_classifier_tf()\n\n # Test untargeted attack\n attack_params = {\n \"max_iter\": 1,\n \"attacker\": \"ead\",\n \"attacker_params\": {\"max_iter\": 5, \"targeted\": False, \"verbose\": False},\n }\n attack = UniversalPerturbation(classifier, verbose=False)\n attack.set_params(**attack_params)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with universal adversarial examples: %.2f%%\", (acc * 100))\n\n def test_4_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n\n attack_params = {\n \"max_iter\": 1,\n \"attacker\": \"ead\",\n \"attacker_params\": {\"max_iter\": 5, \"targeted\": False, \"verbose\": False},\n }\n attack = UniversalPerturbation(classifier, verbose=False)\n attack.set_params(**attack_params)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with universal adversarial examples: %.2f%%\", (acc * 100))\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = UniversalPerturbation(ptc, delta=-1)\n\n with self.assertRaises(ValueError):\n _ = UniversalPerturbation(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = UniversalPerturbation(ptc, eps=-1)\n\n with self.assertRaises(ValueError):\n _ = UniversalPerturbation(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = UniversalPerturbation(ptc, verbose=\"False\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(UniversalPerturbation, [BaseEstimator, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_virtual_adversarial.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\nimport numpy as np\n\nfrom art.attacks.evasion.virtual_adversarial import VirtualAdversarialMethod\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import get_labels_np_array\n\nfrom tests.utils import TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_kr, get_image_classifier_pt\nfrom tests.utils import get_tabular_classifier_tf, get_tabular_classifier_kr, get_tabular_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestVirtualAdversarial(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 100\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_8_keras_mnist(self):\n classifier = get_image_classifier_kr()\n\n scores = classifier._model.evaluate(self.x_train_mnist, self.y_train_mnist)\n logging.info(\"[Keras, MNIST] Accuracy on training set: %.2f%%\", (scores[1] * 100))\n scores = classifier._model.evaluate(self.x_test_mnist, self.y_test_mnist)\n logging.info(\"[Keras, MNIST] Accuracy on test set: %.2f%%\", (scores[1] * 100))\n\n self._test_backend_mnist(classifier, self.x_test_mnist, self.y_test_mnist)\n\n def test_3_tensorflow_mnist(self):\n classifier, sess = get_image_classifier_tf(from_logits=False)\n\n scores = get_labels_np_array(classifier.predict(self.x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", (acc * 100))\n\n scores = get_labels_np_array(classifier.predict(self.x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", (acc * 100))\n\n self._test_backend_mnist(classifier, self.x_test_mnist, self.y_test_mnist)\n\n def test_5_pytorch_mnist(self):\n x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n classifier = get_image_classifier_pt()\n\n scores = get_labels_np_array(classifier.predict(x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", (acc * 100))\n\n scores = get_labels_np_array(classifier.predict(x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on test set: %.2f%%\", (acc * 100))\n\n self._test_backend_mnist(classifier, x_test_mnist, self.y_test_mnist)\n\n def _test_backend_mnist(self, classifier, x_test, y_test):\n x_test_original = x_test.copy()\n\n df = VirtualAdversarialMethod(classifier, batch_size=100, max_iter=2, verbose=False)\n\n x_test_adv = df.generate(x_test)\n\n self.assertFalse((x_test == x_test_adv).all())\n\n y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n self.assertFalse((y_test == y_pred).all())\n\n acc = np.sum(np.argmax(y_pred, axis=1) == np.argmax(y_test, axis=1)) / y_test.shape[0]\n logger.info(\"Accuracy on adversarial examples: %.2f%%\", (acc * 100))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_6_keras_iris_clipped(self):\n classifier = get_tabular_classifier_kr()\n\n # Test untargeted attack\n attack = VirtualAdversarialMethod(classifier, eps=0.1, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv <= 1).all())\n self.assertTrue((x_test_iris_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with VAT adversarial examples: %.2f%%\", (acc * 100))\n\n def test_7_keras_iris_unbounded(self):\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n attack = VirtualAdversarialMethod(classifier, eps=1, verbose=False)\n x_test_iris_adv = attack.generate(self.x_test_iris)\n self.assertFalse((self.x_test_iris == x_test_iris_adv).all())\n self.assertTrue((x_test_iris_adv > 1).any())\n self.assertTrue((x_test_iris_adv < 0).any())\n\n preds_adv = np.argmax(classifier.predict(x_test_iris_adv), axis=1)\n self.assertFalse((np.argmax(self.y_test_iris, axis=1) == preds_adv).all())\n acc = np.sum(preds_adv == np.argmax(self.y_test_iris, axis=1)) / self.y_test_iris.shape[0]\n logger.info(\"Accuracy on Iris with VAT adversarial examples: %.2f%%\", (acc * 100))\n\n # def test_iris_tf(self):\n # classifier, _ = get_iris_classifier_tf()\n #\n # attack = VirtualAdversarialMethod(classifier, eps=.1, verbose=False)\n # x_test_adv = attack.generate(x_test)\n # #print(np.min(x_test_adv), np.max(x_test_adv), np.min(x_test), np.max(x_test))\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(y_test, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(y_test, axis=1)) / y_test.shape[0]\n # logger.info('Accuracy on Iris with VAT adversarial examples: %.2f%%', (acc * 100))\n\n # def test_iris_pt(self):\n # (_, _), (x_test, y_test) = self.iris\n # classifier = get_iris_classifier_pt()\n #\n # attack = VirtualAdversarialMethod(classifier, eps=.1, verbose=False)\n # x_test_adv = attack.generate(x_test.astype(np.float32))\n # #print(np.min(x_test_adv), np.max(x_test_adv), np.min(x_test), np.max(x_test))\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertTrue((x_test_adv <= 1).all())\n # self.assertTrue((x_test_adv >= 0).all())\n #\n # preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n # self.assertFalse((np.argmax(y_test, axis=1) == preds_adv).all())\n # acc = np.sum(preds_adv == np.argmax(y_test, axis=1)) / y_test.shape[0]\n # logger.info('Accuracy on Iris with VAT adversarial examples: %.2f%%', (acc * 100))\n\n def test_2_tensorflow_iris(self):\n classifier, _ = get_tabular_classifier_tf()\n\n attack = VirtualAdversarialMethod(classifier, eps=0.1, verbose=False)\n\n with self.assertRaises(TypeError) as context:\n _ = attack.generate(self.x_test_iris)\n\n self.assertIn(\n \"This attack requires a classifier predicting probabilities in the range [0, 1] as output.\"\n \"Values smaller than 0.0 or larger than 1.0 have been detected.\",\n str(context.exception),\n )\n\n def test_4_pytorch_iris(self):\n classifier = get_tabular_classifier_pt()\n\n attack = VirtualAdversarialMethod(classifier, eps=0.1, verbose=False)\n\n with self.assertRaises(TypeError) as context:\n _ = attack.generate(self.x_test_iris.astype(np.float32))\n\n self.assertIn(\n \"This attack requires a classifier predicting probabilities in the range [0, 1] as output.\"\n \"Values smaller than 0.0 or larger than 1.0 have been detected.\",\n str(context.exception),\n )\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, max_iter=1.0)\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, eps=-1)\n\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, finite_diff=1)\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, finite_diff=-1.0)\n\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = VirtualAdversarialMethod(ptc, verbose=\"true\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(VirtualAdversarialMethod, [BaseEstimator, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_wasserstein.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.wasserstein import Wasserstein\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import get_labels_np_array, random_targets\n\nfrom tests.utils import TestBase, master_seed\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_pt\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestWasserstein(TestBase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.n_train = 10\n cls.n_test = 10\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n # def test_keras_mnist(self):\n # classifier = get_image_classifier_kr()\n #\n # scores = classifier._model.evaluate(self.x_train_mnist, self.y_train_mnist)\n # logger.info(\"[Keras, MNIST] Accuracy on training set: %.2f%%\", scores[1] * 100)\n # scores = classifier._model.evaluate(self.x_test_mnist, self.y_test_mnist)\n # logger.info(\"[Keras, MNIST] Accuracy on test set: %.2f%%\", scores[1] * 100)\n #\n # self._test_backend_mnist(\n # classifier, self.x_train_mnist, self.y_train_mnist, self.x_test_mnist, self.y_test_mnist\n # )\n\n def test_tensorflow_mnist(self):\n classifier, sess = get_image_classifier_tf()\n\n scores = get_labels_np_array(classifier.predict(self.x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on training set: %.2f%%\", acc * 100)\n\n scores = get_labels_np_array(classifier.predict(self.x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[TF, MNIST] Accuracy on test set: %.2f%%\", acc * 100)\n\n self._test_backend_mnist(\n classifier, self.x_train_mnist, self.y_train_mnist, self.x_test_mnist, self.y_test_mnist\n )\n\n def test_pytorch_mnist(self):\n x_train_mnist = np.swapaxes(self.x_train_mnist, 1, 3).astype(np.float32)\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n classifier = get_image_classifier_pt()\n\n scores = get_labels_np_array(classifier.predict(x_train_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_train_mnist, axis=1)) / self.y_train_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on training set: %.2f%%\", acc * 100)\n\n scores = get_labels_np_array(classifier.predict(x_test_mnist))\n acc = np.sum(np.argmax(scores, axis=1) == np.argmax(self.y_test_mnist, axis=1)) / self.y_test_mnist.shape[0]\n logger.info(\"[PyTorch, MNIST] Accuracy on test set: %.2f%%\", acc * 100)\n\n self._test_backend_mnist(classifier, x_train_mnist, self.y_train_mnist, x_test_mnist, self.y_test_mnist)\n\n def _test_backend_mnist(self, classifier, x_train, y_train, x_test, y_test):\n\n base_success_rate = 0.1\n num_iter = 5\n regularization = 100\n batch_size = 5\n eps = 0.3\n\n # Test Wasserstein with wasserstein ball and wasserstein norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"wasserstein\",\n ball=\"wasserstein\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train_adv == x_train).all())\n self.assertFalse((x_test_adv == x_test).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, base_success_rate)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, base_success_rate)\n\n # Test Wasserstein with wasserstein ball and l2 norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"2\",\n ball=\"wasserstein\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, base_success_rate)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, 0)\n\n # Test Wasserstein with wasserstein ball and inf norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"inf\",\n ball=\"wasserstein\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, base_success_rate)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, 0)\n\n # Test Wasserstein with wasserstein ball and l1 norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"1\",\n ball=\"wasserstein\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, base_success_rate)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, 0)\n\n # Test Wasserstein with l2 ball and wasserstein norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"wasserstein\",\n ball=\"2\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.05,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, 0)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, 0)\n\n # Test Wasserstein with l1 ball and wasserstein norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"wasserstein\",\n ball=\"1\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, 0)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, 0)\n\n # Test Wasserstein with inf ball and Wasserstein norm\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"wasserstein\",\n ball=\"inf\",\n targeted=False,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, base_success_rate)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertGreaterEqual(test_success_rate, base_success_rate)\n\n # Test Wasserstein with targeted attack\n master_seed(1234)\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"wasserstein\",\n ball=\"wasserstein\",\n targeted=True,\n p=2,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=5,\n batch_size=batch_size,\n verbose=False,\n )\n\n train_y_rand = random_targets(y_train, nb_classes=10)\n test_y_rand = random_targets(y_test, nb_classes=10)\n\n x_train_adv = attack.generate(x_train, train_y_rand)\n x_test_adv = attack.generate(x_test, test_y_rand)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) == np.argmax(train_y_rand, axis=1)) / y_train.shape[0]\n )\n self.assertGreaterEqual(train_success_rate, base_success_rate)\n\n test_success_rate = np.sum(np.argmax(test_y_pred, axis=1) == np.argmax(test_y_rand, axis=1)) / y_test.shape[0]\n self.assertGreaterEqual(test_success_rate, 0)\n\n # Test Wasserstein with p-wasserstein=1 and kernel_size=3\n attack = Wasserstein(\n classifier,\n regularization=regularization,\n max_iter=num_iter,\n conjugate_sinkhorn_max_iter=num_iter,\n projected_sinkhorn_max_iter=num_iter,\n norm=\"wasserstein\",\n ball=\"wasserstein\",\n targeted=False,\n p=1,\n eps_iter=2,\n eps_factor=1.05,\n eps=eps,\n eps_step=0.1,\n kernel_size=3,\n batch_size=batch_size,\n verbose=False,\n )\n\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv)).astype(float)\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv)).astype(float)\n\n train_success_rate = (\n np.sum(np.argmax(train_y_pred, axis=1) != np.argmax(classifier.predict(x_train), axis=1)) / y_train.shape[0]\n )\n self.assertTrue(train_success_rate >= base_success_rate)\n\n test_success_rate = (\n np.sum(np.argmax(test_y_pred, axis=1) != np.argmax(classifier.predict(x_test), axis=1)) / y_test.shape[0]\n )\n self.assertTrue(test_success_rate >= base_success_rate)\n\n def test_unsquared_images(self):\n from art.estimators.estimator import (\n BaseEstimator,\n LossGradientsMixin,\n NeuralNetworkMixin,\n )\n\n from art.estimators.classification.classifier import (\n ClassGradientsMixin,\n ClassifierMixin,\n )\n\n class DummyClassifier(\n ClassGradientsMixin, ClassifierMixin, NeuralNetworkMixin, LossGradientsMixin, BaseEstimator\n ):\n estimator_params = (\n BaseEstimator.estimator_params + NeuralNetworkMixin.estimator_params + ClassifierMixin.estimator_params\n )\n\n def __init__(self):\n super(DummyClassifier, self).__init__(model=None, clip_values=None, channels_first=True)\n self.nb_classes = 10\n\n def class_gradient(self):\n return None\n\n def fit(self):\n pass\n\n def loss_gradient(self, x, y):\n return np.random.normal(size=(1, 3, 33, 32))\n\n def predict(self, x, batch_size=1):\n return np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]])\n\n def get_activations(self):\n return None\n\n def save(self):\n pass\n\n def compute_loss(self, x, y, **kwargs):\n pass\n\n def input_shape(self):\n pass\n\n classifier = DummyClassifier()\n attack = Wasserstein(\n classifier,\n regularization=1,\n kernel_size=3,\n max_iter=1,\n conjugate_sinkhorn_max_iter=10,\n projected_sinkhorn_max_iter=10,\n )\n\n x = np.random.normal(size=(1, 3, 33, 32))\n x_adv = attack.generate(x)\n\n self.assertTrue(x_adv.shape == x.shape)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, targeted=\"true\")\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, regularization=-1)\n\n with self.assertRaises(TypeError):\n _ = Wasserstein(ptc, p=1.0)\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, p=-1)\n\n with self.assertRaises(TypeError):\n _ = Wasserstein(ptc, kernel_size=1.0)\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, kernel_size=2)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, norm=0)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, ball=0)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, eps=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, eps_step=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, norm=\"inf\", eps=1, eps_step=2)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, eps_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, eps_factor=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, conjugate_sinkhorn_max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, projected_sinkhorn_max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = Wasserstein(ptc, verbose=\"true\")\n\n def test_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(Wasserstein, (BaseEstimator, LossGradientsMixin, ClassifierMixin))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/test_zoo.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion.zoo import ZooAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.utils import random_targets\n\nfrom tests.utils import TestBase, get_image_classifier_kr, get_image_classifier_pt\nfrom tests.utils import get_image_classifier_tf, master_seed\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestZooAttack(TestBase):\n \"\"\"\n A unittest class for testing the ZOO attack.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.n_train = 1\n cls.n_test = 1\n cls.x_train_mnist = cls.x_train_mnist[0 : cls.n_train]\n cls.y_train_mnist = cls.y_train_mnist[0 : cls.n_train]\n cls.x_test_mnist = cls.x_test_mnist[0 : cls.n_test]\n cls.y_test_mnist = cls.y_test_mnist[0 : cls.n_test]\n\n def test_2_tensorflow_failure_attack(self):\n \"\"\"\n Test the corner case when attack fails.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # Failure attack\n zoo = ZooAttack(classifier=tfc, max_iter=0, binary_search_steps=0, learning_rate=0, verbose=False)\n x_test_mnist_adv = zoo.generate(self.x_test_mnist)\n self.assertLessEqual(np.amax(x_test_mnist_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_mnist_adv), 0.0)\n np.testing.assert_almost_equal(self.x_test_mnist, x_test_mnist_adv, 3)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_3_tensorflow_mnist(self):\n \"\"\"\n First test with the TensorFlowClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build TensorFlowClassifier\n tfc, sess = get_image_classifier_tf()\n\n # Targeted attack\n zoo = ZooAttack(\n classifier=tfc, targeted=True, max_iter=30, binary_search_steps=8, batch_size=128, verbose=False\n )\n params = {\"y\": random_targets(self.y_test_mnist, tfc.nb_classes)}\n x_test_mnist_adv = zoo.generate(self.x_test_mnist, **params)\n self.assertFalse((self.x_test_mnist == x_test_mnist_adv).all())\n self.assertLessEqual(np.amax(x_test_mnist_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_mnist_adv), 0.0)\n target = np.argmax(params[\"y\"], axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_mnist_adv), axis=1)\n logger.debug(\"ZOO target: %s\", target)\n logger.debug(\"ZOO actual: %s\", y_pred_adv)\n logger.info(\"ZOO success rate on MNIST: %.2f\", (sum(target == y_pred_adv) / float(len(target))))\n\n # Untargeted attack\n zoo = ZooAttack(classifier=tfc, targeted=False, max_iter=10, binary_search_steps=3, verbose=False)\n x_test_mnist_adv = zoo.generate(self.x_test_mnist)\n # self.assertFalse((x_test == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_mnist_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_mnist_adv), 0.0)\n y_pred = np.argmax(tfc.predict(self.x_test_mnist), axis=1)\n y_pred_adv = np.argmax(tfc.predict(x_test_mnist_adv), axis=1)\n logger.debug(\"ZOO actual: %s\", y_pred_adv)\n logger.info(\"ZOO success rate on MNIST: %.2f\", (sum(y_pred != y_pred_adv) / float(len(y_pred))))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Check resize\n x_test_resized = zoo._resize_image(self.x_test_mnist, 64, 64)\n self.assertEqual(x_test_resized.shape, (1, 64, 64, 1))\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_5_keras_mnist(self):\n \"\"\"\n Second test with the KerasClassifier.\n :return:\n \"\"\"\n x_test_original = self.x_test_mnist.copy()\n\n # Build KerasClassifier\n krc = get_image_classifier_kr()\n\n # Targeted attack\n # zoo = ZooAttack(classifier=krc, targeted=True, batch_size=5, verbose=False)\n # params = {'y': random_targets(self.y_test, krc.nb_classes)}\n # x_test_adv = zoo.generate(self.x_test, **params)\n #\n # self.assertFalse((self.x_test == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # target = np.argmax(params['y'], axis=1)\n # y_pred_adv = np.argmax(krc.predict(x_test_adv), axis=1)\n # logger.debug('ZOO target: %s', target)\n # logger.debug('ZOO actual: %s', y_pred_adv)\n # logger.info('ZOO success rate on MNIST: %.2f', (sum(target == y_pred_adv) / float(len(target))))\n\n # Untargeted attack\n # zoo = ZooAttack(classifier=krc, targeted=False, max_iter=20, verbose=False)\n zoo = ZooAttack(classifier=krc, targeted=False, batch_size=5, max_iter=10, binary_search_steps=3, verbose=False)\n # x_test_adv = zoo.generate(x_test)\n params = {\"y\": random_targets(self.y_test_mnist, krc.nb_classes)}\n x_test_mnist_adv = zoo.generate(self.x_test_mnist, **params)\n\n # x_test_adv_true = [0.00000000e+00, 2.50167388e-04, 1.50529508e-04, 4.69674182e-04,\n # 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n # 1.67321396e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n # 0.00000000e+00, 2.08451956e-06, 0.00000000e+00, 0.00000000e+00,\n # 2.53360748e-01, 9.60119188e-01, 9.85227525e-01, 2.53600776e-01,\n # 0.00000000e+00, 0.00000000e+00, 5.23251540e-04, 0.00000000e+00,\n # 0.00000000e+00, 0.00000000e+00, 1.08632184e-05, 0.00000000e+00]\n #\n # for i in range(14):\n # self.assertAlmostEqual(x_test_adv_true[i], x_test_adv[0, 14, i, 0])\n\n # self.assertFalse((x_test == x_test_adv).all())\n self.assertLessEqual(np.amax(x_test_mnist_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_mnist_adv), 0.0)\n y_pred_adv = np.argmax(krc.predict(x_test_mnist_adv), axis=1)\n y_pred = np.argmax(krc.predict(self.x_test_mnist), axis=1)\n logger.debug(\"ZOO actual: %s\", y_pred_adv)\n logger.info(\"ZOO success rate on MNIST: %.2f\", (sum(y_pred != y_pred_adv) / float(len(y_pred))))\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - self.x_test_mnist))), 0.0, delta=0.00001)\n\n # Clean-up\n k.clear_session()\n\n def test_4_pytorch_mnist(self):\n \"\"\"\n Third test with the PyTorchClassifier.\n :return:\n \"\"\"\n # Build PyTorchClassifier\n ptc = get_image_classifier_pt()\n\n # Get MNIST\n x_test_mnist = np.swapaxes(self.x_test_mnist, 1, 3).astype(np.float32)\n x_test_original = x_test_mnist.copy()\n\n # First attack\n # zoo = ZooAttack(classifier=ptc, targeted=True, max_iter=10, binary_search_steps=10, verbose=False)\n # params = {'y': random_targets(self.y_test, ptc.nb_classes)}\n # x_test_adv = zoo.generate(x_test, **params)\n # self.assertFalse((x_test == x_test_adv).all())\n # self.assertLessEqual(np.amax(x_test_adv), 1.0)\n # self.assertGreaterEqual(np.amin(x_test_adv), 0.0)\n # target = np.argmax(params['y'], axis=1)\n # y_pred_adv = np.argmax(ptc.predict(x_test_adv), axis=1)\n # logger.debug('ZOO target: %s', target)\n # logger.debug('ZOO actual: %s', y_pred_adv)\n # logger.info('ZOO success rate on MNIST: %.2f', (sum(target != y_pred_adv) / float(len(target))))\n\n # Second attack\n zoo = ZooAttack(\n classifier=ptc,\n targeted=False,\n learning_rate=1e-2,\n max_iter=10,\n binary_search_steps=3,\n abort_early=False,\n use_resize=False,\n use_importance=False,\n verbose=False,\n )\n x_test_mnist_adv = zoo.generate(x_test_mnist)\n self.assertLessEqual(np.amax(x_test_mnist_adv), 1.0)\n self.assertGreaterEqual(np.amin(x_test_mnist_adv), 0.0)\n\n # print(x_test[0, 0, 14, :])\n # print(x_test_adv[0, 0, 14, :])\n # print(np.amax(x_test - x_test_adv))\n # x_test_adv_expected = []\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test_mnist))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, binary_search_steps=1.0)\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, binary_search_steps=-1)\n\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, max_iter=1.0)\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, nb_parallel=1.0)\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, nb_parallel=-1)\n\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, batch_size=1.0)\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = ZooAttack(ptc, verbose=\"true\")\n\n def test_1_classifier_type_check_fail(self):\n backend_test_classifier_type_check_fail(ZooAttack, [BaseEstimator, ClassifierMixin])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\nimport numpy as np\nimport logging\n\nimport keras.backend as k\n\nfrom art.utils import random_targets, get_labels_np_array\nfrom art.exceptions import EstimatorError\n\nfrom tests.utils import check_adverse_example_x, check_adverse_predicted_sample_y\n\nlogger = logging.getLogger(__name__)\n\n\ndef backend_targeted_images(attack, fix_get_mnist_subset):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n targets = random_targets(y_test_mnist, attack.estimator.nb_classes)\n x_test_adv = attack.generate(x_test_mnist, y=targets, x_init=x_train_mnist)\n assert bool((x_test_mnist == x_test_adv).all()) is False\n\n y_test_pred_adv = get_labels_np_array(attack.estimator.predict(x_test_adv))\n\n assert targets.shape == y_test_pred_adv.shape\n assert (targets == y_test_pred_adv).sum() >= (x_test_mnist.shape[0] // 2)\n\n check_adverse_example_x(x_test_adv, x_test_mnist)\n\n y_pred_adv = np.argmax(attack.estimator.predict(x_test_adv), axis=1)\n\n target = np.argmax(targets, axis=1)\n assert (target == y_pred_adv).any()\n\n\ndef backend_test_defended_images(attack, mnist_dataset):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = mnist_dataset\n x_train_adv = attack.generate(x_train_mnist)\n\n check_adverse_example_x(x_train_adv, x_train_mnist)\n\n y_train_pred_adv = get_labels_np_array(attack.estimator.predict(x_train_adv))\n y_train_labels = get_labels_np_array(y_train_mnist)\n\n check_adverse_predicted_sample_y(y_train_pred_adv, y_train_labels)\n\n x_test_adv = attack.generate(x_test_mnist)\n check_adverse_example_x(x_test_adv, x_test_mnist)\n\n y_test_pred_adv = get_labels_np_array(attack.estimator.predict(x_test_adv))\n check_adverse_predicted_sample_y(y_test_pred_adv, y_test_mnist)\n\n\ndef backend_test_random_initialisation_images(attack, mnist_dataset):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = mnist_dataset\n x_test_adv = attack.generate(x_test_mnist)\n assert bool((x_test_mnist == x_test_adv).all()) is False\n\n\ndef backend_check_adverse_values(attack, mnist_dataset, expected_values):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = mnist_dataset\n x_test_adv = attack.generate(x_test_mnist)\n y_test_pred_adv_matrix = attack.estimator.predict(x_test_adv)\n y_test_pred_adv = np.argmax(y_test_pred_adv_matrix, axis=1)\n\n if \"x_test_mean\" in expected_values:\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_adv - x_test_mnist)),\n expected_values[\"x_test_mean\"].value,\n decimal=expected_values[\"x_test_mean\"].decimals,\n )\n if \"x_test_min\" in expected_values:\n # utils_test.assert_almost_equal_min(x_test_mnist, x_test_adv,\n # expected_values[\"x_test_min\"].value, decimal=expected_values[\"x_test_min\"].decimals)\n np.testing.assert_array_almost_equal(\n float(np.min(x_test_adv - x_test_mnist)),\n expected_values[\"x_test_min\"].value,\n decimal=expected_values[\"x_test_min\"].decimals,\n )\n if \"x_test_max\" in expected_values:\n np.testing.assert_array_almost_equal(\n float(np.max(x_test_adv - x_test_mnist)),\n expected_values[\"x_test_max\"].value,\n decimal=expected_values[\"x_test_max\"].decimals,\n )\n if \"y_test_pred_adv_expected_matrix\" in expected_values:\n np.testing.assert_array_almost_equal(\n y_test_pred_adv_matrix,\n expected_values[\"y_test_pred_adv_expected_matrix\"].value,\n decimal=expected_values[\"y_test_pred_adv_expected\"].decimals,\n )\n if \"y_test_pred_adv_expected\" in expected_values:\n np.testing.assert_array_equal(y_test_pred_adv, expected_values[\"y_test_pred_adv_expected\"].value)\n\n\ndef backend_check_adverse_frames(attack, mnist_dataset, expected_values):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = mnist_dataset\n x_test_adv = attack.generate(x_test_mnist)\n\n x_diff = x_test_adv - x_test_mnist\n x_diff = np.swapaxes(x_diff, 1, attack.frame_index)\n x_diff = np.reshape(x_diff, x_diff.shape[:2] + (np.prod(x_diff.shape[2:]),))\n x_diff_norm = np.round(np.linalg.norm(x_diff, axis=-1), decimals=4)\n x_diff_norm = np.linalg.norm(x_diff_norm, ord=0, axis=-1)\n\n np.testing.assert_array_equal(x_diff_norm, expected_values[\"nb_perturbed_frames\"].value)\n\n\ndef backend_test_classifier_type_check_fail(attack, classifier_expected_list=[], classifier=None, **kwargs):\n assert len(classifier_expected_list) == len(attack._estimator_requirements)\n\n for cls in classifier_expected_list:\n assert cls in classifier_expected_list\n\n for cls in attack._estimator_requirements:\n assert cls in classifier_expected_list\n\n # Use a useless test classifier to test basic classifier properties\n class ClassifierNoAPI:\n pass\n\n classifier = ClassifierNoAPI\n\n with pytest.raises(EstimatorError) as exception:\n _ = attack(classifier, **kwargs)\n\n for classifier_expected in classifier_expected_list:\n assert classifier_expected in exception.value.class_expected_list\n\n\ndef backend_targeted_tabular(attack, fix_get_iris):\n (x_train_iris, _), (x_test_iris, y_test_iris) = fix_get_iris\n\n targets = random_targets(y_test_iris, nb_classes=3)\n x_test_adv = attack.generate(x_test_iris, **{\"y\": targets}, x_init=x_train_iris)\n\n check_adverse_example_x(x_test_adv, x_test_iris)\n\n y_pred_adv = np.argmax(attack.estimator.predict(x_test_adv), axis=1)\n target = np.argmax(targets, axis=1)\n assert (target == y_pred_adv).any()\n\n accuracy = np.sum(y_pred_adv == target) / y_test_iris.shape[0]\n logger.info(\"Success rate of targeted boundary on Iris: %.2f%%\", (accuracy * 100))\n\n\ndef back_end_untargeted_images(attack, fix_get_mnist_subset, fix_framework):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_test_adv = attack.generate(x_test_mnist)\n\n check_adverse_example_x(x_test_adv, x_test_mnist)\n\n y_pred = np.argmax(attack.estimator.predict(x_test_mnist), axis=1)\n y_pred_adv = np.argmax(attack.estimator.predict(x_test_adv), axis=1)\n assert (y_pred != y_pred_adv).any()\n\n if fix_framework in [\"keras\"]:\n k.clear_session()\n\n\ndef backend_untargeted_tabular(attack, iris_dataset, clipped):\n (_, _), (x_test_iris, y_test_iris) = iris_dataset\n\n x_test_adv = attack.generate(x_test_iris)\n\n # TODO remove that platform specific case\n # if framework in [\"scikitlearn\"]:\n # np.testing.assert_array_almost_equal(np.abs(x_test_adv - x_test_iris), .1, decimal=5)\n\n check_adverse_example_x(x_test_adv, x_test_iris)\n # utils_test.check_adverse_example_x(x_test_adv, x_test_iris, bounded=clipped)\n\n y_pred_test_adv = np.argmax(attack.estimator.predict(x_test_adv), axis=1)\n y_test_true = np.argmax(y_test_iris, axis=1)\n\n # assert (y_test_true == y_pred_test_adv).any(), \"An untargeted attack should have changed SOME predictions\"\n assert (\n bool((y_test_true == y_pred_test_adv).all()) is False\n ), \"An untargeted attack should NOT have changed all predictions\"\n\n accuracy = np.sum(y_pred_test_adv == y_test_true) / y_test_true.shape[0]\n logger.info(\n \"Accuracy of \" + attack.estimator.__class__.__name__ + \" on Iris with FGM adversarial examples: \" \"%.2f%%\",\n (accuracy * 100),\n )\n\n\ndef backend_masked_images(attack, fix_get_mnist_subset):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n # generate a random mask:\n mask = np.random.binomial(n=1, p=0.5, size=np.prod(x_test_mnist.shape))\n mask = mask.reshape(x_test_mnist.shape).astype(np.float32)\n\n x_test_adv = attack.generate(x_test_mnist, mask=mask)\n mask_diff = (1 - mask) * (x_test_adv - x_test_mnist)\n np.testing.assert_array_almost_equal(mask_diff, np.zeros(mask_diff.shape), decimal=3)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\nimport pytest\n\nfrom art.estimators.pytorch import PyTorchEstimator\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin\nfrom art.estimators.tensorflow import TensorFlowV2Estimator\nfrom tests.utils import ARTTestFixtureNotImplemented\n\n\n@pytest.fixture\ndef audio_sample():\n \"\"\"\n Create audio sample.\n \"\"\"\n sample_rate = 16000\n test_input = np.ones((sample_rate)) * 10e3\n return test_input\n\n\n@pytest.fixture\ndef audio_data():\n \"\"\"\n Create audio fixtures of shape (nb_samples=3,) with elements of variable length.\n \"\"\"\n sample_rate = 16000\n test_input = np.array(\n [\n np.zeros(sample_rate),\n np.ones(sample_rate * 2) * 2e3,\n np.ones(sample_rate * 3) * 3e3,\n np.ones(sample_rate * 3) * 3e3,\n ],\n dtype=object,\n )\n test_target = [\"DUMMY\"] * test_input.shape[0]\n return test_input, test_target\n\n\n@pytest.fixture\ndef audio_batch_padded():\n \"\"\"\n Create audio fixtures of shape (batch_size=2,) with elements of variable length.\n \"\"\"\n sample_rate = 16000\n test_input = np.ones((2, sample_rate)) * 2e3\n return test_input\n\n\n@pytest.fixture\ndef asr_dummy_estimator(framework):\n def _asr_dummy_estimator(**kwargs):\n asr_dummy = None\n if framework == \"tensorflow2\":\n\n class TensorFlowV2ASRDummy(TensorFlowV2Estimator, SpeechRecognizerMixin):\n def get_activations(self):\n pass\n\n def predict(self, x):\n pass\n\n def loss_gradient(self, x, y, **kwargs):\n return x\n\n @property\n def input_shape(self):\n return None\n\n def compute_loss(self, x, y, **kwargs):\n pass\n\n asr_dummy = TensorFlowV2ASRDummy(channels_first=None, model=None, clip_values=None)\n if framework == \"pytorch\":\n\n class PyTorchASRDummy(PyTorchEstimator, SpeechRecognizerMixin):\n def get_activations(self):\n pass\n\n def predict(self, x):\n pass\n\n def loss_gradient(self, x, y, **kwargs):\n return x\n\n @property\n def input_shape(self):\n return None\n\n def compute_loss(self, x, y, **kwargs):\n pass\n\n asr_dummy = PyTorchASRDummy(channels_first=None, model=None, clip_values=None)\n if asr_dummy is None:\n raise ARTTestFixtureNotImplemented(\n \"ASR dummy estimator not available for this framework\", asr_dummy_estimator.__name__, framework\n )\n return asr_dummy\n\n return _asr_dummy_estimator\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_adversarial_asr.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.adversarial_asr import CarliniWagnerASR\nfrom art.attacks.evasion.imperceptible_asr.imperceptible_asr import ImperceptibleASR\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin, NeuralNetworkMixin\nfrom art.estimators.speech_recognition.speech_recognizer import SpeechRecognizerMixin\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestImperceptibleASR:\n \"\"\"\n Test the ImperceptibleASR attack.\n \"\"\"\n\n @pytest.mark.framework_agnostic\n def test_is_subclass(self, art_warning):\n try:\n assert issubclass(CarliniWagnerASR, (ImperceptibleASR, EvasionAttack))\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"kerastf\", \"non_dl_frameworks\")\n def test_implements_abstract_methods(self, art_warning, asr_dummy_estimator):\n try:\n CarliniWagnerASR(estimator=asr_dummy_estimator())\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.framework_agnostic\n def test_classifier_type_check_fail(self, art_warning):\n try:\n backend_test_classifier_type_check_fail(\n CarliniWagnerASR, [NeuralNetworkMixin, LossGradientsMixin, BaseEstimator, SpeechRecognizerMixin]\n )\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"kerastf\", \"non_dl_frameworks\")\n def test_generate_batch(self, art_warning, mocker, asr_dummy_estimator, audio_data):\n try:\n test_input, test_target = audio_data\n\n # mock _create_adversarial and test if result gets passed unchanged through _create_imperceptible\n mocker.patch.object(CarliniWagnerASR, \"_create_adversarial\", return_value=test_input)\n\n carlini_asr = CarliniWagnerASR(estimator=asr_dummy_estimator())\n adversarial = carlini_asr._generate_batch(test_input, test_target)\n\n carlini_asr._create_adversarial.assert_called()\n for a, t in zip(adversarial, test_input):\n assert_array_equal(a, t)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_adversarial_texture_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import AdversarialTexturePyTorch\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.object_tracking.object_tracker import ObjectTrackerMixin\nfrom art.estimators.object_tracking import PyTorchGoturn\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_module(\"scripts\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_generate(art_warning, fix_get_mnist_subset, fix_get_goturn, framework):\n try:\n import torch\n from scripts.train import GoturnTrain\n from pathlib import Path\n\n _device = \"cpu\"\n\n goturn_path = os.path.join(os.sep, \"tmp\", \"goturn-pytorch\")\n\n model_dir = Path(os.path.join(goturn_path, \"src\", \"goturn\", \"models\"))\n ckpt_dir = model_dir.joinpath(\"checkpoints\")\n ckpt_path = next(ckpt_dir.glob(\"*.ckpt\"))\n\n ckpt_mod = torch.load(\n os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"),\n map_location=_device,\n )\n ckpt_mod[\"hparams\"][\"pretrained_model\"] = os.path.join(\n goturn_path, \"src\", \"goturn\", \"models\", \"pretrained\", \"caffenet_weights.npy\"\n )\n torch.save(ckpt_mod, os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"))\n\n model = GoturnTrain.load_from_checkpoint(ckpt_path)\n\n pgt = PyTorchGoturn(\n model=model,\n input_shape=(3, 227, 227),\n clip_values=(0, 255),\n preprocessing=(np.array([104.0, 117.0, 123.0]), np.array([1.0, 1.0, 1.0])),\n device_type=_device,\n )\n\n y_init = np.array([[48, 79, 80, 110], [48, 79, 80, 110]])\n x_list = list()\n for i in range(2):\n x_list.append(np.random.random_integers(0, 255, size=(4, 277, 277, 3)).astype(float) / 255.0)\n\n x = np.asarray(x_list, dtype=float)\n\n y_pred = pgt.predict(x=x, y_init=y_init)\n\n attack = AdversarialTexturePyTorch(\n pgt,\n patch_height=4,\n patch_width=4,\n x_min=2,\n y_min=2,\n step_size=1.0 / 255.0,\n max_iter=5,\n batch_size=16,\n verbose=True,\n )\n\n patch = attack.generate(x=x, y=y_pred, y_init=y_init)\n assert patch.shape == (2, 4, 277, 277, 3)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"scripts\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_generate_patch_points(art_warning, fix_get_mnist_subset, fix_get_goturn, framework):\n try:\n import torch\n from scripts.train import GoturnTrain\n from pathlib import Path\n\n _device = \"cpu\"\n\n goturn_path = os.path.join(os.sep, \"tmp\", \"goturn-pytorch\")\n\n model_dir = Path(os.path.join(goturn_path, \"src\", \"goturn\", \"models\"))\n ckpt_dir = model_dir.joinpath(\"checkpoints\")\n ckpt_path = next(ckpt_dir.glob(\"*.ckpt\"))\n\n ckpt_mod = torch.load(\n os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"),\n map_location=_device,\n )\n ckpt_mod[\"hparams\"][\"pretrained_model\"] = os.path.join(\n goturn_path, \"src\", \"goturn\", \"models\", \"pretrained\", \"caffenet_weights.npy\"\n )\n torch.save(ckpt_mod, os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"))\n\n model = GoturnTrain.load_from_checkpoint(ckpt_path)\n\n pgt = PyTorchGoturn(\n model=model,\n input_shape=(3, 227, 227),\n clip_values=(0, 255),\n preprocessing=(np.array([104.0, 117.0, 123.0]), np.array([1.0, 1.0, 1.0])),\n device_type=_device,\n )\n\n y_init = np.array([[48, 79, 80, 110], [48, 79, 80, 110]])\n x_list = list()\n nb_frames = 4\n for i in range(2):\n x_list.append(np.random.random_integers(0, 255, size=(4, 277, 277, 3)).astype(float) / 255.0)\n\n x = np.asarray(x_list, dtype=float)\n\n y_pred = pgt.predict(x=x, y_init=y_init)\n\n attack = AdversarialTexturePyTorch(\n pgt,\n patch_height=4,\n patch_width=4,\n x_min=0,\n y_min=0,\n step_size=1.0 / 255.0,\n max_iter=5,\n batch_size=16,\n verbose=True,\n )\n\n patch_points = np.zeros((nb_frames, 4, 2))\n patch_points_0 = [[30, 20], [50, 20], [50, 50], [30, 50]]\n\n for i in range(nb_frames):\n patch_points[i, 0, 0] = patch_points_0[0][0]\n patch_points[i, 0, 1] = patch_points_0[0][1]\n patch_points[i, 1, 0] = patch_points_0[1][0]\n patch_points[i, 1, 1] = patch_points_0[1][1]\n patch_points[i, 2, 0] = patch_points_0[2][0]\n patch_points[i, 2, 1] = patch_points_0[2][1]\n patch_points[i, 3, 0] = patch_points_0[3][0]\n patch_points[i, 3, 1] = patch_points_0[3][1]\n\n x_patched = attack.generate(x=x, y=y_pred, y_init=y_init, patch_points=patch_points)\n assert x_patched.shape == (2, nb_frames, 277, 277, 3)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_apply_patch(art_warning, fix_get_goturn):\n try:\n goturn = fix_get_goturn\n attack = AdversarialTexturePyTorch(\n goturn,\n patch_height=4,\n patch_width=4,\n x_min=0,\n y_min=0,\n step_size=1.0 / 255.0,\n max_iter=500,\n batch_size=16,\n verbose=True,\n )\n\n nb_frames = 15\n patch = np.ones(shape=(4, 4, 3))\n foreground = np.ones(shape=(1, nb_frames, 10, 10, 3))\n foreground[:, :, 5, 5, :] = 0\n x = np.zeros(shape=(1, nb_frames, 10, 10, 3))\n\n patch_points = np.zeros((nb_frames, 4, 2))\n patch_points_0 = [[3, 2], [5, 2], [5, 5], [3, 5]]\n\n for i in range(nb_frames):\n patch_points[i, 0, 0] = patch_points_0[0][0]\n patch_points[i, 0, 1] = patch_points_0[0][1]\n patch_points[i, 1, 0] = patch_points_0[1][0]\n patch_points[i, 1, 1] = patch_points_0[1][1]\n patch_points[i, 2, 0] = patch_points_0[2][0]\n patch_points[i, 2, 1] = patch_points_0[2][1]\n patch_points[i, 3, 0] = patch_points_0[3][0]\n patch_points[i, 3, 1] = patch_points_0[3][1]\n\n patched_images = attack.apply_patch(x=x, patch_external=patch, foreground=foreground, patch_points=patch_points)\n\n patch_sum_expected = nb_frames * 3 * (2 * 3)\n complement_sum_expected = 0.0\n\n patch_sum = np.sum(patched_images[0, :, 3:5, 2:5, :])\n complement_sum = np.sum(patched_images[0]) - patch_sum\n\n assert patch_sum == patch_sum_expected\n assert complement_sum == complement_sum_expected\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_apply_patch_patch_points(art_warning, fix_get_goturn):\n try:\n goturn = fix_get_goturn\n attack = AdversarialTexturePyTorch(\n goturn,\n patch_height=4,\n patch_width=4,\n x_min=2,\n y_min=2,\n step_size=1.0 / 255.0,\n max_iter=500,\n batch_size=16,\n verbose=True,\n )\n\n patch = np.ones(shape=(4, 4, 3))\n foreground = np.ones(shape=(1, 15, 10, 10, 3))\n foreground[:, :, 5, 5, :] = 0\n x = np.zeros(shape=(1, 15, 10, 10, 3))\n\n patched_images = attack.apply_patch(x=x, patch_external=patch, foreground=foreground)\n\n patch_sum_expected = 15 * 3 * (4 * 4 - 1)\n complement_sum_expected = 0.0\n\n patch_sum = np.sum(patched_images[0, :, 2:6, 2:6, :])\n complement_sum = np.sum(patched_images[0]) - patch_sum\n\n assert patch_sum == patch_sum_expected\n assert complement_sum == complement_sum_expected\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_check_params(art_warning, fix_get_goturn):\n try:\n goturn = fix_get_goturn\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=-2, patch_width=2)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2.0, patch_width=2)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=-2)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2.0)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, x_min=-2)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, x_min=2.0)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, y_min=-2)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, y_min=2.0)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, step_size=-2.0)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, step_size=2)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, max_iter=-2)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, max_iter=2.0)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, batch_size=-2)\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, batch_size=2.0)\n\n with pytest.raises(ValueError):\n _ = AdversarialTexturePyTorch(goturn, patch_height=2, patch_width=2, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n# @pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n AdversarialTexturePyTorch,\n [BaseEstimator, LossGradientsMixin, ObjectTrackerMixin],\n patch_height=2,\n patch_width=2,\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_auto_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion import AutoAttack\nfrom art.attacks.evasion.auto_projected_gradient_descent import AutoProjectedGradientDescent\nfrom art.attacks.evasion.deepfool import DeepFool\nfrom art.attacks.evasion.square_attack import SquareAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate_default(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n\n attack = AutoAttack(\n estimator=classifier,\n norm=np.inf,\n eps=0.3,\n eps_step=0.1,\n attacks=None,\n batch_size=32,\n estimator_orig=None,\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(0.0292, abs=0.105)\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(0.3, abs=0.05)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate_attacks_and_targeted(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n\n norm = np.inf\n eps = 0.3\n eps_step = 0.1\n batch_size = 32\n\n attacks = list()\n attacks.append(\n AutoProjectedGradientDescent(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=100,\n targeted=True,\n nb_random_init=5,\n batch_size=batch_size,\n loss_type=\"cross_entropy\",\n )\n )\n attacks.append(\n AutoProjectedGradientDescent(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=100,\n targeted=False,\n nb_random_init=5,\n batch_size=batch_size,\n loss_type=\"difference_logits_ratio\",\n )\n )\n attacks.append(DeepFool(classifier=classifier, max_iter=100, epsilon=1e-6, nb_grads=3, batch_size=batch_size))\n attacks.append(SquareAttack(estimator=classifier, norm=norm, max_iter=5000, eps=eps, p_init=0.8, nb_restarts=5))\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n # First test with defined_attack_only=False\n attack = AutoAttack(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n attacks=attacks,\n batch_size=batch_size,\n estimator_orig=None,\n targeted=False,\n )\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(0.0182, abs=0.105)\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(0.3, abs=0.05)\n\n # Then test with defined_attack_only=True\n attack = AutoAttack(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n attacks=attacks,\n batch_size=batch_size,\n estimator_orig=None,\n targeted=True,\n )\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.mean(x_train_mnist_adv - x_train_mnist) == pytest.approx(0.0179, abs=0.0075)\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(eps, abs=0.005)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_attack_if_targeted_not_supported(art_warning, fix_get_mnist_subset, image_dl_estimator):\n with pytest.raises(ValueError) as excinfo:\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = SquareAttack(estimator=classifier, norm=np.inf, max_iter=5000, eps=0.3, p_init=0.8, nb_restarts=5)\n attack.set_params(targeted=True)\n assert str(excinfo.value) == \"\"\"The attribute \"targeted\" cannot be set for this attack.\"\"\"\n\n\n@pytest.mark.skip_framework(\"keras\", \"pytorch\", \"non_dl_frameworks\", \"kerastf\")\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n from art.attacks.evasion import FastGradientMethod\n\n classifier = image_dl_estimator_for_attack(AutoAttack)\n\n attacks = [FastGradientMethod(estimator=classifier)]\n\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, norm=0)\n\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, eps=\"1\")\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, eps=-1.0)\n\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, eps_step=\"1\")\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, eps_step=-1.0)\n\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = AutoAttack(classifier, attacks=attacks, batch_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(AutoAttack, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate_parallel(art_warning, fix_get_mnist_subset, image_dl_estimator, framework):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n\n if framework == \"tensorflow2\":\n import tensorflow as tf\n\n classifier.model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01))\n\n norm = np.inf\n eps = 0.3\n eps_step = 0.1\n batch_size = 32\n\n attacks = list()\n attacks.append(\n AutoProjectedGradientDescent(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=100,\n targeted=True,\n nb_random_init=5,\n batch_size=batch_size,\n loss_type=\"cross_entropy\",\n verbose=False,\n )\n )\n attacks.append(\n AutoProjectedGradientDescent(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n max_iter=100,\n targeted=False,\n nb_random_init=5,\n batch_size=batch_size,\n loss_type=\"difference_logits_ratio\",\n verbose=False,\n )\n )\n attacks.append(\n DeepFool(\n classifier=classifier,\n max_iter=100,\n epsilon=1e-6,\n nb_grads=3,\n batch_size=batch_size,\n verbose=False,\n )\n )\n attacks.append(\n SquareAttack(\n estimator=classifier,\n norm=norm,\n max_iter=5000,\n eps=eps,\n p_init=0.8,\n nb_restarts=5,\n verbose=False,\n )\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n # First test with defined_attack_only=False\n attack = AutoAttack(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n attacks=attacks,\n batch_size=batch_size,\n estimator_orig=None,\n targeted=False,\n parallel_pool_size=3,\n )\n\n attack_noparallel = AutoAttack(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n attacks=attacks,\n batch_size=batch_size,\n estimator_orig=None,\n targeted=False,\n parallel_pool_size=0,\n )\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n x_train_mnist_adv_nop = attack_noparallel.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(expected=0.0182, abs=0.105)\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(expected=0.3, abs=0.05)\n\n noparallel_perturbation = np.linalg.norm(x_train_mnist[[2]] - x_train_mnist_adv_nop[[2]])\n parallel_perturbation = np.linalg.norm(x_train_mnist[[2]] - x_train_mnist_adv[[2]])\n\n assert parallel_perturbation < noparallel_perturbation\n\n # Then test with defined_attack_only=True\n attack = AutoAttack(\n estimator=classifier,\n norm=norm,\n eps=eps,\n eps_step=eps_step,\n attacks=attacks,\n batch_size=batch_size,\n estimator_orig=None,\n targeted=True,\n parallel_pool_size=3,\n )\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.mean(x_train_mnist_adv - x_train_mnist) == pytest.approx(expected=0.0, abs=0.0075)\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(expected=eps, abs=0.005)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_auto_conjugate_gradient.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n\n# Copyright (c) 2022 Keiichiro Yamamura\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion import AutoConjugateGradient\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.parametrize(\"loss_type\", [\"cross_entropy\", \"difference_logits_ratio\"])\n@pytest.mark.parametrize(\"norm\", [\"inf\", np.inf, 1, 2])\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, framework, loss_type, norm):\n try:\n classifier = image_dl_estimator_for_attack(AutoConjugateGradient, from_logits=True)\n\n attack = AutoConjugateGradient(\n estimator=classifier,\n norm=norm,\n eps=0.3,\n eps_step=0.1,\n max_iter=5,\n targeted=False,\n nb_random_init=1,\n batch_size=32,\n loss_type=loss_type,\n verbose=False,\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) > 0.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n\n classifier = image_dl_estimator_for_attack(AutoConjugateGradient, from_logits=True)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, eps=\"1\")\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, eps=-1.0)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, eps_step=\"1\")\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, eps_step=-1.0)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, targeted=\"true\")\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, nb_random_init=1.0)\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, nb_random_init=-1)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, loss_type=\"test\")\n\n with pytest.raises(ValueError):\n _ = AutoConjugateGradient(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n AutoConjugateGradient, [BaseEstimator, LossGradientsMixin, ClassifierMixin]\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_auto_projected_gradient_descent.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion import AutoProjectedGradientDescent\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.parametrize(\"loss_type\", [\"cross_entropy\", \"difference_logits_ratio\"])\n@pytest.mark.parametrize(\"norm\", [\"inf\", np.inf, 1, 2])\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, framework, loss_type, norm):\n try:\n classifier = image_dl_estimator_for_attack(AutoProjectedGradientDescent, from_logits=True)\n\n attack = AutoProjectedGradientDescent(\n estimator=classifier,\n norm=norm,\n eps=0.3,\n eps_step=0.1,\n max_iter=5,\n targeted=False,\n nb_random_init=1,\n batch_size=32,\n loss_type=loss_type,\n verbose=False,\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) > 0.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n\n classifier = image_dl_estimator_for_attack(AutoProjectedGradientDescent, from_logits=True)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, eps=\"1\")\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, eps=-1.0)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, eps_step=\"1\")\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, eps_step=-1.0)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, targeted=\"true\")\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, nb_random_init=1.0)\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, nb_random_init=-1)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, loss_type=\"test\")\n\n with pytest.raises(ValueError):\n _ = AutoProjectedGradientDescent(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n AutoProjectedGradientDescent, [BaseEstimator, LossGradientsMixin, ClassifierMixin]\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_boundary.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport pytest\nimport logging\n\nfrom art.attacks.evasion import BoundaryAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_targeted_tabular, backend_untargeted_tabular, backend_targeted_images\nfrom tests.attacks.utils import back_end_untargeted_images, backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"clipped_classifier, targeted\", [(True, True), (True, False), (False, True), (False, False)])\ndef test_tabular(art_warning, tabular_dl_estimator, framework, get_iris_dataset, clipped_classifier, targeted):\n try:\n classifier = tabular_dl_estimator(clipped=clipped_classifier)\n attack = BoundaryAttack(classifier, targeted=targeted, max_iter=10, verbose=False)\n if targeted:\n backend_targeted_tabular(attack, get_iris_dataset)\n else:\n backend_untargeted_tabular(attack, get_iris_dataset, clipped=clipped_classifier)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"targeted\", [True, False])\ndef test_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, framework, targeted):\n try:\n classifier = image_dl_estimator_for_attack(BoundaryAttack)\n attack = BoundaryAttack(estimator=classifier, targeted=targeted, max_iter=20, verbose=False)\n if targeted:\n backend_targeted_images(attack, fix_get_mnist_subset)\n else:\n back_end_untargeted_images(attack, fix_get_mnist_subset, framework)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(BoundaryAttack)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, num_trial=1.0)\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, num_trial=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, sample_size=1.0)\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, sample_size=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, init_size=1.0)\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, init_size=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, epsilon=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, delta=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, step_adapt=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, min_epsilon=\"1.0\")\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, min_epsilon=-1)\n\n with pytest.raises(ValueError):\n _ = BoundaryAttack(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(BoundaryAttack, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_brendel_and_bethge.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import BrendelBethgeAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"targeted\", [True, False])\n@pytest.mark.parametrize(\"norm\", [0, 1, 2, np.inf, \"inf\"])\ndef test_generate(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack, targeted, norm):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier = image_dl_estimator_for_attack(BrendelBethgeAttack, defended=False, from_logits=True)\n\n attack = BrendelBethgeAttack(\n estimator=classifier,\n norm=norm,\n targeted=targeted,\n overshoot=1.1,\n steps=1,\n lr=1e-3,\n lr_decay=0.5,\n lr_num_decay=20,\n momentum=0.8,\n binary_search_steps=1,\n init_size=5,\n batch_size=32,\n )\n\n attack.generate(x=x_test_mnist[0:1].astype(np.float32), y=y_test_mnist[0:1].astype(int))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(BrendelBethgeAttack, from_logits=True)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, norm=3)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, targeted=\"true\")\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, overshoot=1)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, overshoot=0.9)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, steps=1.0)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, steps=0)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, lr=1)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, lr=-1)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, lr_decay=1)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, lr_decay=-1)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, lr_num_decay=1.0)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, lr_num_decay=-1)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, momentum=1)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, momentum=-1)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, binary_search_steps=1.0)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, binary_search_steps=-1)\n\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, init_size=1.0)\n with pytest.raises(ValueError):\n _ = BrendelBethgeAttack(classifier, init_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail():\n backend_test_classifier_type_check_fail(BrendelBethgeAttack, [BaseEstimator, LossGradientsMixin, ClassifierMixin])\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_composite_adversarial_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import CompositeAdversarialAttackPyTorch\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException, get_cifar10_image_classifier_pt\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_cifar10_subset(get_cifar10_dataset):\n (x_train_cifar10, y_train_cifar10), (x_test_cifar10, y_test_cifar10) = get_cifar10_dataset\n n_train = 100\n n_test = 11\n yield x_train_cifar10[:n_train], y_train_cifar10[:n_train], x_test_cifar10[:n_test], y_test_cifar10[:n_test]\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"non_dl_frameworks\", \"kerastf\", \"huggingface\")\ndef test_generate(art_warning, fix_get_cifar10_subset):\n try:\n (x_train, y_train, x_test, y_test) = fix_get_cifar10_subset\n\n classifier = get_cifar10_image_classifier_pt(from_logits=False, load_init=True)\n attack = CompositeAdversarialAttackPyTorch(classifier)\n\n x_train_adv = attack.generate(x=x_train, y=y_train)\n x_test_adv = attack.generate(x=x_test, y=y_test)\n\n assert x_train.shape == x_train_adv.shape\n assert np.min(x_train_adv) >= 0.0\n assert np.max(x_train_adv) <= 1.0\n assert x_test.shape == x_test_adv.shape\n assert np.min(x_test_adv) >= 0.0\n assert np.max(x_test_adv) <= 1.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_check_params(art_warning):\n try:\n classifier = get_cifar10_image_classifier_pt(from_logits=False, load_init=True)\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, enabled_attack=(0, 1, 2, 3, 4, 5, 6, 7))\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, hue_epsilon=(-10.0, 0.0))\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, hue_epsilon=(0.0, 10.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, hue_epsilon=(-1, 2.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, hue_epsilon=3.14)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, hue_epsilon=(0.0, 10.0, 20.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, hue_epsilon=(\"1.0\", 2.0))\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, sat_epsilon=(-10.0, 0.0))\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, sat_epsilon=(0.0, -10.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, sat_epsilon=(1, 2.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, sat_epsilon=2.0)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, sat_epsilon=(0.0, 10.0, 20.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, sat_epsilon=(\"1.0\", 2.0))\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, rot_epsilon=(-450.0, 359.0))\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, rot_epsilon=(10.0, -10.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, rot_epsilon=(1.0, 2))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, rot_epsilon=10)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, rot_epsilon=(0.0, 10.0, 20.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, rot_epsilon=(\"10\", 20.0))\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, bri_epsilon=(-10.0, 0.0))\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, bri_epsilon=(0.0, 10.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, bri_epsilon=(-1, 1.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, bri_epsilon=1.0)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, bri_epsilon=(0.0, 10.0, 20.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, bri_epsilon=(\"1.0\", 2.0))\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, con_epsilon=(-10.0, 10.0))\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, con_epsilon=(0.0, -10.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, con_epsilon=(1, 2.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, con_epsilon=2.0)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, con_epsilon=(0.0, 10.0, 20.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, con_epsilon=(\"1.0\", 2.0))\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, pgd_epsilon=(-0.5, 2.0))\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, pgd_epsilon=(8 / 255, -8 / 255))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, pgd_epsilon=(-2, 1))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, pgd_epsilon=8 / 255)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, pgd_epsilon=(0.0, 10.0, 20.0))\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, pgd_epsilon=(\"2/255\", 3 / 255))\n\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, early_stop=\"true\")\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, early_stop=1)\n\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, max_iter=\"max\")\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, max_iter=-5)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, max_iter=2.5)\n\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, max_inner_iter=\"max\")\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, max_inner_iter=-5)\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, max_inner_iter=2.5)\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, attack_order=\"schedule\")\n\n with pytest.raises(ValueError):\n _ = CompositeAdversarialAttackPyTorch(classifier, batch_size=-1)\n\n with pytest.raises(TypeError):\n _ = CompositeAdversarialAttackPyTorch(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n CompositeAdversarialAttackPyTorch, [BaseEstimator, LossGradientsMixin, ClassifierMixin]\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_dpatch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import DPatch\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import master_seed\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.framework_agnostic\ndef test_generate(art_warning, fix_get_mnist_subset, fix_get_rcnn):\n try:\n (_, _, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n frcnn = fix_get_rcnn\n attack = DPatch(\n frcnn,\n patch_shape=(4, 4, 1),\n learning_rate=1.0,\n max_iter=1,\n batch_size=1,\n verbose=False,\n )\n patch = attack.generate(x=x_test_mnist[[0]])\n assert patch.shape == (4, 4, 1)\n\n attack.apply_patch(x=x_test_mnist)\n attack.apply_patch(x=x_test_mnist, patch_external=patch)\n attack.apply_patch(x=x_test_mnist, patch_external=patch, mask=np.ones((1, 28, 28)).astype(bool))\n attack.apply_patch(\n x=x_test_mnist, patch_external=patch, mask=np.ones((1, 28, 28)).astype(bool), random_location=True\n )\n\n patch = attack.generate(x=x_test_mnist[[0]], target_label=1)\n assert patch.shape == (4, 4, 1)\n patch = attack.generate(x=x_test_mnist[[0]], target_label=np.array([1]))\n assert patch.shape == (4, 4, 1)\n patch = attack.generate(x=x_test_mnist[[0]], target_label=[1])\n assert patch.shape == (4, 4, 1)\n\n with pytest.raises(ValueError):\n _ = attack.generate(x=np.repeat(x_test_mnist, axis=3, repeats=2))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"random_location\", [True, False])\n@pytest.mark.parametrize(\"image_format\", [\"NHWC\", \"NCHW\"])\n@pytest.mark.framework_agnostic\ndef test_augment_images_with_patch(art_warning, random_location, image_format, fix_get_mnist_subset):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n # TODO this master_seed should be removed as it is already set in conftest.py. expected values will\n # need to be updated accordingly\n master_seed()\n\n if image_format == \"NHWC\":\n patch = np.ones(shape=(4, 4, 1)) * 0.5\n x = x_train_mnist[0:3]\n channels_first = False\n elif image_format == \"NCHW\":\n patch = np.ones(shape=(1, 4, 4)) * 0.5\n x = np.transpose(x_train_mnist[0:3], (0, 3, 1, 2))\n channels_first = True\n else:\n raise ValueError(\"Value of `image_format` not recognized.\")\n\n patched_images, transformations = DPatch._augment_images_with_patch(\n x=x, patch=patch, random_location=random_location, channels_first=channels_first\n )\n\n if random_location:\n transformation_expected = {\"i_x_1\": 0, \"i_y_1\": 2, \"i_x_2\": 4, \"i_y_2\": 6}\n patched_images_column = [\n 0.0,\n 0.0,\n 0.5,\n 0.5,\n 0.5,\n 0.5,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n else:\n transformation_expected = {\"i_x_1\": 0, \"i_y_1\": 0, \"i_x_2\": 4, \"i_y_2\": 4}\n patched_images_column = [\n 0.5,\n 0.5,\n 0.5,\n 0.5,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n\n assert transformations[1] == transformation_expected\n\n if image_format == \"NCHW\":\n patched_images = np.transpose(patched_images, (0, 2, 3, 1))\n\n np.testing.assert_array_equal(patched_images[1, 2, :, 0], patched_images_column)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, fix_get_rcnn):\n try:\n frcnn = fix_get_rcnn\n\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, patch_shape=(1.0, 2.0, 3.0))\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, patch_shape=(1, 2, 3, 4))\n\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, learning_rate=1)\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, learning_rate=-1.0)\n\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = DPatch(frcnn, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(DPatch, [BaseEstimator, LossGradientsMixin, ObjectDetectorMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_dpatch_robust.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import RobustDPatch\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.object_detection.object_detector import ObjectDetectorMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"keras\", \"scikitlearn\", \"kerastf\")\ndef test_generate(art_warning, fix_get_mnist_subset, fix_get_rcnn, framework):\n try:\n (_, _, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n if framework in [\"pytorch\", \"huggingface\"]:\n x_test_mnist = np.transpose(x_test_mnist, (0, 2, 3, 1))\n\n frcnn = fix_get_rcnn\n attack = RobustDPatch(\n frcnn,\n patch_shape=(4, 4, 1),\n patch_location=(2, 2),\n crop_range=(0, 0),\n brightness_range=(1.0, 1.0),\n rotation_weights=(0.25, 0.25, 0.25, 0.25),\n sample_size=1,\n learning_rate=1.0,\n max_iter=1,\n batch_size=1,\n verbose=False,\n )\n patch = attack.generate(x=x_test_mnist)\n assert patch.shape == (4, 4, 1)\n\n with pytest.raises(ValueError):\n _ = attack.generate(x=np.repeat(x_test_mnist, axis=3, repeats=2))\n\n with pytest.raises(ValueError):\n _ = attack.generate(x=x_test_mnist, y=y_test_mnist)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"keras\", \"scikitlearn\", \"kerastf\")\ndef test_generate_targeted(art_warning, fix_get_mnist_subset, fix_get_rcnn, framework):\n try:\n (_, _, x_test_mnist, _) = fix_get_mnist_subset\n\n if framework in [\"pytorch\", \"huggingface\"]:\n x_test_mnist = np.transpose(x_test_mnist, (0, 2, 3, 1))\n\n frcnn = fix_get_rcnn\n attack = RobustDPatch(\n frcnn,\n patch_shape=(4, 4, 1),\n patch_location=(2, 2),\n crop_range=(0, 0),\n brightness_range=(1.0, 1.0),\n rotation_weights=(1, 0, 0, 0),\n sample_size=1,\n learning_rate=1.0,\n max_iter=1,\n batch_size=1,\n targeted=True,\n verbose=False,\n )\n y = frcnn.predict(x_test_mnist)\n patch = attack.generate(x=x_test_mnist, y=y)\n assert patch.shape == (4, 4, 1)\n\n with pytest.raises(ValueError):\n _ = attack.generate(x=x_test_mnist, y=None)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [False, True])\n@pytest.mark.skip_framework(\"keras\", \"scikitlearn\", \"kerastf\")\ndef test_augment_images_with_patch(art_warning, channels_first, fix_get_rcnn):\n try:\n frcnn = fix_get_rcnn\n attack = RobustDPatch(\n frcnn,\n patch_shape=(4, 4, 1),\n patch_location=(2, 2),\n crop_range=(0, 0),\n brightness_range=(1.0, 1.0),\n rotation_weights=(1, 0, 0, 0),\n sample_size=1,\n learning_rate=1.0,\n max_iter=1,\n batch_size=1,\n verbose=False,\n )\n\n if channels_first:\n patch = np.ones(shape=(1, 4, 4))\n x = np.zeros(shape=(1, 1, 10, 10))\n else:\n patch = np.ones(shape=(4, 4, 1))\n x = np.zeros(shape=(1, 10, 10, 1))\n\n patched_images, _, transformations = attack._augment_images_with_patch(\n x=x, y=None, patch=patch, channels_first=channels_first\n )\n\n transformation_expected = {\"crop_x\": 0, \"crop_y\": 0, \"rot90\": 0, \"brightness\": 1.0}\n patch_sum_expected = 16.0\n complement_sum_expected = 0.0\n\n if channels_first:\n patch_sum = np.sum(patched_images[0, :, 2:7, 2:7])\n else:\n patch_sum = np.sum(patched_images[0, 2:7, 2:7, :])\n\n complement_sum = np.sum(patched_images[0]) - patch_sum\n\n assert transformations == transformation_expected\n\n assert patch_sum == patch_sum_expected\n\n assert complement_sum == complement_sum_expected\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"keras\", \"scikitlearn\", \"kerastf\")\ndef test_apply_patch(art_warning, fix_get_rcnn):\n try:\n frcnn = fix_get_rcnn\n attack = RobustDPatch(\n frcnn,\n patch_shape=(4, 4, 1),\n patch_location=(2, 2),\n crop_range=(0, 0),\n brightness_range=(1.0, 1.0),\n rotation_weights=(1, 0, 0, 0),\n sample_size=1,\n learning_rate=1.0,\n max_iter=1,\n batch_size=1,\n verbose=False,\n )\n\n patch = np.ones(shape=(4, 4, 1))\n x = np.zeros(shape=(1, 10, 10, 1))\n\n patched_images = attack.apply_patch(x=x, patch_external=patch)\n\n patch_sum_expected = 16.0\n complement_sum_expected = 0.0\n\n patch_sum = np.sum(patched_images[0, 2:7, 2:7, :])\n complement_sum = np.sum(patched_images[0]) - patch_sum\n\n assert patch_sum == patch_sum_expected\n assert complement_sum == complement_sum_expected\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [False, True])\n@pytest.mark.skip_framework(\"keras\", \"scikitlearn\", \"kerastf\")\ndef test_untransform_gradients(art_warning, fix_get_rcnn, channels_first):\n try:\n crop_x = 1\n crop_y = 1\n rot90 = 3\n brightness = 1.0\n\n if channels_first:\n patch_shape = (1, 4, 4)\n gradients = np.zeros(shape=(1, 1, 10, 10))\n gradients[:, :, 2:7, 2:7] = 1\n gradients = gradients[:, :, crop_x : 10 - crop_x, crop_y : 10 - crop_y]\n gradients = np.rot90(gradients, rot90, (2, 3))\n else:\n patch_shape = (4, 4, 1)\n gradients = np.zeros(shape=(1, 10, 10, 1))\n gradients[:, 2:7, 2:7, :] = 1\n gradients = gradients[:, crop_x : 10 - crop_x, crop_y : 10 - crop_y, :]\n gradients = np.rot90(gradients, rot90, (1, 2))\n\n frcnn = fix_get_rcnn\n attack = RobustDPatch(\n frcnn,\n patch_shape=patch_shape,\n patch_location=(2, 2),\n crop_range=(0, 0),\n brightness_range=(1.0, 1.0),\n rotation_weights=(1, 0, 0, 0),\n sample_size=1,\n learning_rate=1.0,\n max_iter=1,\n batch_size=1,\n verbose=False,\n )\n\n transforms = {\"crop_x\": crop_x, \"crop_y\": crop_y, \"rot90\": rot90, \"brightness\": brightness}\n\n gradients = attack._untransform_gradients(\n gradients=gradients, transforms=transforms, channels_first=channels_first\n )\n\n gradients_sum = np.sum(gradients[0])\n gradients_sum_expected = 16.0\n\n assert gradients_sum == gradients_sum_expected\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, fix_get_rcnn):\n try:\n frcnn = fix_get_rcnn\n\n # with pytest.raises(TypeError):\n # _ = RobustDPatch(frcnn, patch_shape=(1.0, 2.0, 3.0))\n # with pytest.raises(ValueError):\n # _ = RobustDPatch(frcnn, patch_shape=(1, 2, 3, 4))\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, learning_rate=1)\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, learning_rate=-1.0)\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, verbose=\"true\")\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, patch_location=\"true\")\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, patch_location=(1, 2, 3))\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, crop_range=\"true\")\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, crop_range=(1, 2, 3))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, crop_range=(2, 1))\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, patch_location=(0, 1), crop_range=(1, 2))\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, brightness_range=(1, 2, 3))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, brightness_range=(1.0, 2.0, 3.0))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, brightness_range=(-1.0, 1.0))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, brightness_range=(2.0, 1.0))\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, rotation_weights=(\"1\", \"2\", \"3\"))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, rotation_weights=(1, 2, 3))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, rotation_weights=(-1, -2, -3, -4))\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, rotation_weights=(0.0, 0.0, 0.0, 0.0))\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, sample_size=1.0)\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, sample_size=-1)\n\n with pytest.raises(ValueError):\n _ = RobustDPatch(frcnn, targeted=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(RobustDPatch, [BaseEstimator, LossGradientsMixin, ObjectDetectorMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_fast_gradient.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\n\nfrom tests.attacks.utils import backend_check_adverse_values, backend_test_defended_images\nfrom tests.attacks.utils import backend_test_random_initialisation_images, backend_targeted_images\nfrom tests.attacks.utils import backend_targeted_tabular, backend_untargeted_tabular, backend_masked_images\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ExpectedValue, ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n# currently NOT setting this test as framework_agnostic since no TensorFlow implementation\n# of the defended classifier exists\ndef test_classifier_defended_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod, defended=True)\n attack = FastGradientMethod(classifier, eps=1.0, batch_size=128)\n backend_test_defended_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_random_initialisation_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n attack = FastGradientMethod(classifier, num_random_init=3)\n backend_test_random_initialisation_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_targeted_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n attack = FastGradientMethod(classifier, eps=1.0, targeted=True)\n attack_params = {\"minimal\": True, \"eps_step\": 0.01, \"eps\": 1.0}\n attack.set_params(**attack_params)\n\n backend_targeted_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_masked_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n attack = FastGradientMethod(classifier, eps=1.0, num_random_init=1)\n backend_masked_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_minimal_perturbations_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n\n expected_values = {\n \"x_test_mean\": ExpectedValue(0.03896513, 0.01),\n \"x_test_min\": ExpectedValue(-0.30000000, 0.00001),\n \"x_test_max\": ExpectedValue(0.30000000, 0.00001),\n \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([4, 2, 4, 7, 0, 4, 7, 2, 0, 7, 0]), 2),\n }\n\n attack = FastGradientMethod(classifier, eps=1.0, batch_size=11)\n\n # Test eps of float type\n attack_params = {\"minimal\": True, \"eps_step\": 0.1, \"eps\": 5.0}\n attack.set_params(**attack_params)\n\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n\n # Test eps of array type 1\n (_, _, x_test_mnist, _) = fix_get_mnist_subset\n eps = np.ones(shape=x_test_mnist.shape) * 5.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"minimal\": True, \"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n\n # Test eps of array type 2\n eps = np.ones(shape=x_test_mnist.shape[1:]) * 5.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"minimal\": True, \"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n\n # Test eps of array type 3\n eps = np.ones(shape=x_test_mnist.shape[2:]) * 5.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"minimal\": True, \"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n\n # Test eps of array type 4\n eps = np.ones(shape=x_test_mnist.shape[3:]) * 5.0\n eps_step = np.ones_like(eps) * 0.1\n\n attack_params = {\"minimal\": True, \"eps_step\": eps_step, \"eps\": eps}\n attack.set_params(**attack_params)\n\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"norm\", [np.inf, 1, 2, 10])\n@pytest.mark.skip_framework(\"pytorch\") # temporarily skipping for pytorch until find bug fix in bounded test\n@pytest.mark.framework_agnostic\ndef test_norm_images(art_warning, norm, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n\n if norm == np.inf:\n expected_values = {\n \"x_test_mean\": ExpectedValue(0.2346725, 0.002),\n \"x_test_min\": ExpectedValue(-1.0, 0.00001),\n \"x_test_max\": ExpectedValue(1.0, 0.00001),\n \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([4, 4, 4, 7, 7, 4, 7, 2, 2, 3, 0]), 2),\n }\n\n elif norm == 1:\n expected_values = {\n \"x_test_mean\": ExpectedValue(0.00051374, 0.002),\n \"x_test_min\": ExpectedValue(-0.01486498, 0.001),\n \"x_test_max\": ExpectedValue(0.014761963, 0.001),\n \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([7, 4, 1, 4, 4, 1, 4, 4, 4, 4, 4]), 4),\n }\n elif norm == 2:\n expected_values = {\n \"x_test_mean\": ExpectedValue(0.007636416, 0.001),\n \"x_test_min\": ExpectedValue(-0.211054801, 0.001),\n \"x_test_max\": ExpectedValue(0.209592223, 0.001),\n \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([7, 2, 4, 4, 4, 7, 7, 4, 0, 4, 4]), 2),\n }\n elif norm == 10:\n expected_values = {\n \"x_test_mean\": ExpectedValue(0.007636416, 0.001),\n \"x_test_min\": ExpectedValue(-0.211054801, 0.001),\n \"x_test_max\": ExpectedValue(0.209592223, 0.001),\n \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([4, 2, 4, 7, 0, 4, 7, 7, 2, 3, 0]), 2),\n }\n else:\n raise ValueError(\"Value of `expected_values` not recognized.\")\n\n attack = FastGradientMethod(classifier, eps=1.0, norm=norm, batch_size=128)\n\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"scikitlearn\") # temporarily skipping for scikitlearn until find bug fix in bounded test\n@pytest.mark.parametrize(\"targeted, clipped\", [(True, True), (True, False), (False, True), (False, False)])\n@pytest.mark.framework_agnostic\ndef test_tabular(art_warning, tabular_dl_estimator, framework, get_iris_dataset, targeted, clipped):\n try:\n classifier = tabular_dl_estimator(clipped=clipped)\n\n if targeted:\n attack = FastGradientMethod(classifier, targeted=True, eps=0.1, batch_size=128)\n backend_targeted_tabular(attack, get_iris_dataset)\n else:\n attack = FastGradientMethod(classifier, eps=0.1)\n backend_untargeted_tabular(attack, get_iris_dataset, clipped=clipped)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_classification(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, fix_get_rcnn):\n try:\n classifier = fix_get_rcnn\n attack = FastGradientMethod(classifier, num_random_init=3)\n backend_test_random_initialisation_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, eps=-1, eps_step=1)\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, eps=np.array([-1, -1, -1]), eps_step=np.array([1, 1, 1]))\n\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, eps=1, eps_step=-1)\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, eps=np.array([1, 1, 1]), eps_step=np.array([-1, -1, -1]))\n\n with pytest.raises(TypeError):\n _ = FastGradientMethod(classifier, eps=1, eps_step=np.array([1, 1, 1]))\n\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, targeted=\"true\")\n\n with pytest.raises(TypeError):\n _ = FastGradientMethod(classifier, num_random_init=1.0)\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, num_random_init=-1)\n\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = FastGradientMethod(classifier, minimal=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(FastGradientMethod, [BaseEstimator, LossGradientsMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_frame_saliency.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import FastGradientMethod, FrameSaliencyAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\n\nfrom tests.utils import ExpectedValue\nfrom tests.attacks.utils import backend_check_adverse_values, backend_check_adverse_frames\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"pytorch\")\n@pytest.mark.framework_agnostic\ndef test_one_shot(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n\n # for the one-shot method, frame saliency attack should resort to plain FastGradientMethod\n expected_values = {\n \"x_test_mean\": ExpectedValue(0.2346725, 0.002),\n \"x_test_min\": ExpectedValue(-1.0, 0.00001),\n \"x_test_max\": ExpectedValue(1.0, 0.00001),\n \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([4, 4, 4, 7, 7, 4, 7, 2, 2, 3, 0]), 2),\n }\n\n attacker = FastGradientMethod(classifier, eps=1.0, batch_size=128)\n attack = FrameSaliencyAttack(classifier, attacker, \"one_shot\")\n backend_check_adverse_values(attack, fix_get_mnist_subset, expected_values)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\")\n@pytest.mark.framework_agnostic\ndef test_iterative_saliency(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n\n expected_values_axis_1 = {\n \"nb_perturbed_frames\": ExpectedValue(np.asarray([10, 1, 2, 12, 16, 1, 2, 7, 4, 11, 5]), 2)\n }\n\n expected_values_axis_2 = {\n \"nb_perturbed_frames\": ExpectedValue(np.asarray([11, 1, 2, 6, 14, 2, 2, 13, 4, 8, 4]), 2)\n }\n\n attacker = FastGradientMethod(classifier, eps=0.3, batch_size=128)\n attack = FrameSaliencyAttack(classifier, attacker, \"iterative_saliency\")\n backend_check_adverse_frames(attack, fix_get_mnist_subset, expected_values_axis_1)\n\n # test with non-default frame index:\n attack = FrameSaliencyAttack(classifier, attacker, \"iterative_saliency\", frame_index=2)\n backend_check_adverse_frames(attack, fix_get_mnist_subset, expected_values_axis_2)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\")\n@pytest.mark.framework_agnostic\ndef test_iterative_saliency_refresh(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FastGradientMethod)\n\n expected_values_axis_1 = {\n \"nb_perturbed_frames\": ExpectedValue(np.asarray([5, 1, 3, 10, 8, 1, 3, 8, 4, 7, 7]), 2)\n }\n\n expected_values_axis_2 = {\n \"nb_perturbed_frames\": ExpectedValue(np.asarray([11, 1, 2, 6, 14, 2, 2, 13, 4, 8, 4]), 2)\n }\n\n attacker = FastGradientMethod(classifier, eps=0.3, batch_size=128)\n attack = FrameSaliencyAttack(classifier, attacker, \"iterative_saliency_refresh\")\n backend_check_adverse_frames(attack, fix_get_mnist_subset, expected_values_axis_1)\n\n # test with non-default frame index:\n attack = FrameSaliencyAttack(classifier, attacker, \"iterative_saliency\", frame_index=2)\n backend_check_adverse_frames(attack, fix_get_mnist_subset, expected_values_axis_2)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n from art.attacks.evasion import FastGradientMethod\n\n classifier = image_dl_estimator_for_attack(FrameSaliencyAttack, from_logits=True)\n\n attacker = FastGradientMethod(estimator=classifier)\n\n with pytest.raises(ValueError):\n _ = FrameSaliencyAttack(classifier, attacker=\"attack\")\n\n with pytest.raises(ValueError):\n _ = FrameSaliencyAttack(classifier, attacker=attacker, method=\"test\")\n\n with pytest.raises(ValueError):\n _ = FrameSaliencyAttack(classifier, attacker=attacker, frame_index=0)\n\n with pytest.raises(ValueError):\n _ = FrameSaliencyAttack(classifier, attacker=attacker, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = FrameSaliencyAttack(classifier, attacker=attacker, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(FastGradientMethod, [LossGradientsMixin, BaseEstimator])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_geometric_decision_based_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion.geometric_decision_based_attack import GeoDA\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.framework_agnostic\ndef test_generate_2d_dct_basis(art_warning, image_dl_estimator):\n try:\n sub_dim = 5\n res = 224\n\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = GeoDA(estimator=classifier, sub_dim=5, max_iter=4000, verbose=False)\n\n dct = attack._generate_2d_dct_basis(sub_dim=sub_dim, res=res)\n assert dct.shape == (res * res, sub_dim * sub_dim)\n dct_50000 = np.array(\n [\n [\n 0.00446429,\n -0.0063133,\n 0.00631283,\n -0.00631206,\n 0.00631097,\n 0.00490833,\n -0.00694126,\n 0.00694075,\n -0.00693989,\n 0.0069387,\n 0.00131841,\n -0.00186447,\n 0.00186434,\n -0.00186411,\n 0.00186379,\n -0.00285836,\n 0.00404223,\n -0.00404193,\n 0.00404143,\n -0.00404074,\n -0.00576281,\n 0.00814965,\n -0.00814905,\n 0.00814805,\n -0.00814664,\n ]\n ]\n )\n np.testing.assert_almost_equal(dct[50000], dct_50000)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_is_adversarial(art_warning, image_dl_estimator, fix_get_mnist_subset):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = GeoDA(estimator=classifier, sub_dim=5, max_iter=4000, verbose=False)\n\n assert not attack._is_adversarial(x_adv=x_test_mnist[[0]], y_true=y_test_mnist[[0]])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_find_random_adversarial(art_warning, image_dl_estimator, fix_get_mnist_subset):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = GeoDA(estimator=classifier, sub_dim=5, max_iter=4000, verbose=False)\n\n x_adv = attack._find_random_adversarial(x=x_test_mnist[[0]], y=y_test_mnist[[0]])\n\n assert np.argmax(classifier.predict(x_adv)) != np.argmax(y_test_mnist[[0]])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_opt_query_iteration(art_warning, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = GeoDA(estimator=classifier, sub_dim=5, max_iter=4000, verbose=False)\n opt_q, var_t = attack._opt_query_iteration(var_nq=3800, var_t=8, lambda_param=0.6)\n\n opt_q_expected = [75, 106, 149, 210, 295, 414, 582, 818, 1150]\n var_t_expected = 9\n\n assert opt_q == opt_q_expected\n assert var_t == var_t_expected\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_sub_noise(art_warning, image_dl_estimator, fix_get_mnist_subset):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = GeoDA(estimator=classifier, sub_dim=5, max_iter=4000, verbose=False)\n c = attack._sub_noise(num_noises=64, basis=np.ones((28 * 28, 25)))\n\n assert c[0].shape == x_train_mnist[0].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_generate(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = GeoDA(estimator=classifier, sub_dim=5, max_iter=400, verbose=False)\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(0.057965796, abs=0.01)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(GeoDA, from_logits=True)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, sub_dim=1.0)\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, sub_dim=-1)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, bin_search_tol=\"1\")\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, bin_search_tol=-1.0)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, lambda_param=1)\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, lambda_param=-1.0)\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, sigma=1)\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, sigma=-1.0)\n\n # with pytest.raises(ValueError):\n # _ = GeoDA(classifier, targeted=\"true\")\n\n with pytest.raises(ValueError):\n _ = GeoDA(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(GeoDA, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_imperceptible_asr.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.attacks.evasion.imperceptible_asr.imperceptible_asr import ImperceptibleASR, PsychoacousticMasker\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestImperceptibleASR:\n \"\"\"\n Test the ImperceptibleASR attack.\n \"\"\"\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_is_subclass(self, art_warning):\n try:\n assert issubclass(ImperceptibleASR, EvasionAttack)\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_implements_abstract_methods(self, art_warning, asr_dummy_estimator):\n try:\n ImperceptibleASR(estimator=asr_dummy_estimator(), masker=PsychoacousticMasker())\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_generate(self, art_warning, mocker, asr_dummy_estimator, audio_data):\n try:\n test_input, test_target = audio_data\n\n mocker.patch.object(ImperceptibleASR, \"_generate_batch\")\n\n imperceptible_asr = ImperceptibleASR(estimator=asr_dummy_estimator(), masker=PsychoacousticMasker())\n _ = imperceptible_asr.generate(test_input, test_target)\n\n imperceptible_asr._generate_batch.assert_called()\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_generate_batch(self, art_warning, mocker, asr_dummy_estimator, audio_data):\n try:\n test_input, test_target = audio_data\n\n mocker.patch.object(ImperceptibleASR, \"_create_adversarial\")\n mocker.patch.object(ImperceptibleASR, \"_create_imperceptible\")\n\n imperceptible_asr = ImperceptibleASR(estimator=asr_dummy_estimator(), masker=PsychoacousticMasker())\n _ = imperceptible_asr._generate_batch(test_input, test_target)\n\n imperceptible_asr._create_adversarial.assert_called()\n imperceptible_asr._create_imperceptible.assert_called()\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_create_adversarial(self, art_warning, mocker, asr_dummy_estimator, audio_data):\n try:\n test_input, test_target = audio_data\n\n estimator = asr_dummy_estimator()\n mocker.patch.object(estimator, \"predict\", return_value=test_target)\n mocker.patch.object(\n ImperceptibleASR,\n \"_loss_gradient_masking_threshold\",\n return_value=(np.zeros_like(audio_data), [0] * test_input.shape[0]),\n )\n\n # learning rate of zero ensures that adversarial example equals test input\n imperceptible_asr = ImperceptibleASR(\n estimator=estimator, masker=PsychoacousticMasker(), max_iter_1=15, learning_rate_1=0.5\n )\n # learning rate of zero ensures that adversarial example equals test input\n imperceptible_asr.learning_rate_1 = 0\n adversarial = imperceptible_asr._create_adversarial(test_input, test_target)\n\n # test shape and adversarial example result\n assert [x.shape for x in test_input] == [a.shape for a in adversarial]\n assert [(a - x).sum() for a, x in zip(adversarial, test_input)] == [0.0] * test_input.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_create_imperceptible(self, art_warning, mocker, asr_dummy_estimator, audio_data):\n try:\n test_input, test_target = audio_data\n test_adversarial = test_input\n\n estimator = asr_dummy_estimator()\n mocker.patch.object(estimator, \"predict\", return_value=test_target)\n mocker.patch.object(\n ImperceptibleASR,\n \"_loss_gradient_masking_threshold\",\n return_value=(np.zeros_like(test_input), [0] * test_input.shape[0]),\n )\n\n imperceptible_asr = ImperceptibleASR(\n estimator=estimator, masker=PsychoacousticMasker(), max_iter_2=25, learning_rate_2=0.5\n )\n # learning rate of zero ensures that adversarial example equals test input\n imperceptible_asr.learning_rate_2 = 0\n adversarial = imperceptible_asr._create_imperceptible(test_input, test_adversarial, test_target)\n\n # test shape and adversarial example result\n assert [x.shape for x in test_input] == [a.shape for a in adversarial]\n assert [(x - a).sum() for a, x in zip(adversarial, test_input)] == [0.0] * test_input.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow\", \"kerastf\", \"non_dl_frameworks\")\n def test_loss_gradient_masking_threshold(self, art_warning, asr_dummy_estimator, audio_data):\n try:\n test_input, _ = audio_data\n test_delta = test_input * 0\n\n imperceptible_asr = ImperceptibleASR(estimator=asr_dummy_estimator(), masker=PsychoacousticMasker())\n\n masking_threshold, psd_maximum = imperceptible_asr._stabilized_threshold_and_psd_maximum(test_input)\n loss_gradient, loss = imperceptible_asr._loss_gradient_masking_threshold(\n test_delta, test_input, masking_threshold, psd_maximum\n )\n\n assert [g.shape for g in loss_gradient] == [d.shape for d in test_delta]\n assert loss.ndim == 1 and loss.shape == test_delta.shape\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow\", \"kerastf\", \"non_dl_frameworks\")\n def test_loss_gradient_masking_threshold_torch(self, art_warning, asr_dummy_estimator, audio_batch_padded):\n try:\n test_delta = audio_batch_padded\n test_psd_maximum = np.ones((test_delta.shape[0], 1, 1))\n test_masking_threshold = np.zeros((test_delta.shape[0], 1025, 28))\n\n imperceptible_asr = ImperceptibleASR(estimator=asr_dummy_estimator(), masker=PsychoacousticMasker())\n loss_gradient, loss = imperceptible_asr._loss_gradient_masking_threshold_torch(\n test_delta, test_psd_maximum, test_masking_threshold\n )\n\n assert loss_gradient.shape == test_delta.shape\n assert loss.ndim == 1 and loss.shape[0] == test_delta.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow\", \"kerastf\", \"non_dl_frameworks\")\n def test_approximate_power_spectral_density_torch(self, art_warning, asr_dummy_estimator, audio_batch_padded):\n try:\n import torch\n\n test_delta = audio_batch_padded\n test_psd_maximum = np.ones((test_delta.shape[0], 1, 1))\n\n masker = PsychoacousticMasker()\n imperceptible_asr = ImperceptibleASR(estimator=asr_dummy_estimator(), masker=masker)\n approximate_psd_torch = imperceptible_asr._approximate_power_spectral_density_torch(\n torch.from_numpy(test_delta), torch.from_numpy(test_psd_maximum)\n )\n psd_approximated = approximate_psd_torch.numpy()\n\n assert psd_approximated.ndim == 3\n assert psd_approximated.shape[0] == test_delta.shape[0] # batch_size\n assert psd_approximated.shape[1] == masker.window_size // 2 + 1\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.skip_framework(\"tensorflow2\", \"kerastf\", \"non_dl_frameworks\")\n def test_check_params(self, art_warning, image_dl_estimator_for_attack, asr_dummy_estimator):\n try:\n from art.attacks.evasion.imperceptible_asr.imperceptible_asr import ImperceptibleASR\n\n masker = PsychoacousticMasker()\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, eps=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, max_iter_1=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, max_iter_1=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, max_iter_2=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, max_iter_2=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, learning_rate_1=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, learning_rate_1=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, learning_rate_2=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, learning_rate_2=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, loss_theta_min=\"1\")\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, decrease_factor_eps=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, decrease_factor_eps=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, num_iter_decrease_eps=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, num_iter_decrease_eps=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, alpha=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, alpha=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, increase_factor_alpha=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, increase_factor_alpha=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, num_iter_increase_alpha=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, num_iter_increase_alpha=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, decrease_factor_alpha=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, decrease_factor_alpha=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, num_iter_decrease_alpha=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, num_iter_decrease_alpha=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASR(asr_dummy_estimator(), masker=masker, batch_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\nclass TestPsychoacousticMasker:\n \"\"\"\n Test the PsychoacousticMasker.\n \"\"\"\n\n @pytest.mark.framework_agnostic\n def test_power_spectral_density(self, art_warning, audio_sample):\n try:\n test_input = audio_sample\n\n masker = PsychoacousticMasker()\n psd_matrix, psd_max = masker.power_spectral_density(test_input)\n\n assert psd_matrix.shape == (masker.window_size // 2 + 1, 28)\n assert np.floor(psd_max) == 78.0\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.framework_agnostic\n def test_find_maskers(self, art_warning):\n try:\n test_psd_vector = np.array([2, 10, 96, 90, 35, 40, 36, 60, 55, 91, 40])\n\n masker = PsychoacousticMasker()\n maskers, masker_idx = masker.find_maskers(test_psd_vector)\n\n # test masker_idx shape and first, last maskers\n assert masker_idx.tolist() == [2, 5, 7, 9]\n np.testing.assert_array_equal(\n maskers[[0, -1]], 10 * np.log10(np.sum(10 ** np.array([[1.0, 9.6, 9.0], [5.5, 9.1, 4.0]]), axis=1))\n )\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.framework_agnostic\n def test_filter_maskers(self, art_warning):\n try:\n test_psd_vector = np.array([2, 10, 96, 90, 35, 40, 36, 60, 55, 91, 40])\n test_masker_idx = np.array([2, 5, 7, 9])\n test_maskers = test_psd_vector[test_masker_idx]\n\n masker = PsychoacousticMasker()\n maskers, masker_idx = masker.filter_maskers(test_maskers, test_masker_idx)\n\n assert masker_idx.tolist() == [2]\n assert maskers.tolist() == [96]\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.framework_agnostic\n def test_calculate_individual_threshold(self, art_warning, mocker):\n try:\n test_masker_idx = np.array([2, 5, 7, 9])\n test_maskers = np.array([96, 40, 60, 9])\n\n masker = PsychoacousticMasker()\n threshold = masker.calculate_individual_threshold(test_maskers, test_masker_idx)\n\n assert threshold.shape == test_masker_idx.shape + (masker.window_size // 2 + 1,)\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.framework_agnostic\n def test_calculate_global_threshold(self, art_warning, mocker):\n try:\n test_threshold = np.array([[0, 10, 20], [10, 0, 20]])\n\n mocker.patch(\n \"art.attacks.evasion.imperceptible_asr.imperceptible_asr.\"\n \"PsychoacousticMasker.absolute_threshold_hearing\",\n new_callable=mocker.PropertyMock,\n return_value=np.zeros(test_threshold.shape[1]),\n )\n\n masker = PsychoacousticMasker()\n threshold = masker.calculate_global_threshold(test_threshold)\n\n assert threshold.tolist() == (10 * np.log10([12, 12, 201])).tolist()\n except ARTTestException as e:\n art_warning(e)\n\n @pytest.mark.framework_agnostic\n def test_calculate_threshold_and_psd_maximum(self, art_warning, audio_sample):\n try:\n test_input = audio_sample\n\n masker = PsychoacousticMasker()\n threshold, psd_max = masker.calculate_threshold_and_psd_maximum(test_input)\n\n assert threshold.shape == (masker.window_size // 2 + 1, 28)\n assert np.floor(psd_max) == 78.0\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_imperceptible_asr_pytorch.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_imperceptible_asr_pytorch[cpu-False]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch[cpu-True]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch[gpu-False]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch[gpu-True]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch_mp3compression_pytorch[cpu-False]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch_mp3compression_pytorch[cpu-True]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch_mp3compression_pytorch[gpu-False]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n },\n \"test_imperceptible_asr_pytorch_mp3compression_pytorch[gpu-True]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ]\n }\n}\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_imperceptible_asr_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_module(\"deepspeech_pytorch\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"use_amp\", [False, True])\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_imperceptible_asr_pytorch(art_warning, expected_values, use_amp, device_type):\n import torch\n\n from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\n from art.attacks.evasion.imperceptible_asr.imperceptible_asr_pytorch import ImperceptibleASRPyTorch\n from art.preprocessing.audio import LFilterPyTorch\n\n try:\n # Skip test if gpu is not available and use_amp is true\n if use_amp and not torch.cuda.is_available():\n return\n\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[\"x1\"]\n x2 = expected_data[\"x2\"]\n x3 = expected_data[\"x3\"]\n\n # Create signal data\n x = np.array(\n [\n np.array(x1 * 200, dtype=ART_NUMPY_DTYPE),\n np.array(x2 * 200, dtype=ART_NUMPY_DTYPE),\n np.array(x3 * 200, dtype=ART_NUMPY_DTYPE),\n ]\n )\n\n # Create labels\n y = np.array([\"S\", \"I\", \"GD\"])\n\n # Create DeepSpeech estimator with preprocessing\n numerator_coef = np.array([0.0000001, 0.0000002, -0.0000001, -0.0000002], dtype=ART_NUMPY_DTYPE)\n denominator_coef = np.array([1.0, 0.0, 0.0, 0.0], dtype=ART_NUMPY_DTYPE)\n audio_filter = LFilterPyTorch(\n numerator_coef=numerator_coef, denominator_coef=denominator_coef, device_type=device_type\n )\n\n speech_recognizer = PyTorchDeepSpeech(\n pretrained_model=\"librispeech\",\n device_type=device_type,\n use_amp=use_amp,\n preprocessing_defences=audio_filter,\n )\n\n # Create attack\n asr_attack = ImperceptibleASRPyTorch(\n estimator=speech_recognizer,\n eps=0.001,\n max_iter_1=5,\n max_iter_2=5,\n learning_rate_1=0.00001,\n learning_rate_2=0.001,\n optimizer_1=torch.optim.Adam,\n optimizer_2=torch.optim.Adam,\n global_max_length=3200,\n initial_rescale=1.0,\n decrease_factor_eps=0.8,\n num_iter_decrease_eps=5,\n alpha=0.01,\n increase_factor_alpha=1.2,\n num_iter_increase_alpha=5,\n decrease_factor_alpha=0.8,\n num_iter_decrease_alpha=5,\n win_length=2048,\n hop_length=512,\n n_fft=2048,\n batch_size=2,\n use_amp=use_amp,\n opt_level=\"O1\",\n )\n\n # Test transcription output\n transcriptions_preprocessing = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n expected_transcriptions = np.array([\"\", \"\", \"\"])\n\n assert (expected_transcriptions == transcriptions_preprocessing).all()\n\n # Generate attack\n x_adv_preprocessing = asr_attack.generate(x, y)\n\n # Test shape\n assert x_adv_preprocessing[0].shape == x[0].shape\n assert x_adv_preprocessing[1].shape == x[1].shape\n assert x_adv_preprocessing[2].shape == x[2].shape\n\n # Test content\n assert not (x_adv_preprocessing[0] == x[0]).all()\n assert not (x_adv_preprocessing[1] == x[1]).all()\n assert not (x_adv_preprocessing[2] == x[2]).all()\n\n assert np.sum(x_adv_preprocessing[0]) != np.inf\n assert np.sum(x_adv_preprocessing[1]) != np.inf\n assert np.sum(x_adv_preprocessing[2]) != np.inf\n\n assert np.sum(x_adv_preprocessing[0]) != 0\n assert np.sum(x_adv_preprocessing[1]) != 0\n assert np.sum(x_adv_preprocessing[2]) != 0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"deepspeech_pytorch\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"use_amp\", [False])\n@pytest.mark.parametrize(\"device_type\", [\"cpu\"])\ndef test_imperceptible_asr_pytorch_mp3compression_pytorch(art_warning, expected_values, use_amp, device_type):\n import torch\n\n from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\n from art.attacks.evasion.imperceptible_asr.imperceptible_asr_pytorch import ImperceptibleASRPyTorch\n from art.defences.preprocessor import Mp3CompressionPyTorch\n\n try:\n # Skip test if gpu is not available and use_amp is true\n if use_amp and not torch.cuda.is_available():\n return\n\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[\"x1\"]\n\n # Create signal data\n x = np.array([x1 * 200, x1 * 200], dtype=ART_NUMPY_DTYPE)\n\n # Create labels\n y = np.array([\"S\", \"I\"])\n\n # Create DeepSpeech estimator with preprocessing\n mp3compression = Mp3CompressionPyTorch(sample_rate=44100, channels_first=True)\n\n speech_recognizer = PyTorchDeepSpeech(\n pretrained_model=\"librispeech\",\n device_type=device_type,\n use_amp=use_amp,\n preprocessing_defences=mp3compression,\n )\n\n # Create attack\n asr_attack = ImperceptibleASRPyTorch(\n estimator=speech_recognizer,\n eps=0.001,\n max_iter_1=5,\n max_iter_2=5,\n learning_rate_1=0.00001,\n learning_rate_2=0.001,\n optimizer_1=torch.optim.Adam,\n optimizer_2=torch.optim.Adam,\n global_max_length=3200,\n initial_rescale=1.0,\n decrease_factor_eps=0.8,\n num_iter_decrease_eps=5,\n alpha=0.01,\n increase_factor_alpha=1.2,\n num_iter_increase_alpha=5,\n decrease_factor_alpha=0.8,\n num_iter_decrease_alpha=5,\n win_length=2048,\n hop_length=512,\n n_fft=2048,\n batch_size=2,\n use_amp=use_amp,\n opt_level=\"O1\",\n )\n\n # Test transcription output\n transcriptions_preprocessing = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n expected_transcriptions = np.array([\"\", \"\"])\n\n assert (expected_transcriptions == transcriptions_preprocessing).all()\n\n # Generate attack\n x_adv_preprocessing = asr_attack.generate(x, y)\n\n # Test shape\n assert x_adv_preprocessing[0].shape == x[0].shape\n assert x_adv_preprocessing[1].shape == x[1].shape\n\n # Test content\n assert not (x_adv_preprocessing[0] == x[0]).all()\n assert not (x_adv_preprocessing[1] == x[1]).all()\n\n assert np.sum(x_adv_preprocessing[0]) != np.inf\n assert np.sum(x_adv_preprocessing[1]) != np.inf\n\n assert np.sum(x_adv_preprocessing[0]) != 0\n assert np.sum(x_adv_preprocessing[1]) != 0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"deepspeech_pytorch\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_check_params(art_warning):\n try:\n from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\n from art.attacks.evasion.imperceptible_asr.imperceptible_asr_pytorch import ImperceptibleASRPyTorch\n\n speech_recognizer = PyTorchDeepSpeech(\n pretrained_model=\"librispeech\",\n device_type=\"cpu\",\n use_amp=False,\n preprocessing_defences=None,\n )\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, eps=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, max_iter_1=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, max_iter_1=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, max_iter_2=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, max_iter_2=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, learning_rate_1=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, learning_rate_1=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, learning_rate_2=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, learning_rate_2=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, global_max_length=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, global_max_length=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, initial_rescale=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, initial_rescale=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, decrease_factor_eps=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, decrease_factor_eps=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, num_iter_decrease_eps=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, num_iter_decrease_eps=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, alpha=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, alpha=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, increase_factor_alpha=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, increase_factor_alpha=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, num_iter_increase_alpha=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, num_iter_increase_alpha=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, decrease_factor_alpha=\"1\")\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, decrease_factor_alpha=-1.0)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, num_iter_decrease_alpha=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, num_iter_decrease_alpha=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, win_length=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, win_length=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, hop_length=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, hop_length=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, n_fft=1.0)\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, n_fft=-1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, win_length=5, n_fft=1)\n\n with pytest.raises(ValueError):\n _ = ImperceptibleASRPyTorch(speech_recognizer, batch_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_laser_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nTest LaserAttack.\n\"\"\"\nfrom typing import Callable, Tuple, Any\n\nimport numpy as np\nimport pytest\nfrom art.attacks.evasion.laser_attack.laser_attack import LaserBeam, LaserBeamGenerator, LaserBeamAttack\nfrom art.attacks.evasion.laser_attack.utils import ImageGenerator\nfrom tests.utils import ARTTestException\n\n\n@pytest.fixture(name=\"close\")\ndef fixture_close() -> Callable:\n \"\"\"\n Comparison function.\n :returns: function that checks if two float arrays are close.\n \"\"\"\n\n def close(x: np.ndarray, y: np.ndarray):\n \"\"\"\n Check if two float arrays are close.\n\n :param x: first float array\n :param y: second float array\n :returns: true if they are close\n \"\"\"\n assert x.shape == y.shape\n return np.testing.assert_array_almost_equal(x, y)\n\n return close\n\n\n@pytest.fixture(name=\"not_close\")\ndef fixture_not_close(close):\n \"\"\"\n Comparison function.\n :returns: function that checks if values of two float arrays are not close.\n \"\"\"\n\n def not_close(x: np.ndarray, y: np.ndarray) -> bool:\n \"\"\"\n Compare two float arrays\n\n :param x: first float array\n :param y: second float array\n :returns: true if they are not the same\n \"\"\"\n try:\n close(x, y)\n return False\n except AssertionError:\n return True\n\n return not_close\n\n\n@pytest.fixture(name=\"less_or_equal\")\ndef fixture_less_or_equal():\n \"\"\"\n Comparison function.\n :returns: function that checks if first array is less or equal than the second.\n \"\"\"\n\n def leq(x: np.ndarray, y: np.ndarray) -> bool:\n \"\"\"\n Compare two float arrays\n\n :param x: first array\n :param y: second array\n :returns: true if every element of the first array is less or equal than the corresponding element\n of the second array.\n \"\"\"\n return (x <= y).all()\n\n return leq\n\n\n@pytest.fixture(name=\"image_shape\")\ndef fixture_image_shape() -> Tuple[int, int, int]:\n \"\"\"\n Image shape used for the tests.\n\n :returns: Image shape.\n \"\"\"\n return (64, 128, 3)\n\n\n@pytest.fixture(name=\"min_laser_beam\")\ndef fixture_min_laser_beam() -> LaserBeam:\n \"\"\"\n LaserBeam object with physically minimal possible parameters.\n\n :returns: LaserBeam object\n \"\"\"\n return LaserBeam.from_array([380, 0, 0, 1])\n\n\n@pytest.fixture(name=\"max_laser_beam\")\ndef fixture_max_laser_beam() -> LaserBeam:\n \"\"\"\n LaserBeam object with physically minimal possible parameters.\n\n :returns: LaserBeam.\n \"\"\"\n return LaserBeam.from_array([780, 3.14, 32, int(1.4 * 32)])\n\n\n@pytest.fixture(name=\"laser_generator_fixture\")\ndef fixture_laser_generator_fixture(min_laser_beam, max_laser_beam) -> Callable:\n \"\"\"\n Return a function that returns generator of the LaserBeam objects.\n\n :param min_laser_beam: LaserBeam object with minimal acceptable properties.\n :param max_laser_beam: LaserBeam object with maximal acceptable properties.\n :returns: Function used to generate LaserBeam objects based on max_step param.\n \"\"\"\n return lambda max_step: LaserBeamGenerator(min_laser_beam, max_laser_beam, max_step=max_step)\n\n\n@pytest.fixture(name=\"laser_generator\")\ndef fixture_laser_generator(min_laser_beam, max_laser_beam) -> LaserBeamGenerator:\n \"\"\"\n Generator of the LaserBeam objects.\n\n :param min_laser_beam: LaserBeam object with minimal acceptable properties.\n :param max_laser_beam: LaserBeam object with maximal acceptable properties.\n :returns: LaserBeam object.\n \"\"\"\n return LaserBeamGenerator(min_laser_beam, max_laser_beam, max_step=0.1)\n\n\n@pytest.fixture(name=\"random_image\")\ndef fixture_random_image(image_shape) -> Any:\n \"\"\"\n Random image.\n :returns: random image.\n \"\"\"\n return np.random.random(image_shape)\n\n\n@pytest.fixture(name=\"accurate_class\")\ndef fixture_accurate_class() -> int:\n \"\"\"\n Accurate class.\n :returns: Accurate class.\n \"\"\"\n return 0\n\n\n@pytest.fixture(name=\"adversarial_class\")\ndef fixture_adversarial_class() -> int:\n \"\"\"\n Adversarial class.\n :returns: Adversarial class.\n \"\"\"\n return 1\n\n\n@pytest.fixture(name=\"model\")\ndef fixture_model(adversarial_class) -> Any:\n \"\"\"\n Artificial model that allows execute predict function.\n :returns: Artificial ML Model\n \"\"\"\n\n class ArtificialModel:\n \"\"\"\n Model that simulates behaviour of a real ML model.\n \"\"\"\n\n def __init__(self) -> None:\n self.x = None\n self.channels_first = False\n\n def predict(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n Predict class of an image.\n :returns: prediction scores for arrays\n \"\"\"\n self.x = x\n arr = np.zeros(42)\n arr[adversarial_class] = 1\n return np.array([arr])\n\n return ArtificialModel()\n\n\n@pytest.fixture(name=\"attack\")\ndef fixture_attack(model) -> LaserBeamAttack:\n \"\"\"\n Laser beam attack\n :returns: Laser beam attack\n \"\"\"\n return LaserBeamAttack(estimator=model, iterations=50, max_laser_beam=(780, 3.14, 32, 32))\n\n\ndef test_if_random_laser_beam_is_in_ranges(laser_generator, min_laser_beam, max_laser_beam, less_or_equal, art_warning):\n \"\"\"\n Test if random laser beam is in defined ranges.\n \"\"\"\n try:\n for _ in range(100):\n random_laser = laser_generator.random()\n np.testing.assert_array_compare(less_or_equal, random_laser.to_numpy(), max_laser_beam.to_numpy())\n np.testing.assert_array_compare(less_or_equal, min_laser_beam.to_numpy(), random_laser.to_numpy())\n except ARTTestException as _e:\n art_warning(_e)\n\n\ndef test_laser_beam_update(laser_generator, min_laser_beam, max_laser_beam, not_close, less_or_equal, art_warning):\n \"\"\"\n Test if laser beam update is conducted correctly.\n \"\"\"\n try:\n for _ in range(5):\n random_laser = laser_generator.random()\n\n arr1 = random_laser.to_numpy()\n arr2 = laser_generator.update_params(random_laser).to_numpy()\n np.testing.assert_array_compare(not_close, arr1, arr2)\n np.testing.assert_array_compare(less_or_equal, arr2, max_laser_beam.to_numpy())\n np.testing.assert_array_compare(less_or_equal, min_laser_beam.to_numpy(), arr2)\n np.testing.assert_array_compare(less_or_equal, np.zeros_like(arr1), arr1)\n except ARTTestException as _e:\n art_warning(_e)\n\n\ndef test_image_generator(laser_generator, image_shape, art_warning, not_close):\n \"\"\"\n Test generating images.\n \"\"\"\n try:\n img_gen = ImageGenerator()\n for _ in range(5):\n laser = laser_generator.random()\n arr1 = img_gen.generate_image(laser, image_shape)\n np.testing.assert_array_compare(not_close, arr1, np.zeros_like(arr1))\n except ARTTestException as _e:\n art_warning(_e)\n\n\ndef test_attack_generate(attack, random_image, accurate_class, not_close, art_warning):\n \"\"\"\n Test attacking neural network and generating adversarial images.\n \"\"\"\n try:\n adv_image = attack.generate(np.expand_dims(random_image, 0), np.array([accurate_class]))[0]\n\n assert adv_image.shape == random_image.shape, \"Image shapes are not the same\"\n np.testing.assert_array_compare(not_close, random_image, adv_image)\n except ARTTestException as _e:\n art_warning(_e)\n\n\ndef test_attack_generate_params(attack, random_image, accurate_class, art_warning):\n \"\"\"\n Test attacking neural network and generating adversarial objects.\n \"\"\"\n try:\n adv_laser, adv_class = attack.generate_parameters(np.expand_dims(random_image, 0), np.array([accurate_class]))[\n 0\n ]\n\n assert adv_class != accurate_class\n assert adv_laser is not None\n except ARTTestException as _e:\n art_warning(_e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_lowprofool.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom sklearn import datasets\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom scipy.stats import pearsonr\n\nfrom art.attacks.evasion import LowProFool\nfrom art.estimators.classification.scikitlearn import ScikitlearnLogisticRegression\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.estimators.classification.scikitlearn import ScikitlearnSVC\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture\ndef splitter():\n return StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)\n\n\n@pytest.fixture\ndef iris_dataset(splitter):\n iris = datasets.load_iris()\n design_matrix = pd.DataFrame(data=iris[\"data\"], columns=iris[\"feature_names\"])\n labels = pd.Series(data=iris[\"target\"])\n\n scaler = StandardScaler().fit(design_matrix)\n design_matrix = pd.DataFrame(data=scaler.transform(design_matrix), columns=design_matrix.columns)\n clip_values = (design_matrix.min(), design_matrix.max())\n\n [[train_idx, valid_idx]] = list(splitter.split(design_matrix, labels))\n x_train = design_matrix.iloc[train_idx].copy()\n x_valid = design_matrix.iloc[valid_idx].copy()\n y_train = labels.iloc[train_idx].copy()\n y_valid = labels.iloc[valid_idx].copy()\n\n return (x_train, y_train, x_valid, y_valid), scaler, clip_values\n\n\n@pytest.fixture\ndef breast_cancer_dataset(splitter):\n cancer = datasets.load_breast_cancer()\n design_matrix = pd.DataFrame(data=cancer[\"data\"], columns=cancer[\"feature_names\"])\n labels = pd.Series(data=cancer[\"target\"])\n\n scaler = StandardScaler().fit(design_matrix)\n design_matrix = pd.DataFrame(data=scaler.transform(design_matrix), columns=design_matrix.columns)\n clip_values = (design_matrix.min(), design_matrix.max())\n\n [[train_idx, valid_idx]] = list(splitter.split(design_matrix, labels))\n x_train = design_matrix.iloc[train_idx].copy()\n x_valid = design_matrix.iloc[valid_idx].copy()\n y_train = labels.iloc[train_idx].copy()\n y_valid = labels.iloc[valid_idx].copy()\n\n return (x_train, y_train, x_valid, y_valid), scaler, clip_values\n\n\n@pytest.fixture\ndef wine_dataset(splitter):\n wine = datasets.load_wine()\n design_matrix = pd.DataFrame(data=wine[\"data\"], columns=wine[\"feature_names\"])\n labels = pd.Series(data=wine[\"target\"])\n\n scaler = StandardScaler().fit(design_matrix)\n design_matrix = pd.DataFrame(data=scaler.transform(design_matrix), columns=design_matrix.columns)\n clip_values = (design_matrix.min(), design_matrix.max())\n\n [[train_idx, valid_idx]] = list(splitter.split(design_matrix, labels))\n x_train = design_matrix.iloc[train_idx].copy()\n x_valid = design_matrix.iloc[valid_idx].copy()\n y_train = labels.iloc[train_idx].copy()\n y_valid = labels.iloc[valid_idx].copy()\n\n return (x_train, y_train, x_valid, y_valid), scaler, clip_values\n\n\nclass NeuralNetwork:\n def __init__(self):\n self.loss_fn = torch.nn.MSELoss(reduction=\"sum\")\n\n @staticmethod\n def get_nn_model(input_dimensions, output_dimensions, hidden_neurons):\n return torch.nn.Sequential(\n nn.Linear(input_dimensions, hidden_neurons),\n nn.ReLU(),\n nn.Linear(hidden_neurons, output_dimensions),\n nn.Softmax(dim=1),\n )\n\n def train_nn(self, nn_model, x, y, learning_rate, epochs):\n optimizer = optim.SGD(nn_model.parameters(), lr=learning_rate)\n\n for _ in range(epochs):\n y_pred = nn_model.forward(x)\n loss = self.loss_fn(y_pred, y)\n nn_model.zero_grad()\n loss.backward()\n\n optimizer.step()\n\n\n@pytest.mark.only_with_platform(\"scikitlearn\")\ndef test_general_iris_lr(iris_dataset):\n \"\"\"\n Check whether the produced adversaries are correct,\n given Logistic Regression model and iris flower dataset.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = iris_dataset\n\n # Setup classifier.\n lr_clf = LogisticRegression(penalty=None)\n lr_clf.fit(x_train, y_train)\n clf_slr = ScikitlearnLogisticRegression(model=lr_clf, clip_values=clip_values)\n\n lpf_slr = LowProFool(classifier=clf_slr, n_steps=25, eta=0.02, lambd=1.5)\n lpf_slr.fit_importances(x_train, y_train)\n\n sample = x_valid\n\n # Draw targets different from the original labels and then save as one-hot encoded.\n target = np.eye(3)[np.array(y_valid.apply(lambda x: np.random.choice([i for i in [0, 1, 2] if i != x])))]\n\n adversaries = lpf_slr.generate(x=sample, y=target)\n expected = np.argmax(target, axis=1)\n predicted = np.argmax(lr_clf.predict_proba(adversaries), axis=1)\n correct = expected == predicted\n\n success_rate = np.sum(correct) / correct.shape[0]\n expected = 0.6\n\n logger.info(\n \"[Irises, Scikit-learn Logistic Regression] success rate of adversarial attack (expected >{:.2f}): \"\n \"{:.2f}%\".format(expected * 100, success_rate * 100)\n )\n assert success_rate > expected\n\n with pytest.raises(ValueError):\n _ = lpf_slr.generate(x=sample, y=None)\n with pytest.raises(ValueError):\n _ = lpf_slr.generate(x=sample, y=np.ones((sample.shape[0], 11)))\n with pytest.raises(ValueError):\n _ = lpf_slr.generate(x=np.ones((sample.shape[0], 11)), y=target)\n\n\n@pytest.mark.only_with_platform(\"scikitlearn\")\ndef test_general_wines_lr(wine_dataset):\n \"\"\"\n Check whether the produced adversaries are correct,\n given Logistic Regression classifier and sklearn wines dataset.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = wine_dataset\n\n # Setup classifier\n lr_clf = LogisticRegression(penalty=None)\n lr_clf.fit(x_train, y_train)\n clf_slr = ScikitlearnLogisticRegression(model=lr_clf, clip_values=clip_values)\n\n lpf_slr = LowProFool(classifier=clf_slr, n_steps=80, eta=0.1, lambd=1.25)\n lpf_slr.fit_importances(x_train, y_train)\n\n sample = x_valid\n # Draw targets different from original labels and then save as one-hot encoded.\n target = np.eye(3)[np.array(y_valid.apply(lambda x: np.random.choice([i for i in [0, 1, 2] if i != x])))]\n\n adversaries = lpf_slr.generate(x=sample, y=target)\n expected = np.argmax(target, axis=1)\n predicted = np.argmax(lr_clf.predict_proba(adversaries), axis=1)\n correct = expected == predicted\n\n success_rate = np.sum(correct) / correct.shape[0]\n expected = 0.6\n\n logger.info(\n \"[Wines, Scikit-learn Logistic Regression] success rate of adversarial attack (expected >{:.2f}):\"\n \" {:.2f}%\".format(expected * 100, success_rate * 100)\n )\n assert success_rate > expected\n\n\n@pytest.mark.only_with_platform(\"scikitlearn\")\ndef test_general_cancer_lr(breast_cancer_dataset):\n \"\"\"\n Check whether the produced adversaries are correct,\n given Logistic Regression classifier and breast cancer wisconsin dataset.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = breast_cancer_dataset\n\n # Setup classifier\n lr_clf = LogisticRegression(penalty=None)\n lr_clf.fit(x_train, y_train)\n clf_slr = ScikitlearnLogisticRegression(model=lr_clf, clip_values=clip_values)\n\n lpf_slr = LowProFool(classifier=clf_slr, n_steps=30, eta=0.02, lambd=1.5)\n lpf_slr.fit_importances(x_train, y_train)\n\n sample = x_valid\n\n # Draw targets different from original labels and then save as one-hot encoded.\n target = np.eye(2)[np.array(y_valid.apply(lambda x: np.random.choice([i for i in [0, 1] if i != x])))]\n\n adversaries = lpf_slr.generate(x=sample, y=target)\n expected = np.argmax(target, axis=1)\n predicted = np.argmax(lr_clf.predict_proba(adversaries), axis=1)\n correct = expected == predicted\n\n success_rate = np.sum(correct) / correct.shape[0]\n expected = 0.6\n\n logger.info(\n \"[Breast cancer, Scikit-learn Logistic Regression] success rate of adversarial attack (expected >{:.2f}): \"\n \"{:.2f}%\".format(expected * 100, success_rate * 100)\n )\n assert success_rate > expected\n\n\ndef test_general_iris_nn(iris_dataset):\n \"\"\"\n Check whether the produced adversaries are correct,\n given Neural Network classifier and iris flower dataset.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = iris_dataset\n\n x = Variable(torch.FloatTensor(np.array(x_train)))\n y = Variable(torch.FloatTensor(np.eye(3)[y_train]))\n\n neural_network = NeuralNetwork()\n nn_model_irises = neural_network.get_nn_model(4, 3, 10)\n neural_network.train_nn(nn_model_irises, x, y, 1e-4, 1000)\n\n est_nn_iris = PyTorchClassifier(\n model=nn_model_irises, loss=neural_network.loss_fn, input_shape=(4,), nb_classes=3, clip_values=clip_values\n )\n\n lpf_nn = LowProFool(classifier=est_nn_iris, eta=5, lambd=0.2, eta_decay=0.9)\n\n lpf_nn.fit_importances(x_valid, y_valid)\n\n target = np.eye(3)[np.array(y_valid.apply(lambda x: np.random.choice([i for i in range(3) if i != x])))]\n\n # Use of LowProFool\n adversaries = lpf_nn.generate(x=x_valid, y=target)\n expected = np.argmax(target, axis=1)\n\n x = Variable(torch.from_numpy(adversaries.astype(np.float32)))\n predicted = np.argmax(nn_model_irises.forward(x).detach().numpy(), axis=1)\n\n # Test\n correct = expected == predicted\n success_rate = np.sum(correct) / correct.shape[0]\n expected = 0.6\n logger.info(\n \"[Irises, PyTorch neural network] success rate of adversarial attack (expected >{:.2f}): \"\n \"{:.2f}%\".format(expected * 100, success_rate * 100)\n )\n assert success_rate > expected\n\n\n@pytest.mark.only_with_platform(\"scikitlearn\")\ndef test_general_cancer_svc(breast_cancer_dataset):\n \"\"\"\n Check whether the produced adversaries are correct,\n given SVC and breast cancer wisconsin dataset.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = breast_cancer_dataset\n\n svc_clf = SVC()\n svc_clf.fit(x_train, y_train)\n scaled_clip_values_cancer = (-1.0, 1.0)\n clf_svc = ScikitlearnSVC(model=svc_clf, clip_values=scaled_clip_values_cancer)\n lpf_svc = LowProFool(classifier=clf_svc, n_steps=15, eta=15, lambd=1.75, eta_decay=0.985, verbose=False)\n lpf_svc.fit_importances(x_train, y_train)\n n_classes = lpf_svc.n_classes\n targets = np.eye(n_classes)[\n np.array(y_valid.apply(lambda x: np.random.choice([i for i in range(n_classes) if i != x])))\n ]\n # Generate adversaries\n adversaries = lpf_svc.generate(x=x_valid, y=targets)\n\n # Check the success rate\n expected = np.argmax(targets, axis=1)\n predicted = np.argmax(clf_svc.predict(adversaries), axis=1)\n correct = expected == predicted\n\n success_rate = np.sum(correct) / correct.shape[0]\n expected = 0.6\n\n logger.info(\n \"[Breast cancer, Scikit-learn SVC] success rate of adversarial attack (expected >{:.2f}): \"\n \"{:.2f}%\".format(expected * 100, success_rate * 100)\n )\n assert success_rate > expected\n\n\n@pytest.mark.only_with_platform(\"scikitlearn\")\ndef test_fit_importances(iris_dataset):\n \"\"\"\n Check whether feature importance is calculated properly.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = iris_dataset\n\n def pearson_correlations(x, y):\n correlations = [pearsonr(x[:, col], y)[0] for col in range(x.shape[1])]\n absolutes = np.abs(np.array(correlations))\n result = absolutes / np.power(np.sum(absolutes**2), 0.5)\n return result\n\n # Setup classifier\n lr_clf = LogisticRegression(penalty=None)\n lr_clf.fit(x_train, y_train)\n clf_slr = ScikitlearnLogisticRegression(model=lr_clf, clip_values=clip_values)\n\n # User defined vector\n vector = pearson_correlations(np.array(x_train), np.array(y_train))\n\n # 3 different instances of LowProFool, using 3 different ways of specifying importance\n\n # Default version - using pearson correlation under the hood\n lpf_slr_default = LowProFool(classifier=clf_slr, n_steps=45, eta=0.02, lambd=1.5, importance=\"pearson\")\n\n # Predefined vector, passed in LowProFool initialization\n lpf_slr_vec = LowProFool(classifier=clf_slr, n_steps=45, eta=0.02, lambd=1.5, importance=vector)\n\n # User defined function\n lpf_slr_fun = LowProFool(classifier=clf_slr, n_steps=45, eta=0.02, lambd=1.5, importance=pearson_correlations)\n\n lpf_slr_default.fit_importances(x_train, y_train)\n lpf_slr_vec.fit_importances(x_train, y_train)\n lpf_slr_fun.fit_importances(x_train, y_train, normalize=False)\n\n importance_default = lpf_slr_default.importance_vec\n importance_vec_init = lpf_slr_vec.importance_vec\n importance_function = lpf_slr_fun.importance_vec\n\n # Predefined vector passed while fitting\n lpf_slr_default.fit_importances(x_train, y_train, importance_array=vector)\n importance_vec_fit = lpf_slr_default.importance_vec\n\n # Vector normalization\n vector_norm = vector / np.sum(vector)\n\n is_default_valid = (vector_norm == importance_default).all()\n is_custom_fun_valid = (vector == importance_function).all()\n is_vec_init_valid = (vector_norm == importance_vec_init).all()\n is_vec_fit_valid = (vector_norm == importance_vec_fit).all()\n\n logger.info(\"[Iris flower, Scikit-learn Logistic Regression] Importance fitting test:\")\n if not is_default_valid:\n logger.info(\"Fitting importance by default is invalid\")\n elif not is_custom_fun_valid:\n logger.info(\"Fitting importance with custom function is invalid\")\n elif not is_vec_init_valid:\n logger.info(\"Fitting importance with vector provided in initializer is invalid\")\n elif not is_vec_fit_valid:\n logger.info(\"Fitting importance with vector provided in fit_importances() is invalid\")\n else:\n logger.info(\"Fitting importance with all available methods went successfully\")\n\n assert is_default_valid\n assert is_custom_fun_valid\n assert is_vec_init_valid\n assert is_vec_fit_valid\n\n\n@pytest.mark.only_with_platform(\"scikitlearn\")\ndef test_clipping(iris_dataset):\n \"\"\"\n Check weather adversaries are clipped properly.\n \"\"\"\n (x_train, y_train, x_valid, y_valid), _, clip_values = iris_dataset\n\n # Setup classifier\n lr_clf = LogisticRegression(penalty=None)\n lr_clf.fit(x_train, y_train)\n\n # Dataset min-max clipping values\n bottom_min, top_max = clip_values\n clf_slr_min_max = ScikitlearnLogisticRegression(model=lr_clf, clip_values=(bottom_min, top_max))\n\n # Clip values\n bottom_custom = -3\n top_custom = 3\n clf_slr_custom = ScikitlearnLogisticRegression(model=lr_clf, clip_values=(bottom_custom, top_custom))\n\n # Setting up LowProFool classes with different hyperparameters\n lpf_min_max_default = LowProFool(classifier=clf_slr_min_max, n_steps=45, eta=0.02, lambd=1.5)\n lpf_min_max_high_eta = LowProFool(classifier=clf_slr_min_max, n_steps=45, eta=100000, lambd=1.5)\n lpf_custom_default = LowProFool(classifier=clf_slr_custom, n_steps=45, eta=0.02, lambd=1.5)\n lpf_custom_high_eta = LowProFool(classifier=clf_slr_custom, n_steps=45, eta=100000, lambd=1.5)\n\n lpf_min_max_default.fit_importances(x_train, y_train)\n lpf_min_max_high_eta.fit_importances(x_train, y_train)\n lpf_custom_default.fit_importances(x_train, y_train)\n lpf_custom_high_eta.fit_importances(x_train, y_train)\n\n # Generating adversaries\n sample = np.array([[5.5, 2.4, 3.7, 1.0]])\n target = np.array([[0.0, 0.0, 1.0]])\n\n adversaries_min_max_default = lpf_min_max_default.generate(x=sample, y=target)\n adversaries_min_max_high_eta = lpf_min_max_high_eta.generate(x=sample, y=target)\n adversaries_custom_default = lpf_custom_default.generate(x=sample, y=target)\n adversaries_custom_high_eta = lpf_custom_high_eta.generate(x=sample, y=target)\n\n # Checking whether adversaries were clipped properly\n eps = 1e-6\n is_valid_1 = ((bottom_min - eps).to_numpy() <= adversaries_min_max_default).all() and (\n (top_max + eps).to_numpy() >= adversaries_min_max_default\n ).all()\n is_valid_2 = ((bottom_min - eps).to_numpy() <= adversaries_min_max_high_eta).all() and (\n (top_max + eps).to_numpy() >= adversaries_min_max_high_eta\n ).all()\n is_valid_3 = ((bottom_custom - eps) <= adversaries_custom_default).all() and (\n (top_custom + eps) >= adversaries_custom_default\n ).all()\n is_valid_4 = (bottom_custom - eps <= adversaries_custom_high_eta).all() and (\n top_custom + eps >= adversaries_custom_high_eta\n ).all()\n\n is_clipping_valid = is_valid_1 and is_valid_2 and is_valid_3 and is_valid_4\n if is_clipping_valid:\n logger.info(\"[Iris flower, Scikit-learn Logistic Regression] Clipping is valid.\")\n else:\n logger.info(\"[Iris flower, Scikit-learn Logistic Regression] Clipping is invalid.\")\n\n assert is_valid_1\n assert is_valid_2\n assert is_valid_3\n assert is_valid_4\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(LowProFool)\n\n with pytest.raises(ValueError):\n lpf = LowProFool(classifier)\n lpf.n_classes = -1\n lpf._check_params()\n\n with pytest.raises(ValueError):\n lpf = LowProFool(classifier)\n lpf.n_features = -1\n lpf._check_params()\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, n_steps=5.0)\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, n_steps=-5)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, threshold=5)\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, threshold=-5.0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, lambd=\"test\")\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, lambd=-5.0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, eta=\"test\")\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, eta=-5.0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, eta_decay=\"test\")\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, eta_decay=-5.0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, eta_min=\"test\")\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, eta_min=-5.0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, norm=\"test\")\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, norm=-5.0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, importance=0)\n\n with pytest.raises(ValueError):\n _ = LowProFool(classifier, verbose=\"test\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_momentum_iterative_method.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import MomentumIterativeMethod\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"tensorflow\") # See issue #2439\ndef test_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, framework):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n classifier = image_dl_estimator_for_attack(MomentumIterativeMethod)\n\n attack = MomentumIterativeMethod(classifier, eps=0.3, eps_step=0.1, decay=1.0, max_iter=10)\n x_train_mnist_adv = attack.generate(x=x_train_mnist)\n\n assert np.mean(x_train_mnist) == pytest.approx(0.12659499049186707, 0.01)\n assert np.max(np.abs(x_train_mnist - x_train_mnist_adv)) == pytest.approx(0.3)\n expected_mean_diff = pytest.approx(0.1288, 0.003)\n assert np.mean(np.abs(x_train_mnist - x_train_mnist_adv)) == expected_mean_diff\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\") # See issue #2439\ndef test_images_targeted(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, framework):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n classifier = image_dl_estimator_for_attack(MomentumIterativeMethod)\n\n attack = MomentumIterativeMethod(classifier, eps=0.3, eps_step=0.1, decay=1.0, max_iter=10)\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.max(np.abs(x_train_mnist - x_train_mnist_adv)) == pytest.approx(0.3)\n expected_mean_diff = pytest.approx(0.1077, 0.01)\n assert np.mean(np.abs(x_train_mnist - x_train_mnist_adv)) == expected_mean_diff\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(MomentumIterativeMethod)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, eps=-1)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, eps=1, eps_step=-1)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, decay=-1)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, targeted=\"true\")\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, batch_size=0)\n\n with pytest.raises(ValueError):\n _ = MomentumIterativeMethod(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(MomentumIterativeMethod, [BaseEstimator, LossGradientsMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_over_the_air.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\nimport torch\n\nfrom art.attacks.evasion.over_the_air_flickering.over_the_air_flickering_pytorch import OverTheAirFlickeringPyTorch\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.fc = torch.nn.Linear(12 * 299 * 299 * 3, 101)\n\n def forward(self, x):\n x = x.view(-1, 12 * 299 * 299 * 3)\n logit_output = self.fc(x)\n return logit_output.view(-1, 101)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_get_loss_gradients(art_warning):\n try:\n\n x_train = np.ones((2, 12, 299, 299, 3)).astype(np.float32)\n y_train = np.zeros((2, 101))\n y_train[:, 1] = 1\n\n model = Model()\n classifier = PyTorchClassifier(\n model=model, loss=None, input_shape=x_train.shape[1:], nb_classes=y_train.shape[1]\n )\n attack = OverTheAirFlickeringPyTorch(classifier=classifier, verbose=False)\n\n gradients = attack._get_loss_gradients(\n x=torch.from_numpy(x_train), y=torch.from_numpy(y_train), perturbation=torch.zeros(x_train.shape)\n )\n\n assert gradients.shape == (2, 12, 1, 1, 3)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate(art_warning):\n try:\n\n x_train = np.ones((2, 12, 299, 299, 3)).astype(np.float32)\n y_train = np.zeros((2, 101))\n y_train[:, 1] = 1\n\n model = Model()\n classifier = PyTorchClassifier(\n model=model, loss=None, input_shape=x_train.shape[1:], nb_classes=y_train.shape[1], clip_values=(0, 1)\n )\n attack = OverTheAirFlickeringPyTorch(classifier=classifier, max_iter=1, verbose=False)\n\n x_train_adv = attack.generate(x=x_train, y=y_train)\n\n assert x_train.shape == x_train_adv.shape\n assert np.min(x_train_adv) >= 0.0\n assert np.max(x_train_adv) <= 1.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(OverTheAirFlickeringPyTorch)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, eps_step=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, eps_step=-0.5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, max_iter=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, max_iter=-5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, beta_0=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, beta_0=-0.5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, beta_1=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, beta_1=-0.5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, beta_2=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, beta_2=-0.5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, loss_margin=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, loss_margin=-0.5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, batch_size=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, batch_size=-5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, start_frame_index=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, start_frame_index=-0.5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, num_frames=5.0)\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, num_frames=-5)\n\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, round_samples=\"test\")\n with pytest.raises(ValueError):\n _ = OverTheAirFlickeringPyTorch(classifier, round_samples=-5)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n OverTheAirFlickeringPyTorch, [BaseEstimator, LossGradientsMixin, ClassifierMixin]\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_pe_malware_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nimport pytest\nimport tensorflow as tf\nimport numpy as np\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom art.attacks.evasion.pe_malware_attack import MalwareGDTensorFlow\nfrom art.estimators.classification import TensorFlowV2Classifier\n\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.utils import ARTTestException\n\n\n@pytest.fixture()\ndef fix_get_synthetic_data():\n \"\"\"\n As real malware is hard to share, generate random data of the correct size\n \"\"\"\n # generate dummy data\n padding_char = 256\n maxlen = 2**20\n\n # batch of 5 datapoints\n synthetic_data = np.ones((5, maxlen), dtype=np.uint16) * padding_char\n\n size_of_original_files = [\n int(maxlen * 0.1), # 1 sample significantly smaller than the maxlen\n int(maxlen * 1.5), # 1 sample larger then maxlen\n int(maxlen * 0.95), # 1 sample close to the maximum of the maxlen\n int(maxlen), # 1 sample at the maxlen\n int(maxlen),\n ] # 1 sample at the maxlen, this will be assigned a benign label and\n # should not be perturbed by the attack.\n\n # two class option, later change to binary when ART is generally updated.\n y = np.zeros((5, 1))\n y[0:4] = 1 # assign the first 4 datapoints to be labeled as malware\n\n # fill in with random numbers\n for i, size in enumerate(size_of_original_files):\n if size > maxlen:\n size = maxlen\n synthetic_data[i, 0:size] = np.random.randint(low=0, high=256, size=(1, size))\n\n # set the DOS header values:\n synthetic_data[:, 0:2] = [77, 90]\n synthetic_data[:, int(0x3C) : int(0x40)] = 0 # zero the pointer location\n synthetic_data[:, int(0x3C)] = 44 # put in a dummy pointer\n synthetic_data[:, int(0x3C) + 1] = 1 # put in a dummy pointer\n return synthetic_data, y, np.asarray(size_of_original_files)\n\n\n@pytest.fixture()\ndef fix_make_dummy_model():\n \"\"\"\n Create a random model for testing\n \"\"\"\n\n def get_prediction_model(param_dic):\n \"\"\"\n Model going from embeddings to predictions, so we can easily optimise the embedding malware embedding.\n Needs to have the same structure as the target model.\n Populated here with \"standard\" parameters.\n \"\"\"\n inp = tf.keras.layers.Input(\n shape=(\n param_dic[\"maxlen\"],\n param_dic[\"embedding_size\"],\n )\n )\n filt = tf.keras.layers.Conv1D(\n filters=128,\n kernel_size=500,\n strides=500,\n use_bias=True,\n activation=\"relu\",\n padding=\"valid\",\n name=\"filt_layer\",\n )(inp)\n attn = tf.keras.layers.Conv1D(\n filters=128,\n kernel_size=500,\n strides=500,\n use_bias=True,\n activation=\"sigmoid\",\n padding=\"valid\",\n name=\"attn_layer\",\n )(inp)\n gated = tf.keras.layers.Multiply()([filt, attn])\n feat = tf.keras.layers.GlobalMaxPooling1D()(gated)\n dense = tf.keras.layers.Dense(128, activation=\"relu\", name=\"dense_layer\")(feat)\n output = tf.keras.layers.Dense(1, name=\"output_layer\")(dense)\n return tf.keras.Model(inputs=inp, outputs=output)\n\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n prediction_model = get_prediction_model(param_dic)\n\n model_weights = np.random.normal(loc=0, scale=1.0, size=(257, 8))\n\n classifier = TensorFlowV2Classifier(\n model=prediction_model,\n nb_classes=2,\n loss_object=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n input_shape=(param_dic[\"maxlen\"], param_dic[\"embedding_size\"]),\n )\n\n return classifier, model_weights\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_no_perturbation(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n Assert that with 0 perturbation the data is unmodified\n \"\"\"\n try:\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n # First check: with no perturbation the malware of sufficient size, and benign files, should be unperturbed\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0], embedding_weights=fix_make_dummy_model[1], l_0=0, param_dic=param_dic\n )\n\n attack.l_0 = 0\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n adv_x, adv_y, adv_sizes = attack.pull_out_valid_samples(x, y, size_of_files)\n\n # We should only have 3 files as the following cannot be converted to valid adv samples:\n # 2nd datapoint (file too large to support any modifications)\n # 5th datapoint (benign file)\n\n assert len(adv_x) == 3\n\n adv_x = attack.generate(adv_x, adv_y, adv_sizes)\n\n j = 0\n for i in range(len(x)):\n if i in [0, 2, 3]:\n assert np.array_equal(adv_x[j], x[i])\n j += 1\n else:\n assert np.array_equal(x[i], fix_get_synthetic_data[0][i])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_append_attack(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n Check append attack wih a given l0 budget\n \"\"\"\n try:\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n l0_budget = 1250\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0],\n embedding_weights=fix_make_dummy_model[1],\n l_0=l0_budget,\n param_dic=param_dic,\n )\n\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n adv_x, adv_y, adv_sizes = attack.pull_out_valid_samples(x, y, size_of_files)\n\n # We should only have 2 files as the following cannot be converted to valid adv samples:\n # 2nd datapoint (file too large to support any modifications)\n # 4th datapoint (file too large to support append attacks)\n # 5th datapoint (benign file)\n\n assert len(adv_x) == 2\n\n adv_x = attack.generate(adv_x, adv_y, adv_sizes)\n\n j = 0\n for i, size in enumerate(fix_get_synthetic_data[2]):\n if i in [0, 2]:\n assert np.array_equal(adv_x[j, :size], fix_get_synthetic_data[0][i, :size])\n assert not np.array_equal(\n adv_x[j, size : size + l0_budget], fix_get_synthetic_data[0][i, size : size + l0_budget]\n )\n assert np.array_equal(adv_x[j, size + l0_budget :], fix_get_synthetic_data[0][i, size + l0_budget :])\n j += 1\n else:\n assert np.array_equal(x[i], fix_get_synthetic_data[0][i])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_slack_attacks(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n Testing modification of certain regions in the PE file\n \"\"\"\n try:\n # Third check: Slack insertion attacks.\n\n def generate_synthetic_slack_regions(size):\n \"\"\"\n Generate 4 slack regions per sample, each of size 250.\n \"\"\"\n\n batch_of_slack_starts = []\n batch_of_slack_sizes = []\n\n for _ in range(5):\n size_of_slack = []\n start_of_slack = []\n start = 0\n for _ in range(4):\n start += 1000\n start_of_slack.append(start)\n size_of_slack.append(size)\n batch_of_slack_starts.append(start_of_slack)\n batch_of_slack_sizes.append(size_of_slack)\n return batch_of_slack_starts, batch_of_slack_sizes\n\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n # First check: with no perturbation the malware of sufficient size, and benign files, should be unperturbed\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0], embedding_weights=fix_make_dummy_model[1], l_0=0, param_dic=param_dic\n )\n\n l0_budget = 1250\n attack.l_0 = l0_budget\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n batch_of_section_starts, batch_of_section_sizes = generate_synthetic_slack_regions(size=250)\n adv_x, adv_y, adv_sizes, batch_of_section_starts, batch_of_section_sizes = attack.pull_out_valid_samples(\n x,\n y,\n sample_sizes=size_of_files,\n perturb_starts=batch_of_section_starts,\n perturb_sizes=batch_of_section_sizes,\n )\n\n # We should only have 2 files as the following cannot be converted to valid adv samples:\n # 2nd datapoint (file too large to support any modifications)\n # 4th datapoint (attack requires appending 250 bytes to end of file which this datapoint cannot support)\n # 5th datapoint (benign file)\n assert len(adv_x) == 2\n\n adv_x = attack.generate(\n adv_x, adv_y, adv_sizes, perturb_sizes=batch_of_section_sizes, perturb_starts=batch_of_section_starts\n )\n\n j = 0\n for i, size in enumerate(fix_get_synthetic_data[2]):\n if i in [0, 2]:\n slack_starts = batch_of_section_starts[j]\n slack_sizes = batch_of_section_sizes[j]\n beginning_pos = 0\n total_perturbation = 0\n for slack_start, slack_size in zip(slack_starts, slack_sizes):\n assert np.array_equal(\n adv_x[j, beginning_pos:slack_start], fix_get_synthetic_data[0][i, beginning_pos:slack_start]\n )\n\n assert not np.array_equal(\n adv_x[j, slack_start : slack_start + slack_size],\n fix_get_synthetic_data[0][i, slack_start : slack_start + slack_size],\n )\n beginning_pos = slack_start + slack_size\n total_perturbation += slack_size\n\n # from the last slack region to end of file\n assert np.array_equal(adv_x[j, beginning_pos:size], fix_get_synthetic_data[0][i, beginning_pos:size])\n remaining_perturbation = l0_budget - total_perturbation\n assert remaining_perturbation == 250\n\n # append portion of the attack has been conducted\n assert not np.array_equal(\n adv_x[j, size : size + remaining_perturbation],\n fix_get_synthetic_data[0][i, size : size + remaining_perturbation],\n )\n\n # from end of append to end of datapoint\n assert np.array_equal(\n adv_x[j, size + remaining_perturbation :],\n fix_get_synthetic_data[0][i, size + remaining_perturbation :],\n )\n\n j += 1\n else:\n assert np.array_equal(x[i], fix_get_synthetic_data[0][i])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_large_append(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n Testing with very large perturbation budgets\n \"\"\"\n # Fourth check append large perturbation\n try:\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n # First check: with no perturbation the malware of sufficient size, and benign files, should be unperturbed\n l0_budget = int(((2**20) * 0.2))\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0],\n embedding_weights=fix_make_dummy_model[1],\n l_0=l0_budget,\n param_dic=param_dic,\n )\n\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n adv_x, adv_y, adv_sizes = attack.pull_out_valid_samples(x, y, sample_sizes=size_of_files)\n # We should only have one datapoint that can support an append perturbation of this size\n assert len(adv_x) == 1\n\n adv_x = attack.generate(adv_x, adv_y, adv_sizes)\n\n j = 0\n for i, size in enumerate(fix_get_synthetic_data[2]):\n if i == 0:\n assert np.array_equal(adv_x[j, :size], fix_get_synthetic_data[0][i, :size])\n assert not np.array_equal(\n adv_x[j, size : size + l0_budget], fix_get_synthetic_data[0][i, size : size + l0_budget]\n )\n assert np.array_equal(adv_x[j, size + l0_budget :], fix_get_synthetic_data[0][i, size + l0_budget :])\n else:\n assert np.array_equal(x[i], fix_get_synthetic_data[0][i])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_dos_header_attack(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n Test the DOS header attack modifies the correct regions\n \"\"\"\n # 5th check: DOS header attack\n try:\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n # First check: with no perturbation the malware of sufficient size, and benign files, should be unperturbed\n l0_budget = 290\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0],\n embedding_weights=fix_make_dummy_model[1],\n l_0=l0_budget,\n param_dic=param_dic,\n )\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n dos_starts, dos_sizes = attack.get_dos_locations(x)\n\n adv_x, adv_y, adv_sizes, batch_of_section_starts, batch_of_section_sizes = attack.pull_out_valid_samples(\n x, y, sample_sizes=size_of_files, perturb_starts=dos_starts, perturb_sizes=dos_sizes\n )\n\n # should have 3 files. Samples which are excluded are:\n # 2nd datapoint (file too large to support any modifications)\n # 5th datapoint (benign file)\n\n assert len(adv_x) == 3\n\n adv_x = attack.generate(\n adv_x, adv_y, adv_sizes, perturb_sizes=batch_of_section_sizes, perturb_starts=batch_of_section_starts\n )\n\n j = 0\n for i in range(len(fix_get_synthetic_data[2])):\n if i in [0, 2, 3]:\n assert np.array_equal(adv_x[j, 0:2], [77, 90])\n\n # we should have 58 bytes that were perturbed between the magic number and the pointer\n assert not np.array_equal(adv_x[j, 2 : int(0x3C)], fix_get_synthetic_data[0][i, 2 : int(0x3C)])\n\n # dummy pointer should be unchanged\n assert np.array_equal(adv_x[j, int(0x3C) : int(0x3C) + 4], [44, 1, 0, 0])\n\n # the remaining perturbation 290 - 58 = 232 is in the rest of the DOS header\n assert not np.array_equal(\n adv_x[j, int(0x3C) + 4 : int(0x3C) + 4 + 232],\n fix_get_synthetic_data[0][i, int(0x3C) + 4 : int(0x3C) + 4 + 232],\n )\n\n # rest of the file is unchanged\n assert np.array_equal(\n adv_x[j, int(0x3C) + 4 + 232 :], fix_get_synthetic_data[0][i, int(0x3C) + 4 + 232 :]\n )\n j += 1\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_no_auto_append(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n Verify behaviour when not spilling extra perturbation into an append attack\n \"\"\"\n try:\n\n def generate_synthetic_slack_regions(size):\n \"\"\"\n Generate 4 slack regions per sample, each of size 250.\n \"\"\"\n\n batch_of_slack_starts = []\n batch_of_slack_sizes = []\n\n for _ in range(5):\n size_of_slack = []\n start_of_slack = []\n start = 0\n for _ in range(4):\n start += 1000\n start_of_slack.append(start)\n size_of_slack.append(size)\n batch_of_slack_starts.append(start_of_slack)\n batch_of_slack_sizes.append(size_of_slack)\n return batch_of_slack_starts, batch_of_slack_sizes\n\n # 6th check: Do not automatically append extra perturbation\n l0_budget = 1250\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0],\n embedding_weights=fix_make_dummy_model[1],\n l_0=l0_budget,\n param_dic=param_dic,\n )\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n attack.l_0 = l0_budget\n\n batch_of_section_starts, batch_of_section_sizes = generate_synthetic_slack_regions(size=250)\n adv_x, adv_y, adv_sizes, batch_of_section_starts, batch_of_section_sizes = attack.pull_out_valid_samples(\n x,\n y,\n sample_sizes=size_of_files,\n perturb_starts=batch_of_section_starts,\n perturb_sizes=batch_of_section_sizes,\n automatically_append=False,\n )\n # should have 3 samples.\n # 2nd datapoint cannot support any modification\n # 5th is a benign sample\n assert len(adv_x) == 3\n\n adv_x = attack.generate(\n adv_x,\n adv_y,\n adv_sizes,\n automatically_append=False,\n perturb_sizes=batch_of_section_sizes,\n perturb_starts=batch_of_section_starts,\n )\n\n j = 0\n for i in range(len(fix_get_synthetic_data[0])):\n if i in [0, 2, 3]:\n slack_starts = batch_of_section_starts[j]\n slack_sizes = batch_of_section_sizes[j]\n beginning_pos = 0\n total_perturbation = 0\n for slack_start, slack_size in zip(slack_starts, slack_sizes):\n assert np.array_equal(\n adv_x[j, beginning_pos:slack_start], fix_get_synthetic_data[0][i, beginning_pos:slack_start]\n )\n\n assert not np.array_equal(\n adv_x[j, slack_start : slack_start + slack_size],\n fix_get_synthetic_data[0][i, slack_start : slack_start + slack_size],\n )\n # set the position to the end of the slack region\n beginning_pos = slack_start + slack_size\n total_perturbation += slack_size\n # from end of final inserted perturbation to EOF.\n assert np.array_equal(adv_x[j, beginning_pos:], fix_get_synthetic_data[0][i, beginning_pos:])\n j += 1\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_do_not_check_for_valid(art_warning, fix_get_synthetic_data, fix_make_dummy_model):\n \"\"\"\n No checking for valid data. Expect a mixed adversarial/normal data to be returned.\n \"\"\"\n try:\n l0_budget = 1250\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n attack = MalwareGDTensorFlow(\n classifier=fix_make_dummy_model[0],\n embedding_weights=fix_make_dummy_model[1],\n l_0=l0_budget,\n param_dic=param_dic,\n )\n x = np.copy(fix_get_synthetic_data[0])\n y = np.copy(fix_get_synthetic_data[1])\n size_of_files = np.copy(fix_get_synthetic_data[2])\n\n attack.l_0 = l0_budget\n\n adv_x = attack.generate(x, y, size_of_files, verify_input_data=False)\n assert len(adv_x) == 5\n\n # We expect 2 files to have been made adversarial the following cannot be converted to valid adv samples:\n # 2nd datapoint (file too large to support any modifications)\n # 4th datapoint (file too large to support append attacks)\n # 5th datapoint (benign file)\n for i, size in enumerate(size_of_files):\n if i in [0, 2]:\n assert np.array_equal(adv_x[i, :size], fix_get_synthetic_data[0][i, :size])\n assert not np.array_equal(\n adv_x[i, size : size + l0_budget], fix_get_synthetic_data[0][i, size : size + l0_budget]\n )\n assert np.array_equal(adv_x[i, size + l0_budget :], fix_get_synthetic_data[0][i, size + l0_budget :])\n else:\n assert np.array_equal(adv_x[i], fix_get_synthetic_data[0][i])\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"non_dl_frameworks\", \"keras\", \"kerastf\")\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(MalwareGDTensorFlow)\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(classifier, param_dic=[1, 2, 3], embedding_weights=np.array([1, 2, 3]))\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(classifier, param_dic={\"test\": 1}, embedding_weights=[1, 2, 3])\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), l_0=\"1\")\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), l_0=-1)\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), l_r=\"1\")\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), l_r=-1)\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(\n classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), use_sign=\"true\"\n )\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(\n classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), num_of_iterations=1.0\n )\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(\n classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), num_of_iterations=-1\n )\n\n with pytest.raises(ValueError):\n _ = MalwareGDTensorFlow(\n classifier, param_dic={\"test\": 1}, embedding_weights=np.array([1, 2, 3]), verbose=\"true\"\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning, fix_make_dummy_model):\n try:\n param_dic = {\"maxlen\": 2**20, \"input_dim\": 257, \"embedding_size\": 8}\n backend_test_classifier_type_check_fail(\n MalwareGDTensorFlow,\n [BaseEstimator, NeuralNetworkMixin, ClassifierMixin],\n classifier=None,\n param_dic=param_dic,\n embedding_weights=fix_make_dummy_model[1],\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_rescaling_auto_conjugate_gradient.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n\n# Copyright (c) 2024 Keiichiro Yamamura\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion import RescalingAutoConjugateGradient\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.parametrize(\"loss_type\", [\"cross_entropy\", \"difference_logits_ratio\"])\n@pytest.mark.parametrize(\"norm\", [\"inf\", np.inf, 1, 2])\n@pytest.mark.skip_framework(\"keras\", \"non_dl_frameworks\", \"kerastf\")\ndef test_generate(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, framework, loss_type, norm):\n print(\"test_generate\")\n try:\n classifier = image_dl_estimator_for_attack(RescalingAutoConjugateGradient, from_logits=True)\n\n attack = RescalingAutoConjugateGradient(\n estimator=classifier,\n norm=norm,\n eps=0.3,\n eps_step=0.1,\n max_iter=5,\n targeted=False,\n nb_random_init=1,\n batch_size=32,\n loss_type=loss_type,\n verbose=False,\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) > 0.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n\n classifier = image_dl_estimator_for_attack(RescalingAutoConjugateGradient, from_logits=True)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, eps=\"1\")\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, eps=-1.0)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, eps_step=\"1\")\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, eps_step=-1.0)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, targeted=\"true\")\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, nb_random_init=1.0)\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, nb_random_init=-1)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, loss_type=\"test\")\n\n with pytest.raises(ValueError):\n _ = RescalingAutoConjugateGradient(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n RescalingAutoConjugateGradient, [BaseEstimator, LossGradientsMixin, ClassifierMixin]\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_shadow_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion import ShadowAttack\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_generate(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(ShadowAttack)\n attack = ShadowAttack(\n estimator=classifier,\n sigma=0.5,\n nb_steps=3,\n learning_rate=0.1,\n lambda_tv=0.3,\n lambda_c=1.0,\n lambda_s=0.5,\n batch_size=32,\n targeted=True,\n verbose=False,\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist[0:1], y=y_train_mnist[0:1])\n\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist[0:1])) == pytest.approx(0.3803413510322571, abs=0.06)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_get_regularisation_loss_gradients(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(ShadowAttack)\n\n attack = ShadowAttack(\n estimator=classifier,\n sigma=0.5,\n nb_steps=3,\n learning_rate=0.1,\n lambda_tv=0.3,\n lambda_c=1.0,\n lambda_s=0.5,\n batch_size=32,\n targeted=True,\n verbose=False,\n )\n\n (x_train_mnist, _, _, _) = fix_get_mnist_subset\n\n gradients = attack._get_regularisation_loss_gradients(x_train_mnist[0:1])\n\n gradients_expected = np.array(\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n -0.27294118,\n -0.36906054,\n 0.83799828,\n 0.40741005,\n 0.65682181,\n -0.13141348,\n -0.39729583,\n -0.12235294,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n\n if attack.framework == \"pytorch\":\n np.testing.assert_array_almost_equal(gradients[0, 0, 14, :], gradients_expected, decimal=3)\n else:\n np.testing.assert_array_almost_equal(gradients[0, 14, :, 0], gradients_expected, decimal=3)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(ShadowAttack)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, sigma=\"test\")\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, sigma=-0.5)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, nb_steps=0.5)\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, nb_steps=-5)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, learning_rate=5)\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, learning_rate=-5.0)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, lambda_tv=5)\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, lambda_tv=-5.0)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, lambda_c=5)\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, lambda_c=-5.0)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, lambda_s=5)\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, lambda_s=-5.0)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, batch_size=5.0)\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, batch_size=-5)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, targeted=5.0)\n\n with pytest.raises(ValueError):\n _ = ShadowAttack(classifier, verbose=5.0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(ShadowAttack, [BaseEstimator, LossGradientsMixin, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_sign_opt.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport pytest\nimport logging\n\nfrom art.attacks.evasion import SignOPTAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_targeted_tabular, backend_untargeted_tabular\nfrom tests.attacks.utils import back_end_untargeted_images, backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset_large(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n # n_train is used for x_init in SignOPTAttack._attack().\n # It provides the pool of possible targets for finding initial direction\n n_train = 100\n n_test = 10\n print(f\"fix_get_mnist_subset_large() uses larger train and test set: n_train: {n_train}, n_test: {n_test}\")\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"clipped_classifier, targeted\", [(True, True), (True, False), (False, True), (False, False)])\ndef test_tabular(art_warning, tabular_dl_estimator, framework, get_iris_dataset, clipped_classifier, targeted):\n try:\n classifier = tabular_dl_estimator(clipped=clipped_classifier)\n attack = SignOPTAttack(classifier, targeted=targeted, num_trial=10, max_iter=10, query_limit=40, verbose=True)\n if targeted:\n backend_targeted_tabular(attack, get_iris_dataset)\n else:\n backend_untargeted_tabular(attack, get_iris_dataset, clipped=clipped_classifier)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"targeted\", [True, False])\ndef test_images(\n art_warning, fix_get_mnist_subset, fix_get_mnist_subset_large, image_dl_estimator_for_attack, targeted, framework\n):\n try:\n classifier = image_dl_estimator_for_attack(SignOPTAttack)\n\n if targeted:\n pass\n # attack = SignOPTAttack(\n # estimator=classifier, targeted=targeted, max_iter=2000, query_limit=14000, verbose=True\n # )\n # backend_targeted_images(attack, fix_get_mnist_subset_large)\n else:\n attack = SignOPTAttack(\n estimator=classifier, targeted=targeted, max_iter=1000, query_limit=4000, verbose=True\n )\n back_end_untargeted_images(attack, fix_get_mnist_subset, framework)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(SignOPTAttack)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, targeted=\"false\")\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, epsilon=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, num_trial=1.0)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, num_trial=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, max_iter=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, query_limit=1.0)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, query_limit=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, k=1.0)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, k=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, alpha=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, beta=-1)\n with pytest.raises(ValueError):\n _ = SignOPTAttack(classifier, verbose=\"true\")\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(SignOPTAttack, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/test_square_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion import SquareAttack\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"keras\", \"scikitlearn\", \"kerastf\")\n@pytest.mark.parametrize(\"norm\", [2, \"inf\"])\ndef test_generate(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack, norm):\n try:\n classifier = image_dl_estimator_for_attack(SquareAttack)\n\n attack = SquareAttack(\n estimator=classifier, norm=norm, max_iter=5, eps=0.3, p_init=0.8, nb_restarts=1, verbose=False\n )\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n x_train_mnist_adv = attack.generate(x=x_train_mnist, y=y_train_mnist)\n\n if norm == \"inf\":\n expected_mean = 0.053533513\n expected_max = 0.3\n elif norm == 2:\n expected_mean = 0.00073682\n expected_max = 0.25\n else:\n raise ValueError(\"Value of `norm` not recognized.\")\n\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(expected_mean, abs=0.025)\n assert np.max(np.abs(x_train_mnist_adv - x_train_mnist)) == pytest.approx(expected_max, abs=0.05)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(SquareAttack)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, norm=0)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, eps=\"1.0\")\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, eps=-1)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, p_init=\"1.0\")\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, p_init=-1)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, nb_restarts=1.0)\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, nb_restarts=-1)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, batch_size=1.0)\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = SquareAttack(classifier, verbose=\"true\")\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(SquareAttack, [BaseEstimator, NeuralNetworkMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/feature_adversaries/test_feature_adversaries.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import FeatureAdversariesNumpy\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"pytorch\")\n@pytest.mark.framework_agnostic\ndef test_images(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier = image_dl_estimator_for_attack(FeatureAdversariesNumpy)\n\n attack = FeatureAdversariesNumpy(classifier, delta=0.2, layer=1, batch_size=32)\n x_train_mnist_adv = attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:3], maxiter=1)\n\n assert np.mean(x_train_mnist[0:3]) == pytest.approx(0.13015706282513004, 0.01)\n assert np.mean(x_train_mnist_adv) == pytest.approx(0.1592448561261751, 0.01)\n\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3], y=None)\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:2])\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3, 0:5, 0:5, :], y=x_test_mnist[0:3])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FeatureAdversariesNumpy)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesNumpy(classifier, delta=None)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesNumpy(classifier, delta=-1.0)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesNumpy(classifier, delta=1.0, layer=1.0)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesNumpy(classifier, delta=1.0, layer=1, batch_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(FeatureAdversariesNumpy, [BaseEstimator, NeuralNetworkMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/feature_adversaries/test_feature_adversaries_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import FeatureAdversariesPyTorch\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_images_pgd(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier = image_dl_estimator_for_attack(FeatureAdversariesPyTorch, functional=True)\n\n attack = FeatureAdversariesPyTorch(\n classifier, delta=1.0, layer=1, batch_size=32, step_size=0.05, max_iter=2, random_start=False\n )\n x_train_mnist_adv = attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:3])\n\n assert np.mean(x_train_mnist[0:3]) == pytest.approx(0.13015705, 0.01)\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist[0:3])) != 0.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_images_unconstrained_adam(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n import torch\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier = image_dl_estimator_for_attack(FeatureAdversariesPyTorch, functional=True)\n\n attack = FeatureAdversariesPyTorch(\n classifier, delta=1.0, layer=1, batch_size=32, optimizer=torch.optim.Adam, max_iter=1, random_start=False\n )\n x_train_mnist_adv = attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:3])\n\n assert np.mean(x_train_mnist[0:3]) == pytest.approx(0.13015705, 0.01)\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist[0:3])) != 0.0\n\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3], y=None)\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:2])\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3, 0:5, 0:5, :], y=x_test_mnist[0:3])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FeatureAdversariesPyTorch)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1, step_size=0.5)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=-1.0, step_size=0.5)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=0.5, lambda_=1)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=0.5, lambda_=-1.0)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=0.5, layer=1.0)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=0.5, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=0.5, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=0.5, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=None, optimizer=None)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=\"test\")\n with pytest.raises(ValueError):\n _ = FeatureAdversariesPyTorch(classifier, delta=1.0, step_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n FeatureAdversariesPyTorch, [BaseEstimator, NeuralNetworkMixin], delta=1.0\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/evasion/feature_adversaries/test_feature_adversaries_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.evasion import FeatureAdversariesTensorFlowV2\nfrom art.estimators.estimator import BaseEstimator, NeuralNetworkMixin\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"keras\", \"kerastf\", \"non_dl_frameworks\", \"pytorch\", \"huggingface\")\ndef test_images_pgd(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier = image_dl_estimator_for_attack(FeatureAdversariesTensorFlowV2)\n\n attack = FeatureAdversariesTensorFlowV2(\n classifier, delta=1.0, layer=1, batch_size=32, step_size=0.05, max_iter=2, random_start=False\n )\n x_train_mnist_adv = attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:3])\n\n assert np.mean(x_train_mnist[0:3]) == pytest.approx(0.13015705, 0.01)\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist[0:3])) != 0.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"keras\", \"kerastf\", \"non_dl_frameworks\", \"pytorch\", \"huggingface\")\ndef test_images_unconstrained_adam(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n import tensorflow as tf\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n classifier = image_dl_estimator_for_attack(FeatureAdversariesTensorFlowV2)\n\n attack = FeatureAdversariesTensorFlowV2(\n classifier, delta=1.0, layer=1, batch_size=32, optimizer=tf.optimizers.Adam, max_iter=1, random_start=False\n )\n x_train_mnist_adv = attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:3])\n\n assert np.mean(x_train_mnist[0:3]) == pytest.approx(0.13015705, 0.01)\n assert np.mean(np.abs(x_train_mnist_adv - x_train_mnist[0:3])) != 0.0\n\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3], y=None)\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3], y=x_test_mnist[0:2])\n with pytest.raises(ValueError):\n attack.generate(x=x_train_mnist[0:3, 0:5, 0:5, :], y=x_test_mnist[0:3])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"huggingface\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(FeatureAdversariesTensorFlowV2)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1, step_size=0.5)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=-1.0, step_size=0.5)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=0.5, lambda_=1)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=0.5, lambda_=-1.0)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=0.5, layer=1.0)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=0.5, max_iter=1.0)\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=0.5, max_iter=-1)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=0.5, batch_size=-1)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=None, optimizer=None)\n\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=\"test\")\n with pytest.raises(ValueError):\n _ = FeatureAdversariesTensorFlowV2(classifier, delta=1.0, step_size=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n FeatureAdversariesTensorFlowV2, [BaseEstimator, NeuralNetworkMixin], delta=1.0\n )\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/test_reconstruction.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import LogisticRegression\n\nfrom art.attacks.inference.reconstruction import DatabaseReconstruction\nfrom art.estimators.classification.scikitlearn import ScikitlearnGaussianNB, ScikitlearnLogisticRegression\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef test_database_reconstruction_gaussian_nb(get_iris_dataset):\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n y_train_iris = np.array([np.argmax(y) for y in y_train_iris])\n y_test_iris = np.array([np.argmax(y) for y in y_test_iris])\n\n x_private = x_test_iris[0, :].reshape(1, -1)\n y_private = y_test_iris[0]\n\n x_input = np.vstack((x_train_iris, x_private))\n y_input = np.hstack((y_train_iris, y_private))\n\n nb_private = GaussianNB()\n nb_private.fit(x_input, y_input)\n estimator_private = ScikitlearnGaussianNB(model=nb_private)\n\n recon = DatabaseReconstruction(estimator=estimator_private)\n x_recon, y_recon = recon.reconstruct(x_train_iris, y_train_iris)\n\n assert x_recon is not None\n assert x_recon.shape == (1, 4)\n assert y_recon.shape == (1, 3)\n # assert np.isclose(x_recon, x_private).all()\n assert np.isclose(x_recon, np.array([[0.84792809, 0.41754901, 0.72134694, 0.31628275]])).all()\n assert np.argmax(y_recon, axis=1) == y_private\n\n\ndef test_database_reconstruction_logistic_regression(get_iris_dataset):\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n y_train_iris = np.array([np.argmax(y) for y in y_train_iris])\n y_test_iris = np.array([np.argmax(y) for y in y_test_iris])\n\n x_private = x_test_iris[0, :].reshape(1, -1)\n y_private = y_test_iris[0]\n\n x_input = np.vstack((x_train_iris, x_private))\n y_input = np.hstack((y_train_iris, y_private))\n\n nb_private = LogisticRegression()\n nb_private.fit(x_input, y_input)\n estimator_private = ScikitlearnLogisticRegression(model=nb_private)\n\n recon = DatabaseReconstruction(estimator=estimator_private)\n x_recon, y_recon = recon.reconstruct(x_train_iris, y_train_iris)\n\n assert x_recon is not None\n assert x_recon.shape == (1, 4)\n assert y_recon.shape == (1, 3)\n assert np.isclose(x_recon, x_private, rtol=0.05).all()\n assert np.argmax(y_recon, axis=1) == y_private\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/attribute_inference/test_baseline.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OrdinalEncoder\n\nfrom art.attacks.inference.attribute_inference.baseline import AttributeInferenceBaseline\nfrom art.utils import check_and_transform_label_format\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaseline(attack_feature=attack_feature, attack_model_type=model_type)\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.77, \"dt\": 0.98, \"knn\": 0.84, \"svm\": 0.83}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.83, \"gb\": 0.79, \"lr\": 0.86, \"dt\": 0.82, \"knn\": 0.82, \"svm\": 0.93}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_continuous(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=attack_feature, attack_model_type=model_type, is_continuous=True\n )\n # train attack model\n baseline_attack.fit(x_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack)\n # check accuracy\n assert (\n np.count_nonzero(np.isclose(baseline_inferred_train, x_train_feature.reshape(1, -1), atol=0.4))\n > baseline_inferred_train.shape[0] * 0.75\n )\n assert (\n np.count_nonzero(np.isclose(baseline_inferred_test, x_test_feature.reshape(1, -1), atol=0.4))\n > baseline_inferred_test.shape[0] * 0.75\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_slice(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=slice(attack_feature, attack_feature + 1), attack_model_type=model_type\n )\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.77, \"dt\": 0.98, \"knn\": 0.85, \"svm\": 0.83}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.83, \"gb\": 0.82, \"lr\": 0.86, \"dt\": 0.8, \"knn\": 0.81, \"svm\": 0.93}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_no_values(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaseline(attack_feature=attack_feature, attack_model_type=model_type)\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.77, \"dt\": 0.98, \"knn\": 0.85, \"svm\": 0.83}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.82, \"gb\": 0.8, \"lr\": 0.86, \"dt\": 0.8, \"knn\": 0.81, \"svm\": 0.93}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_encoder(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n encoder.fit(x_train_for_attack)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=attack_feature, attack_model_type=model_type, encoder=encoder\n )\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.96, \"gb\": 0.96, \"lr\": 0.71, \"dt\": 0.96, \"knn\": 0.89, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.8, \"gb\": 0.77, \"lr\": 0.75, \"dt\": 0.82, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_no_encoder(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=attack_feature, attack_model_type=model_type, non_numerical_features=[other_feature]\n )\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.96, \"gb\": 0.96, \"lr\": 0.71, \"dt\": 0.96, \"knn\": 0.89, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.8, \"gb\": 0.77, \"lr\": 0.75, \"dt\": 0.82, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_no_encoder_after_feature(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.3] = 2.0\n x[(x > 0.2) & (x <= 0.3)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 3\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n new_other_feature = other_feature - 1\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, new_other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :new_other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, new_other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, new_other_feature, 1)\n x_test_other_feature = x_test_iris[:, new_other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate(\n (x_test_without_feature[:, :new_other_feature], x_test_other_feature), axis=1\n )\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, new_other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=attack_feature, attack_model_type=model_type, non_numerical_features=[other_feature]\n )\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.94, \"gb\": 0.95, \"lr\": 0.8, \"dt\": 0.94, \"knn\": 0.87, \"svm\": 0.8}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.82, \"gb\": 0.84, \"lr\": 0.86, \"dt\": 0.79, \"knn\": 0.86, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_no_encoder_after_feature_slice(art_warning, get_iris_dataset, model_type):\n try:\n orig_attack_feature = 1 # petal length\n new_attack_feature = slice(1, 4) # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.3] = 2.0\n x[(x > 0.2) & (x <= 0.3)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, orig_attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, orig_attack_feature].copy()\n transform_attacked_feature(x_train_feature)\n x_train_feature = check_and_transform_label_format(x_train_feature, nb_classes=3, return_one_hot=True)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :orig_attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, orig_attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 5 # was 3 before 1-hot encoding of attacked feature\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n new_other_feature = other_feature - 3\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, new_other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :new_other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, new_other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, orig_attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, orig_attack_feature].copy()\n transform_attacked_feature(x_test_feature)\n x_test_feature = check_and_transform_label_format(x_test_feature, nb_classes=3, return_one_hot=True)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, new_other_feature, 1)\n x_test_other_feature = x_test_for_attack[:, new_other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate(\n (x_test_without_feature[:, :new_other_feature], x_test_other_feature), axis=1\n )\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, new_other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=new_attack_feature, attack_model_type=model_type, non_numerical_features=[other_feature]\n )\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = np.argmax(baseline_attack.infer(x_train_for_attack), axis=1)\n baseline_inferred_test = np.argmax(baseline_attack.infer(x_test_for_attack), axis=1)\n x_train_feature = np.argmax(x_train_feature, axis=1)\n x_test_feature = np.argmax(x_test_feature, axis=1)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature) / len(baseline_inferred_train)\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature) / len(baseline_inferred_test)\n\n expected_train_acc = {\"nn\": 0.96, \"rf\": 0.99, \"gb\": 0.99, \"lr\": 0.96, \"dt\": 0.98, \"knn\": 0.97, \"svm\": 0.96}\n expected_test_acc = {\"nn\": 0.99, \"rf\": 0.97, \"gb\": 0.97, \"lr\": 0.99, \"dt\": 0.97, \"knn\": 0.99, \"svm\": 0.99}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_baseline_no_encoder_remove_attack_feature(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaseline(\n attack_feature=attack_feature,\n attack_model_type=model_type,\n non_numerical_features=[other_feature, attack_feature],\n )\n # train attack model\n baseline_attack.fit(x_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.58, \"rf\": 0.96, \"gb\": 0.96, \"lr\": 0.71, \"dt\": 0.96, \"knn\": 0.89, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.62, \"rf\": 0.8, \"gb\": 0.77, \"lr\": 0.75, \"dt\": 0.82, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_check_params(art_warning, get_iris_dataset):\n try:\n (x_train, y_train), (_, _) = get_iris_dataset\n\n with pytest.raises(ValueError):\n AttributeInferenceBaseline(attack_feature=\"a\")\n\n with pytest.raises(ValueError):\n AttributeInferenceBaseline(attack_feature=-3)\n\n with pytest.raises(ValueError):\n AttributeInferenceBaseline(non_numerical_features=[\"a\"])\n\n with pytest.raises(ValueError):\n AttributeInferenceBaseline(encoder=\"a\")\n\n with pytest.raises(ValueError):\n AttributeInferenceBaseline(is_continuous=\"a\")\n\n attack = AttributeInferenceBaseline(attack_feature=8)\n\n with pytest.raises(ValueError):\n attack.fit(x_train)\n\n _ = AttributeInferenceBaseline()\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/attribute_inference/test_black_box.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.preprocessing import StandardScaler, OrdinalEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n\nfrom art.attacks.inference.attribute_inference.black_box import AttributeInferenceBlackBox\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification import ClassifierMixin\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier, ScikitlearnClassifier\nfrom art.estimators.regression import ScikitlearnRegressor, RegressorMixin\nfrom art.utils import check_and_transform_label_format\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box(art_warning, decision_tree_estimator, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, attack_model_type=model_type)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert pytest.approx(0.8285, abs=0.35) == train_acc\n assert pytest.approx(0.8888, abs=0.35) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"scaler_type\", [\"standard\", \"robust\", \"minmax\"])\ndef test_black_box_scalers(art_warning, scaler_type, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, scaler_type=scaler_type)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert pytest.approx(0.8285, abs=0.3) == train_acc\n assert pytest.approx(0.8888, abs=0.3) == test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_black_box_tabular_no_scaler(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, scaler_type=None)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert pytest.approx(0.8285, abs=0.3) == train_acc\n assert pytest.approx(0.8888, abs=0.3) == test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_continuous(art_warning, decision_tree_estimator, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(\n classifier, attack_feature=attack_feature, attack_model_type=model_type, is_continuous=True\n )\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train_iris)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions)\n # check accuracy\n assert (\n np.count_nonzero(np.isclose(inferred_train, x_train_feature.reshape(1, -1), atol=0.4))\n > inferred_train.shape[0] * 0.75\n )\n assert (\n np.count_nonzero(np.isclose(inferred_test, x_test_feature.reshape(1, -1), atol=0.4))\n > inferred_test.shape[0] * 0.75\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_slice(art_warning, decision_tree_estimator, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(\n classifier, attack_feature=slice(attack_feature, attack_feature + 1), attack_model_type=model_type\n )\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert pytest.approx(0.8285, abs=0.35) == train_acc\n assert pytest.approx(0.8888, abs=0.35) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_with_label(art_warning, decision_tree_estimator, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, attack_model_type=model_type)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train, y=y_train_iris)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y=y_train_iris, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, y=y_test_iris, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert pytest.approx(0.8285, abs=0.35) == train_acc\n assert pytest.approx(0.8888, abs=0.35) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_no_values(art_warning, decision_tree_estimator, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, attack_model_type=model_type)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert pytest.approx(0.8285, abs=0.35) == train_acc\n assert pytest.approx(0.8888, abs=0.35) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_regressor(art_warning, get_diabetes_dataset, model_type):\n try:\n attack_feature = 0 # age\n\n bins = [\n -0.96838121,\n -0.77154309,\n -0.57470497,\n -0.37786684,\n -0.18102872,\n 0.0158094,\n 0.21264752,\n 0.40948564,\n 0.60632376,\n 0.80316188,\n 1.0,\n ]\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n for i in range(len(bins) - 1):\n x[(x >= bins[i]) & (x <= bins[i + 1])] = i\n\n values = list(range(len(bins) - 1))\n\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes) = get_diabetes_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_diabetes, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_diabetes[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_diabetes, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_diabetes[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n from sklearn import linear_model\n\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train_diabetes, y_train_diabetes)\n regressor = ScikitlearnRegressor(regr_model)\n\n attack = AttributeInferenceBlackBox(\n regressor, attack_feature=attack_feature, prediction_normal_factor=1 / 250, attack_model_type=model_type\n )\n # get original model's predictions\n x_train_predictions = regressor.predict(x_train_diabetes).reshape(-1, 1)\n x_test_predictions = regressor.predict(x_test_diabetes).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n\n assert train_acc == pytest.approx(0.1, abs=0.15)\n assert test_acc == pytest.approx(0.1, abs=0.15)\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_regressor_label(art_warning, get_diabetes_dataset, model_type):\n try:\n attack_feature = 0 # age\n\n bins = [\n -0.96838121,\n -0.77154309,\n -0.57470497,\n -0.37786684,\n -0.18102872,\n 0.0158094,\n 0.21264752,\n 0.40948564,\n 0.60632376,\n 0.80316188,\n 1.0,\n ]\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n for i in range(len(bins) - 1):\n x[(x >= bins[i]) & (x <= bins[i + 1])] = i\n\n values = list(range(len(bins) - 1))\n\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes) = get_diabetes_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_diabetes, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_diabetes[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_diabetes, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_diabetes[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n from sklearn import linear_model\n\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train_diabetes, y_train_diabetes)\n regressor = ScikitlearnRegressor(regr_model)\n\n attack = AttributeInferenceBlackBox(\n regressor, attack_feature=attack_feature, prediction_normal_factor=1 / 250, attack_model_type=model_type\n )\n # get original model's predictions\n x_train_predictions = regressor.predict(x_train_diabetes).reshape(-1, 1)\n x_test_predictions = regressor.predict(x_test_diabetes).reshape(-1, 1)\n # train attack model\n attack.fit(x_train, y=y_train_diabetes)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values, y=y_train_diabetes)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values, y=y_test_diabetes)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n\n assert pytest.approx(0.1, abs=0.15) == train_acc\n assert pytest.approx(0.1, abs=0.15) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_black_box_with_model(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n model = nn.Linear(4, 3)\n\n # Define a loss function and optimizer\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n attack_model = PyTorchClassifier(\n model=model, clip_values=(0, 1), loss=loss_fn, optimizer=optimizer, input_shape=(4,), nb_classes=3\n )\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceBlackBox(classifier, attack_model=attack_model, attack_feature=attack_feature)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values)\n # check accuracy\n # train_acc\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n # test_acc\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n # assert train_acc == pytest.approx(0.5523, abs=0.03)\n # assert test_acc == pytest.approx(0.5777, abs=0.03)\n print(train_acc, test_acc)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_one_hot(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2\n x[(x > 0.2) & (x <= 0.5)] = 1\n x[x <= 0.2] = 0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # transform to one-hot encoding\n train_one_hot = np.zeros((x_train_feature.size, int(x_train_feature.max()) + 1))\n train_one_hot[np.arange(x_train_feature.size), x_train_feature.reshape(1, -1).astype(int)] = 1\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], train_one_hot), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n y_train = np.array([np.argmax(y) for y in y_train_iris]).reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # transform to one-hot encoding\n test_one_hot = np.zeros((x_test_feature.size, int(x_test_feature.max()) + 1))\n test_one_hot[np.arange(x_test_feature.size), x_test_feature.reshape(1, -1).astype(int)] = 1\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], test_one_hot), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n tree = DecisionTreeClassifier()\n tree.fit(x_train, y_train)\n classifier = ScikitlearnDecisionTreeClassifier(tree)\n\n attack = AttributeInferenceBlackBox(\n classifier, attack_feature=slice(attack_feature, attack_feature + 3), attack_model_type=model_type\n )\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions)\n # check accuracy\n train_acc = np.sum(np.all(inferred_train == train_one_hot, axis=1)) / len(inferred_train)\n test_acc = np.sum(np.all(inferred_test == test_one_hot, axis=1)) / len(inferred_test)\n assert pytest.approx(0.8666, abs=0.3) == train_acc\n assert pytest.approx(0.8888, abs=0.7) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_one_hot_float(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2\n x[(x > 0.2) & (x <= 0.5)] = 1\n x[x <= 0.2] = 0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # transform to one-hot encoding\n num_columns = int(x_train_feature.max()) + 1\n train_one_hot = np.zeros((x_train_feature.size, num_columns))\n train_one_hot[np.arange(x_train_feature.size), x_train_feature.reshape(1, -1).astype(int)] = 1\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], train_one_hot), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n y_train = np.array([np.argmax(y) for y in y_train_iris]).reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # transform to one-hot encoding\n test_one_hot = np.zeros((x_test_feature.size, int(x_test_feature.max()) + 1))\n test_one_hot[np.arange(x_test_feature.size), x_test_feature.reshape(1, -1).astype(int)] = 1\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], test_one_hot), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n # scale before training\n scaler = StandardScaler().fit(x_train)\n x_test = scaler.transform(x_test).astype(np.float32)\n x_train = scaler.transform(x_train).astype(np.float32)\n # derive dataset for attack (after scaling)\n attack_feature = slice(attack_feature, attack_feature + 3)\n x_train_for_attack = np.delete(x_train, attack_feature, 1)\n x_test_for_attack = np.delete(x_test, attack_feature, 1)\n train_one_hot = x_train[:, attack_feature]\n test_one_hot = x_test[:, attack_feature]\n\n tree = DecisionTreeClassifier()\n tree.fit(x_train, y_train)\n classifier = ScikitlearnDecisionTreeClassifier(tree)\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, attack_model_type=model_type)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n values = [[-0.559017, 1.7888544], [-0.47003216, 2.127514], [-1.1774395, 0.84930056]]\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions, values=values).astype(np.float32)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions, values=values).astype(np.float32)\n # check accuracy\n train_acc = np.sum(\n np.all(np.around(inferred_train, decimals=3) == np.around(train_one_hot, decimals=3), axis=1)\n ) / len(inferred_train)\n test_acc = np.sum(\n np.all(np.around(inferred_test, decimals=3) == np.around(test_one_hot, decimals=3), axis=1)\n ) / len(inferred_test)\n assert pytest.approx(0.8666, abs=0.12) == train_acc\n assert pytest.approx(0.8666, abs=0.1) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_one_hot_float_no_values(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2\n x[(x > 0.2) & (x <= 0.5)] = 1\n x[x <= 0.2] = 0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # transform to one-hot encoding\n num_columns = int(x_train_feature.max()) + 1\n train_one_hot = np.zeros((x_train_feature.size, num_columns))\n train_one_hot[np.arange(x_train_feature.size), x_train_feature.reshape(1, -1).astype(int)] = 1\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], train_one_hot), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n y_train = np.array([np.argmax(y) for y in y_train_iris]).reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # transform to one-hot encoding\n test_one_hot = np.zeros((x_test_feature.size, int(x_test_feature.max()) + 1))\n test_one_hot[np.arange(x_test_feature.size), x_test_feature.reshape(1, -1).astype(int)] = 1\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], test_one_hot), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n # scale before training\n scaler = StandardScaler().fit(x_train)\n x_test = scaler.transform(x_test).astype(np.float32)\n x_train = scaler.transform(x_train).astype(np.float32)\n # derive dataset for attack (after scaling)\n attack_feature = slice(attack_feature, attack_feature + 3)\n x_train_for_attack = np.delete(x_train, attack_feature, 1)\n x_test_for_attack = np.delete(x_test, attack_feature, 1)\n train_one_hot = x_train[:, attack_feature]\n test_one_hot = x_test[:, attack_feature]\n\n tree = DecisionTreeClassifier()\n tree.fit(x_train, y_train)\n classifier = ScikitlearnDecisionTreeClassifier(tree)\n\n attack = AttributeInferenceBlackBox(classifier, attack_feature=attack_feature, attack_model_type=model_type)\n # get original model's predictions\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test)]).reshape(-1, 1)\n # train attack model\n attack.fit(x_train)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, pred=x_train_predictions).astype(np.float32)\n inferred_test = attack.infer(x_test_for_attack, pred=x_test_predictions).astype(np.float32)\n # check accuracy\n train_acc = np.sum(\n np.all(np.around(inferred_train, decimals=3) == np.around(train_one_hot, decimals=3), axis=1)\n ) / len(inferred_train)\n test_acc = np.sum(\n np.all(np.around(inferred_test, decimals=3) == np.around(test_one_hot, decimals=3), axis=1)\n ) / len(inferred_test)\n assert pytest.approx(0.8666, abs=0.12) == train_acc\n assert pytest.approx(0.8666, abs=0.1) == test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_encoder(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n # transform other feature for full test data\n x_test = np.delete(x_test_iris, other_feature, 1)\n # test data with other feature (after transformation)\n x_test_for_pred = np.concatenate((x_test[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_pred = np.concatenate((x_test_for_pred, x_test[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n encoder.fit(x_train_for_attack)\n\n encoder_for_pipeline = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n model = DecisionTreeClassifier()\n pipeline = Pipeline([(\"encoder\", encoder_for_pipeline), (\"model\", model)])\n pipeline.fit(x_train, np.argmax(y_train_iris, axis=1))\n classifier = ScikitlearnClassifier(pipeline, preprocessing=None)\n\n attack = AttributeInferenceBlackBox(\n classifier, attack_feature=attack_feature, attack_model_type=model_type, encoder=encoder\n )\n # train attack model\n attack.fit(x_train, y_train_iris)\n # infer attacked feature\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_for_pred)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n\n assert 0.6 <= train_acc\n assert 0.6 <= test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_no_encoder(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n # transform other feature for full test data\n x_test = np.delete(x_test_iris, other_feature, 1)\n # test data with other feature (after transformation)\n x_test_for_pred = np.concatenate((x_test[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_pred = np.concatenate((x_test_for_pred, x_test[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n encoder.fit(x_train_for_attack)\n\n encoder_for_pipeline = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n model = DecisionTreeClassifier()\n pipeline = Pipeline([(\"encoder\", encoder_for_pipeline), (\"model\", model)])\n pipeline.fit(x_train, np.argmax(y_train_iris, axis=1))\n classifier = ScikitlearnClassifier(pipeline, preprocessing=None)\n\n attack = AttributeInferenceBlackBox(\n classifier,\n attack_feature=attack_feature,\n attack_model_type=model_type,\n non_numerical_features=[other_feature],\n )\n # train attack model\n attack.fit(x_train, y_train_iris)\n # infer attacked feature\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_for_pred)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n\n assert 0.6 <= train_acc\n assert 0.6 <= test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_no_encoder_after_feature(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.3] = 2.0\n x[(x > 0.2) & (x <= 0.3)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 3\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n new_other_feature = other_feature - 1\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, new_other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :new_other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, new_other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, new_other_feature, 1)\n x_test_other_feature = x_test_iris[:, new_other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate(\n (x_test_without_feature[:, :new_other_feature], x_test_other_feature), axis=1\n )\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, new_other_feature:]), axis=1)\n\n # transform other feature for full test data\n x_test = np.delete(x_test_iris, other_feature, 1)\n # test data with other feature (after transformation)\n x_test_for_pred = np.concatenate((x_test[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_pred = np.concatenate((x_test_for_pred, x_test[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n\n encoder_for_pipeline = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n model = DecisionTreeClassifier()\n pipeline = Pipeline([(\"encoder\", encoder_for_pipeline), (\"model\", model)])\n pipeline.fit(x_train, np.argmax(y_train_iris, axis=1))\n classifier = ScikitlearnClassifier(pipeline, preprocessing=None)\n\n attack = AttributeInferenceBlackBox(\n classifier,\n attack_feature=attack_feature,\n attack_model_type=model_type,\n non_numerical_features=[other_feature],\n )\n # train attack model\n attack.fit(x_train, y_train_iris)\n # infer attacked feature\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_for_pred)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n\n assert 0.4 <= train_acc\n assert 0.35 <= test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_no_encoder_after_feature_slice(art_warning, get_iris_dataset, model_type):\n try:\n orig_attack_feature = 1 # petal length\n new_attack_feature = slice(1, 4) # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.3] = 2.0\n x[(x > 0.2) & (x <= 0.3)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, orig_attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, orig_attack_feature].copy()\n transform_attacked_feature(x_train_feature)\n x_train_feature = check_and_transform_label_format(x_train_feature, nb_classes=3, return_one_hot=True)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :orig_attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, orig_attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 5 # was 3 before 1-hot encoding of attacked feature\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n new_other_feature = other_feature - 3\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, new_other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :new_other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, new_other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, orig_attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, orig_attack_feature].copy()\n transform_attacked_feature(x_test_feature)\n x_test_feature = check_and_transform_label_format(x_test_feature, nb_classes=3, return_one_hot=True)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, new_other_feature, 1)\n x_test_other_feature = x_test_for_attack[:, new_other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate(\n (x_test_without_feature[:, :new_other_feature], x_test_other_feature), axis=1\n )\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, new_other_feature:]), axis=1)\n\n # transform features for full test data\n x_test_without_feature = np.delete(x_test_iris, orig_attack_feature, 1)\n # test data with attacked feature (after transformation)\n x_test_with_feature = np.concatenate((x_test_without_feature[:, :orig_attack_feature], x_test_feature), axis=1)\n x_test_with_feature = np.concatenate(\n (x_test_with_feature, x_test_without_feature[:, orig_attack_feature:]), axis=1\n )\n x_test_without_feature = np.delete(x_test_with_feature, other_feature, 1)\n # test data with other feature (after transformation)\n x_test_for_pred = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_pred = np.concatenate((x_test_for_pred, x_test_without_feature[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n encoder_for_pipeline = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n model = DecisionTreeClassifier()\n pipeline = Pipeline([(\"encoder\", encoder_for_pipeline), (\"model\", model)])\n pipeline.fit(x_train, np.argmax(y_train_iris, axis=1))\n classifier = ScikitlearnClassifier(pipeline, preprocessing=None)\n\n attack = AttributeInferenceBlackBox(\n classifier,\n attack_feature=new_attack_feature,\n attack_model_type=model_type,\n non_numerical_features=[other_feature],\n )\n # train attack model\n attack.fit(x_train, y_train_iris)\n # infer attacked feature\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_for_pred)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, pred=x_train_predictions)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, pred=x_test_predictions)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature) / len(inferred_test)\n\n assert 0.0 <= train_acc\n assert 0.0 <= test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_no_encoder_remove_attack_feature(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n # transform other feature for full test data\n x_test = np.delete(x_test_iris, other_feature, 1)\n # test data with other feature (after transformation)\n x_test_for_pred = np.concatenate((x_test[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_pred = np.concatenate((x_test_for_pred, x_test[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n encoder.fit(x_train_for_attack)\n\n encoder_for_pipeline = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n model = DecisionTreeClassifier()\n pipeline = Pipeline([(\"encoder\", encoder_for_pipeline), (\"model\", model)])\n pipeline.fit(x_train, np.argmax(y_train_iris, axis=1))\n classifier = ScikitlearnClassifier(pipeline, preprocessing=None)\n\n attack = AttributeInferenceBlackBox(\n classifier,\n attack_feature=attack_feature,\n attack_model_type=model_type,\n non_numerical_features=[other_feature, attack_feature],\n )\n # train attack model\n attack.fit(x_train, y_train_iris)\n # infer attacked feature\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_for_pred)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, pred=x_train_predictions, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, pred=x_test_predictions, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n\n assert 0.6 <= train_acc\n assert 0.6 <= test_acc\n print(model_type, train_acc, test_acc)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_errors(art_warning, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(AttributeInferenceBlackBox)\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, attack_feature=\"a\")\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, attack_feature=-3)\n attack = AttributeInferenceBlackBox(classifier, attack_feature=8)\n with pytest.raises(ValueError):\n attack.fit(x_train)\n attack = AttributeInferenceBlackBox(classifier)\n with pytest.raises(ValueError):\n attack.fit(np.delete(x_train, 1, 1))\n with pytest.raises(ValueError):\n attack.infer(x_train, y_test)\n with pytest.raises(ValueError):\n attack.infer(x_train, y_train)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail():\n backend_test_classifier_type_check_fail(\n AttributeInferenceBlackBox, (BaseEstimator, (ClassifierMixin, RegressorMixin))\n )\n\n\ndef test_check_params(art_warning, tabular_dl_estimator_for_attack):\n try:\n classifier = tabular_dl_estimator_for_attack(AttributeInferenceBlackBox)\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, attack_feature=\"a\")\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, attack_feature=-1)\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, prediction_normal_factor=-1)\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, non_numerical_features=[\"a\"])\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, encoder=\"a\")\n\n with pytest.raises(ValueError):\n AttributeInferenceBlackBox(classifier, is_continuous=\"a\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/attribute_inference/test_meminf_based.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.preprocessing import StandardScaler\n\nfrom art.attacks.inference.attribute_inference.meminf_based import AttributeInferenceMembership\nfrom art.attacks.inference.membership_inference import (\n MembershipInferenceBlackBox,\n MembershipInferenceBlackBoxRuleBased,\n LabelOnlyDecisionBoundary,\n)\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\nfrom art.estimators.regression import ScikitlearnRegressor\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_meminf_black_box(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 0.6\n x[(x > 0.2) & (x <= 0.5)] = 0.35\n x[x <= 0.2] = 0.1\n\n values = [0.1, 0.35, 0.6]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], x_test_feature), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n classifier = decision_tree_estimator()\n\n meminf_attack = MembershipInferenceBlackBox(classifier, attack_model_type=\"nn\")\n attack_train_ratio = 0.5\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n meminf_attack.fit(\n x_train[:attack_train_size],\n y_train_iris[:attack_train_size],\n x_test[:attack_test_size],\n y_test_iris[:attack_test_size],\n )\n attack = AttributeInferenceMembership(classifier, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert 0.1 <= train_acc\n assert 0.1 <= test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_meminf_black_box_slice(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 0.6\n x[(x > 0.2) & (x <= 0.5)] = 0.35\n x[x <= 0.2] = 0.1\n\n values = [0.1, 0.35, 0.6]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], x_test_feature), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n classifier = decision_tree_estimator()\n\n meminf_attack = MembershipInferenceBlackBox(classifier, attack_model_type=\"nn\")\n attack_train_ratio = 0.5\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n meminf_attack.fit(\n x_train[:attack_train_size],\n y_train_iris[:attack_train_size],\n x_test[:attack_test_size],\n y_test_iris[:attack_test_size],\n )\n attack = AttributeInferenceMembership(\n classifier, meminf_attack, attack_feature=slice(attack_feature, attack_feature + 1)\n )\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert 0.1 <= train_acc\n assert 0.1 <= test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_meminf_black_box_regressor(art_warning, get_diabetes_dataset):\n try:\n attack_feature = 0 # age\n\n bins = [-1.0, -0.5, 0.0, 0.5, 1.0]\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n for i in range(len(bins) - 1):\n x[(x >= bins[i]) & (x < bins[i + 1])] = i\n\n values = list(range(len(bins) - 1))\n\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes) = get_diabetes_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_diabetes, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_diabetes[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_diabetes, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_diabetes[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], x_test_feature), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n from sklearn import linear_model\n\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train_diabetes, y_train_diabetes)\n regressor = ScikitlearnRegressor(regr_model)\n\n meminf_attack = MembershipInferenceBlackBox(regressor, attack_model_type=\"rf\", input_type=\"loss\")\n attack_train_ratio = 0.5\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n meminf_attack.fit(\n x_train[:attack_train_size],\n y_train_diabetes[:attack_train_size],\n x_test[:attack_test_size],\n y_test_diabetes[:attack_test_size],\n )\n attack = AttributeInferenceMembership(regressor, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_diabetes, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n assert 0.15 <= train_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"scikitlearn\")\ndef test_meminf_black_box_dl(art_warning, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 0.6\n x[(x > 0.2) & (x <= 0.5)] = 0.35\n x[x <= 0.2] = 0.1\n\n values = [0.1, 0.35, 0.6]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], x_test_feature), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n classifier = tabular_dl_estimator_for_attack(AttributeInferenceMembership)\n\n meminf_attack = MembershipInferenceBlackBox(classifier, attack_model_type=\"nn\")\n attack_train_ratio = 0.5\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n meminf_attack.fit(\n x_train[:attack_train_size],\n y_train_iris[:attack_train_size],\n x_test[:attack_test_size],\n y_test_iris[:attack_test_size],\n )\n attack = AttributeInferenceMembership(classifier, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature.reshape(1, -1)) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature.reshape(1, -1)) / len(inferred_test)\n assert 0.085 <= train_acc\n assert 0.04 <= test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_meminf_rule_based(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 0.6\n x[(x > 0.2) & (x <= 0.5)] = 0.35\n x[x <= 0.2] = 0.1\n\n values = [0.1, 0.35, 0.6]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n classifier = decision_tree_estimator()\n\n meminf_attack = MembershipInferenceBlackBoxRuleBased(classifier)\n attack = AttributeInferenceMembership(classifier, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature) / len(inferred_test)\n assert 0.1 <= train_acc\n assert 0.1 <= test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_black_box_one_hot_float(art_warning, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2\n x[(x > 0.2) & (x <= 0.5)] = 1\n x[x <= 0.2] = 0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # transform to one-hot encoding\n num_columns = int(x_train_feature.max()) + 1\n train_one_hot = np.zeros((x_train_feature.size, num_columns))\n train_one_hot[np.arange(x_train_feature.size), x_train_feature.reshape(1, -1).astype(int)] = 1\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], train_one_hot), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n y_train = np.array([np.argmax(y) for y in y_train_iris]).reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # transform to one-hot encoding\n test_one_hot = np.zeros((x_test_feature.size, int(x_test_feature.max()) + 1))\n test_one_hot[np.arange(x_test_feature.size), x_test_feature.reshape(1, -1).astype(int)] = 1\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], test_one_hot), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n # scale before training\n scaler = StandardScaler().fit(x_train)\n x_test = scaler.transform(x_test).astype(np.float32)\n x_train = scaler.transform(x_train).astype(np.float32)\n # derive dataset for attack (after scaling)\n attack_feature = slice(attack_feature, attack_feature + 3)\n x_train_for_attack = np.delete(x_train, attack_feature, 1)\n x_test_for_attack = np.delete(x_test, attack_feature, 1)\n train_one_hot = x_train[:, attack_feature]\n test_one_hot = x_test[:, attack_feature]\n\n tree = DecisionTreeClassifier()\n tree.fit(x_train, y_train)\n classifier = ScikitlearnDecisionTreeClassifier(tree)\n\n meminf_attack = MembershipInferenceBlackBox(classifier, attack_model_type=\"nn\")\n attack_train_ratio = 0.5\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n meminf_attack.fit(\n x_train[:attack_train_size],\n y_train_iris[:attack_train_size],\n x_test[:attack_test_size],\n y_test_iris[:attack_test_size],\n )\n attack = AttributeInferenceMembership(classifier, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n values = [[-0.559017, 1.7888544], [-0.47003216, 2.127514], [-1.1774395, 0.84930056]]\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(\n np.all(np.around(inferred_train, decimals=3) == np.around(train_one_hot, decimals=3), axis=1)\n ) / len(inferred_train)\n test_acc = np.sum(\n np.all(np.around(inferred_test, decimals=3) == np.around(test_one_hot, decimals=3), axis=1)\n ) / len(inferred_test)\n assert 0.1 <= train_acc\n assert 0.1 <= test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_meminf_label_only(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 0.6\n x[(x > 0.2) & (x <= 0.5)] = 0.35\n x[x <= 0.2] = 0.1\n\n values = [0.1, 0.35, 0.6]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n # test data with attacked feature (after transformation)\n x_test = np.concatenate((x_test_for_attack[:, :attack_feature], x_test_feature), axis=1)\n x_test = np.concatenate((x_test, x_test_for_attack[:, attack_feature:]), axis=1)\n\n classifier = decision_tree_estimator()\n\n meminf_attack = LabelOnlyDecisionBoundary(classifier, distance_threshold_tau=0.5)\n kwargs = {\n \"norm\": 2,\n \"max_iter\": 2,\n \"max_eval\": 4,\n \"init_eval\": 1,\n \"init_size\": 1,\n \"verbose\": False,\n }\n attack_train_ratio = 0.5\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n # attack without calibration\n attack = AttributeInferenceMembership(classifier, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature) / len(inferred_test)\n assert 0.5 <= train_acc\n assert 0.5 <= test_acc\n\n # attack with calibration\n meminf_attack.calibrate_distance_threshold(\n x_train[:attack_train_size],\n y_train_iris[:attack_train_size],\n x_test[:attack_test_size],\n y_test_iris[:attack_test_size],\n **kwargs\n )\n attack = AttributeInferenceMembership(classifier, meminf_attack, attack_feature=attack_feature)\n # infer attacked feature\n inferred_train = attack.infer(x_train_for_attack, y_train_iris, values=values)\n inferred_test = attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n train_acc = np.sum(inferred_train == x_train_feature) / len(inferred_train)\n test_acc = np.sum(inferred_test == x_test_feature) / len(inferred_test)\n assert 0.1 <= train_acc\n assert 0.1 <= test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_errors(art_warning, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(AttributeInferenceMembership)\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n meminf_attack = MembershipInferenceBlackBox(classifier, attack_model_type=\"nn\")\n\n with pytest.raises(ValueError):\n AttributeInferenceMembership(classifier, meminf_attack, attack_feature=\"a\")\n with pytest.raises(ValueError):\n AttributeInferenceMembership(classifier, meminf_attack, attack_feature=-3)\n\n attack = AttributeInferenceMembership(classifier, meminf_attack)\n with pytest.raises(ValueError):\n AttributeInferenceMembership(classifier, attack, attack_feature=1)\n with pytest.raises(ValueError):\n attack.infer(x_train, y_test, values=[1, 2])\n with pytest.raises(ValueError):\n attack.infer(x_train, y_train)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/attribute_inference/test_true_label_baseline.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OrdinalEncoder\n\nfrom art.attacks.inference.attribute_inference.true_label_baseline import AttributeInferenceBaselineTrueLabel\nfrom art.utils import check_and_transform_label_format\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y=y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y=y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.81, \"dt\": 0.98, \"knn\": 0.85, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.8, \"gb\": 0.74, \"lr\": 0.88, \"dt\": 0.75, \"knn\": 0.82, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_continuous(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type, is_continuous=True\n )\n # train attack model\n baseline_attack.fit(x_train_iris, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y=y_train_iris)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y=y_test_iris)\n # check accuracy\n assert (\n np.count_nonzero(np.isclose(baseline_inferred_train, x_train_feature.reshape(1, -1), atol=0.4))\n > baseline_inferred_train.shape[0] * 0.75\n )\n assert (\n np.count_nonzero(np.isclose(baseline_inferred_test, x_test_feature.reshape(1, -1), atol=0.4))\n > baseline_inferred_test.shape[0] * 0.75\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_column(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n y_train_iris = y_train_iris[:, 0]\n y_test_iris = y_test_iris[:, 0]\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y=y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y=y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.81, \"dt\": 0.98, \"knn\": 0.87, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.8, \"gb\": 0.75, \"lr\": 0.88, \"dt\": 0.75, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_no_values(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y=y_train_iris)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y=y_test_iris)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.81, \"dt\": 0.98, \"knn\": 0.85, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.81, \"gb\": 0.75, \"lr\": 0.88, \"dt\": 0.8, \"knn\": 0.82, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_true_label_baseline_slice(art_warning, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_feature(x_test_feature)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(attack_feature=slice(attack_feature, attack_feature + 1))\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y=y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y=y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n assert 0.8 <= baseline_train_acc\n assert 0.7 <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_regression(art_warning, get_diabetes_dataset, model_type):\n try:\n attack_feature = 1 # sex\n\n (x_train, y_train), (x_test, y_test) = get_diabetes_dataset\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train, attack_feature, 1)\n # only attacked feature\n x_train_feature = x_train[:, attack_feature].copy().reshape(-1, 1)\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test[:, attack_feature].copy().reshape(-1, 1)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type, is_regression=True\n )\n # train attack model\n baseline_attack.fit(x_train, y_train)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y=y_train)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y=y_test)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.45, \"rf\": 0.99, \"gb\": 0.97, \"lr\": 0.68, \"dt\": 0.99, \"knn\": 0.69, \"svm\": 0.54}\n expected_test_acc = {\"nn\": 0.45, \"rf\": 0.6, \"gb\": 0.65, \"lr\": 0.68, \"dt\": 0.54, \"knn\": 0.45, \"svm\": 0.47}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_encoder(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n categorical_transformer = OrdinalEncoder()\n encoder = ColumnTransformer(\n transformers=[\n (\"cat\", categorical_transformer, [other_feature]),\n ],\n remainder=\"passthrough\",\n )\n encoder.fit(x_train_for_attack)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type, encoder=encoder\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.96, \"gb\": 0.96, \"lr\": 0.81, \"dt\": 0.96, \"knn\": 0.9, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.77, \"gb\": 0.77, \"lr\": 0.88, \"dt\": 0.81, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_no_encoder(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type, non_numerical_features=[other_feature]\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.96, \"gb\": 0.96, \"lr\": 0.81, \"dt\": 0.96, \"knn\": 0.9, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.81, \"gb\": 0.77, \"lr\": 0.88, \"dt\": 0.82, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_no_encoder_after_feature(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.3] = 2.0\n x[(x > 0.2) & (x <= 0.3)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 3\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n new_other_feature = other_feature - 1\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, new_other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :new_other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, new_other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, new_other_feature, 1)\n x_test_other_feature = x_test_iris[:, new_other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate(\n (x_test_without_feature[:, :new_other_feature], x_test_other_feature), axis=1\n )\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, new_other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature, attack_model_type=model_type, non_numerical_features=[other_feature]\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.93, \"gb\": 0.95, \"lr\": 0.81, \"dt\": 0.94, \"knn\": 0.87, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.78, \"gb\": 0.8, \"lr\": 0.88, \"dt\": 0.74, \"knn\": 0.86, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_no_encoder_after_feature_slice(art_warning, get_iris_dataset, model_type):\n try:\n orig_attack_feature = 1 # petal length\n new_attack_feature = slice(1, 4) # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.3] = 2.0\n x[(x > 0.2) & (x <= 0.3)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, orig_attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, orig_attack_feature].copy()\n transform_attacked_feature(x_train_feature)\n x_train_feature = check_and_transform_label_format(x_train_feature, nb_classes=3, return_one_hot=True)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :orig_attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, orig_attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 5 # was 3 before 1-hot encoding of attacked feature\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n new_other_feature = other_feature - 3\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, new_other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :new_other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, new_other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, orig_attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, orig_attack_feature].copy()\n transform_attacked_feature(x_test_feature)\n x_test_feature = check_and_transform_label_format(x_test_feature, nb_classes=3, return_one_hot=True)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, new_other_feature, 1)\n x_test_other_feature = x_test_for_attack[:, new_other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate(\n (x_test_without_feature[:, :new_other_feature], x_test_other_feature), axis=1\n )\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, new_other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=new_attack_feature, attack_model_type=model_type, non_numerical_features=[other_feature]\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = np.argmax(baseline_attack.infer(x_train_for_attack, y_train_iris), axis=1)\n baseline_inferred_test = np.argmax(baseline_attack.infer(x_test_for_attack, y_test_iris), axis=1)\n x_train_feature = np.argmax(x_train_feature, axis=1)\n x_test_feature = np.argmax(x_test_feature, axis=1)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature) / len(baseline_inferred_train)\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature) / len(baseline_inferred_test)\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.98, \"gb\": 0.98, \"lr\": 0.81, \"dt\": 0.98, \"knn\": 0.85, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.86, \"gb\": 0.8, \"lr\": 0.88, \"dt\": 0.84, \"knn\": 0.82, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_true_label_baseline_no_encoder_remove_attack_feature(art_warning, get_iris_dataset, model_type):\n try:\n attack_feature = 2 # petal length\n\n # need to transform attacked feature into categorical\n def transform_attacked_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n\n def transform_other_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n values = [0.0, 1.0, 2.0]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n\n # training data without attacked feature\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n # transform attacked feature\n x_train_feature = x_train_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_train_feature)\n # training data with attacked feature (after transformation)\n x_train = np.concatenate((x_train_for_attack[:, :attack_feature], x_train_feature), axis=1)\n x_train = np.concatenate((x_train, x_train_for_attack[:, attack_feature:]), axis=1)\n\n # transform other feature\n other_feature = 1\n x_without_feature = np.delete(x_train, other_feature, 1)\n x_other_feature = x_train_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_other_feature)\n # training data with other feature (after transformation)\n x_train = np.concatenate((x_without_feature[:, :other_feature], x_other_feature), axis=1)\n x_train = np.concatenate((x_train, x_without_feature[:, other_feature:]), axis=1)\n\n x_train_for_attack_without_feature = np.delete(x_train_for_attack, other_feature, 1)\n x_train_for_attack = np.concatenate(\n (x_train_for_attack_without_feature[:, :other_feature], x_other_feature), axis=1\n )\n x_train_for_attack = np.concatenate(\n (x_train_for_attack, x_train_for_attack_without_feature[:, other_feature:]), axis=1\n )\n\n # test data without attacked feature\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n # only attacked feature\n x_test_feature = x_test_iris[:, attack_feature].copy().reshape(-1, 1)\n transform_attacked_feature(x_test_feature)\n\n # transform other feature\n x_test_without_feature = np.delete(x_test_for_attack, other_feature, 1)\n x_test_other_feature = x_test_iris[:, other_feature].copy().reshape(-1, 1).astype(object)\n transform_other_feature(x_test_other_feature)\n # training data with other feature (after transformation)\n x_test_for_attack = np.concatenate((x_test_without_feature[:, :other_feature], x_test_other_feature), axis=1)\n x_test_for_attack = np.concatenate((x_test_for_attack, x_test_without_feature[:, other_feature:]), axis=1)\n\n baseline_attack = AttributeInferenceBaselineTrueLabel(\n attack_feature=attack_feature,\n attack_model_type=model_type,\n non_numerical_features=[other_feature, attack_feature],\n )\n # train attack model\n baseline_attack.fit(x_train, y_train_iris)\n # infer attacked feature\n baseline_inferred_train = baseline_attack.infer(x_train_for_attack, y_train_iris, values=values)\n baseline_inferred_test = baseline_attack.infer(x_test_for_attack, y_test_iris, values=values)\n # check accuracy\n baseline_train_acc = np.sum(baseline_inferred_train == x_train_feature.reshape(1, -1)) / len(\n baseline_inferred_train\n )\n baseline_test_acc = np.sum(baseline_inferred_test == x_test_feature.reshape(1, -1)) / len(\n baseline_inferred_test\n )\n\n expected_train_acc = {\"nn\": 0.81, \"rf\": 0.96, \"gb\": 0.96, \"lr\": 0.81, \"dt\": 0.96, \"knn\": 0.9, \"svm\": 0.81}\n expected_test_acc = {\"nn\": 0.88, \"rf\": 0.82, \"gb\": 0.77, \"lr\": 0.88, \"dt\": 0.82, \"knn\": 0.84, \"svm\": 0.88}\n\n assert expected_train_acc[model_type] <= baseline_train_acc\n assert expected_test_acc[model_type] <= baseline_test_acc\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n AttributeInferenceBaselineTrueLabel(attack_feature=\"a\")\n\n with pytest.raises(ValueError):\n AttributeInferenceBaselineTrueLabel(attack_feature=-3)\n\n with pytest.raises(ValueError):\n AttributeInferenceBaselineTrueLabel(non_numerical_features=[\"a\"])\n\n with pytest.raises(ValueError):\n AttributeInferenceBaselineTrueLabel(encoder=\"a\")\n\n with pytest.raises(ValueError):\n AttributeInferenceBaselineTrueLabel(is_continuous=\"a\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/attribute_inference/test_white_box_decision_tree.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.inference.attribute_inference.white_box_decision_tree import AttributeInferenceWhiteBoxDecisionTree\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_white_box(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n values = [0.14, 0.42, 0.71] # rounded down\n priors = [50 / 150, 54 / 150, 46 / 150]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n x_train_feature = x_train_iris[:, attack_feature]\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n x_test_feature = x_test_iris[:, attack_feature]\n\n classifier = decision_tree_estimator()\n\n attack = AttributeInferenceWhiteBoxDecisionTree(classifier, attack_feature=attack_feature)\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, x_train_predictions, values=values, priors=priors)\n inferred_test = attack.infer(x_test_for_attack, x_test_predictions, values=values, priors=priors)\n train_diff = np.abs(inferred_train - x_train_feature.reshape(1, -1))\n test_diff = np.abs(inferred_test - x_test_feature.reshape(1, -1))\n assert np.sum(train_diff) / len(inferred_train) == pytest.approx(0.2108, abs=0.03)\n assert np.sum(test_diff) / len(inferred_test) == pytest.approx(0.1988, abs=0.03)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_check_params(art_warning, decision_tree_estimator):\n try:\n classifier = decision_tree_estimator()\n\n with pytest.raises(ValueError):\n _ = AttributeInferenceWhiteBoxDecisionTree(classifier, attack_feature=-5)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail():\n backend_test_classifier_type_check_fail(\n AttributeInferenceWhiteBoxDecisionTree, (ScikitlearnDecisionTreeClassifier,)\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/attribute_inference/test_white_box_lifestyle_decision_tree.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.inference.attribute_inference.white_box_lifestyle_decision_tree import (\n AttributeInferenceWhiteBoxLifestyleDecisionTree,\n)\nfrom art.estimators.classification.scikitlearn import ScikitlearnDecisionTreeClassifier\nfrom art.estimators.regression.scikitlearn import ScikitlearnDecisionTreeRegressor\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_white_box_lifestyle(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n attack_feature = 2 # petal length\n values = [0.14, 0.42, 0.71] # rounded down\n priors = [50 / 150, 54 / 150, 46 / 150]\n\n (x_train_iris, y_train_iris), (x_test_iris, y_test_iris) = get_iris_dataset\n x_train_for_attack = np.delete(x_train_iris, attack_feature, 1)\n x_train_feature = x_train_iris[:, attack_feature]\n x_test_for_attack = np.delete(x_test_iris, attack_feature, 1)\n x_test_feature = x_test_iris[:, attack_feature]\n\n classifier = decision_tree_estimator()\n attack = AttributeInferenceWhiteBoxLifestyleDecisionTree(classifier, attack_feature=attack_feature)\n x_train_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_train_iris)]).reshape(-1, 1)\n x_test_predictions = np.array([np.argmax(arr) for arr in classifier.predict(x_test_iris)]).reshape(-1, 1)\n inferred_train = attack.infer(x_train_for_attack, x_train_predictions, values=values, priors=priors)\n inferred_test = attack.infer(x_test_for_attack, x_test_predictions, values=values, priors=priors)\n train_diff = np.abs(inferred_train - x_train_feature.reshape(1, -1))\n test_diff = np.abs(inferred_test - x_test_feature.reshape(1, -1))\n assert np.sum(train_diff) / len(inferred_train) == pytest.approx(0.3357, abs=0.03)\n assert np.sum(test_diff) / len(inferred_test) == pytest.approx(0.3149, abs=0.03)\n # assert np.sum(train_diff) / len(inferred_train) < np.sum(test_diff) / len(inferred_test)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_white_box_lifestyle_regression(art_warning, get_diabetes_dataset):\n try:\n attack_feature = 0 # age\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, y_test_diabetes) = get_diabetes_dataset\n\n bins = [\n -0.96838121,\n -0.18102872,\n 0.21264752,\n 1.0,\n ]\n\n # need to transform attacked feature into categorical\n def transform_feature(x):\n orig = x.copy()\n for i in range(3):\n x[(orig >= bins[i]) & (orig <= bins[i + 1])] = i / 3\n\n values = [i / 3 for i in range(3)]\n priors = [154 / 442, 145 / 442, 143 / 442]\n\n x_train_for_attack = np.delete(x_train_diabetes, attack_feature, 1)\n x_train_feature = x_train_diabetes[:, attack_feature].copy()\n transform_feature(x_train_feature)\n\n x_test_for_attack = np.delete(x_test_diabetes, attack_feature, 1)\n x_test_feature = x_test_diabetes[:, attack_feature].copy()\n transform_feature(x_test_feature)\n\n from sklearn import tree\n\n regr_model = tree.DecisionTreeRegressor(random_state=7)\n regr_model.fit(x_train_diabetes, y_train_diabetes)\n regressor = ScikitlearnDecisionTreeRegressor(regr_model)\n\n attack = AttributeInferenceWhiteBoxLifestyleDecisionTree(regressor, attack_feature=attack_feature)\n\n x_train_predictions = regressor.predict(x_train_diabetes).reshape(-1, 1)\n x_test_predictions = regressor.predict(x_test_diabetes).reshape(-1, 1)\n\n inferred_train = attack.infer(x_train_for_attack, x_train_predictions, values=values, priors=priors)\n inferred_test = attack.infer(x_test_for_attack, x_test_predictions, values=values, priors=priors)\n\n train_diff = np.abs(inferred_train - x_train_feature.reshape(1, -1))\n test_diff = np.abs(inferred_test - x_test_feature.reshape(1, -1))\n assert np.sum(train_diff) / len(inferred_train) == pytest.approx(0.318, abs=0.1)\n assert np.sum(test_diff) / len(inferred_test) == pytest.approx(0.34, abs=0.12)\n # assert np.sum(train_diff) / len(inferred_train) < np.sum(test_diff) / len(inferred_test)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_check_params(art_warning, decision_tree_estimator):\n try:\n classifier = decision_tree_estimator()\n\n with pytest.raises(ValueError):\n _ = AttributeInferenceWhiteBoxLifestyleDecisionTree(classifier, attack_feature=-5)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail():\n backend_test_classifier_type_check_fail(\n AttributeInferenceWhiteBoxLifestyleDecisionTree,\n ((ScikitlearnDecisionTreeClassifier, ScikitlearnDecisionTreeRegressor),),\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/membership_inference/test_black_box.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nimport keras\n\nfrom art.attacks.inference.membership_inference.black_box import MembershipInferenceBlackBox\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\nfrom art.estimators.regression import ScikitlearnRegressor, RegressorMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\nattack_train_ratio = 0.5\nnum_classes_iris = 3\nnum_classes_mnist = 10\n\n\ndef test_black_box_image(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack = MembershipInferenceBlackBox(classifier)\n backend_check_membership_accuracy(attack, get_default_mnist_subset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_tabular(art_warning, model_type, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"scaler_type\", [\"standard\", \"robust\", \"minmax\"])\ndef test_black_box_tabular_scalers(art_warning, scaler_type, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n attack = MembershipInferenceBlackBox(classifier, scaler_type=scaler_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_black_box_tabular_no_scaler(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n attack = MembershipInferenceBlackBox(classifier, scaler_type=None)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_tabular_no_label(art_warning, model_type, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25, False)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_loss_tabular(art_warning, model_type, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n if type(classifier).__name__ == \"PyTorchClassifier\" or type(classifier).__name__ == \"TensorFlowV2Classifier\":\n attack = MembershipInferenceBlackBox(classifier, input_type=\"loss\", attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_tabular_dl(art_warning, model_type, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_tabular_no_label_dl(art_warning, model_type, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25, False)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_loss_tabular_dl(art_warning, model_type, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n if type(classifier).__name__ == \"PyTorchClassifier\" or type(classifier).__name__ == \"TensorFlowV2Classifier\":\n attack = MembershipInferenceBlackBox(classifier, input_type=\"loss\", attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_loss_regression(art_warning, model_type, get_diabetes_dataset):\n try:\n from sklearn import linear_model\n\n (x_train_diabetes, y_train_diabetes), _ = get_diabetes_dataset\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train_diabetes, y_train_diabetes)\n regressor = ScikitlearnRegressor(regr_model)\n\n attack = MembershipInferenceBlackBox(regressor, input_type=\"loss\", attack_model_type=model_type)\n backend_check_membership_accuracy(attack, get_diabetes_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"pytorch\", \"huggingface\", \"scikitlearn\", \"kerastf\")\n@pytest.mark.skipif(keras.__version__.startswith(\"2.2\"), reason=\"requires Keras 2.3.0 or higher\")\ndef test_black_box_keras_loss(art_warning, get_iris_dataset):\n try:\n (x_train, y_train), (_, _) = get_iris_dataset\n\n # This test creates a framework-specific (keras) model because it needs to check both the case of a string-based\n # loss and a class-based loss, and therefore cannot use the generic fixture get_tabular_classifier_list\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(8, input_dim=4, activation=\"relu\"))\n model.add(keras.layers.Dense(3, activation=\"softmax\"))\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n model.fit(x_train, y_train, epochs=150, batch_size=10)\n\n classifier = KerasClassifier(model)\n attack = MembershipInferenceBlackBox(classifier, input_type=\"loss\")\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n\n model2 = keras.models.Sequential()\n model2.add(keras.layers.Dense(12, input_dim=4, activation=\"relu\"))\n model2.add(keras.layers.Dense(3, activation=\"softmax\"))\n model2.compile(loss=keras.losses.CategoricalCrossentropy(), optimizer=\"adam\", metrics=[\"accuracy\"])\n model2.fit(x_train, y_train, epochs=150, batch_size=10)\n\n classifier = KerasClassifier(model2)\n attack = MembershipInferenceBlackBox(classifier, input_type=\"loss\")\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_black_box_with_model(art_warning, tabular_dl_estimator_for_attack, estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack_model = estimator_for_attack(num_features=2 * num_classes_iris)\n attack = MembershipInferenceBlackBox(classifier, attack_model=attack_model)\n backend_check_membership_accuracy(attack, get_iris_dataset, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_tabular_prob(art_warning, decision_tree_estimator, get_iris_dataset, model_type):\n try:\n classifier = decision_tree_estimator()\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n backend_check_membership_probabilities(attack, get_iris_dataset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_black_box_with_model_prob(art_warning, decision_tree_estimator, estimator_for_attack, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n attack_model = estimator_for_attack(num_features=2 * num_classes_iris)\n attack = MembershipInferenceBlackBox(classifier, attack_model=attack_model)\n backend_check_membership_probabilities(attack, get_iris_dataset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_pred(art_warning, model_type, decision_tree_estimator, get_iris_dataset):\n try:\n (x_train, _), (x_test, _) = get_iris_dataset\n classifier = decision_tree_estimator()\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n pred_x = classifier.predict(x_train)\n test_pred_x = classifier.predict(x_test)\n pred = (pred_x, test_pred_x)\n backend_check_membership_accuracy_pred(attack, get_iris_dataset, pred, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_tabular_prob_dl(art_warning, tabular_dl_estimator_for_attack, get_iris_dataset, model_type):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n backend_check_membership_probabilities(attack, get_iris_dataset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_black_box_with_model_prob_dl(\n art_warning, tabular_dl_estimator_for_attack, estimator_for_attack, get_iris_dataset\n):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack_model = estimator_for_attack(num_features=2 * num_classes_iris)\n attack = MembershipInferenceBlackBox(classifier, attack_model=attack_model)\n backend_check_membership_probabilities(attack, get_iris_dataset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_pred_dl(art_warning, model_type, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n (x_train, _), (x_test, _) = get_iris_dataset\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n attack = MembershipInferenceBlackBox(classifier, attack_model_type=model_type)\n pred_x = classifier.predict(x_train)\n test_pred_x = classifier.predict(x_test)\n pred = (pred_x, test_pred_x)\n backend_check_membership_accuracy_pred(attack, get_iris_dataset, pred, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"nn\", \"rf\", \"gb\", \"lr\", \"dt\", \"knn\", \"svm\"])\ndef test_black_box_loss_regression_pred(art_warning, model_type, get_diabetes_dataset):\n try:\n from sklearn import linear_model\n\n (x_train_diabetes, y_train_diabetes), (x_test_diabetes, _) = get_diabetes_dataset\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train_diabetes, y_train_diabetes)\n regressor = ScikitlearnRegressor(regr_model)\n pred_x = regr_model.predict(x_train_diabetes)\n test_pred_x = regr_model.predict(x_test_diabetes)\n pred = (pred_x, test_pred_x)\n attack = MembershipInferenceBlackBox(regressor, input_type=\"loss\", attack_model_type=model_type)\n backend_check_membership_accuracy_pred(attack, get_diabetes_dataset, pred, attack_train_ratio, 0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_errors(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n with pytest.raises(ValueError):\n MembershipInferenceBlackBox(classifier, attack_model_type=\"a\")\n with pytest.raises(ValueError):\n MembershipInferenceBlackBox(classifier, input_type=\"a\")\n attack = MembershipInferenceBlackBox(classifier)\n with pytest.raises(ValueError):\n attack.fit(x_train, y_test, x_test, y_test)\n with pytest.raises(ValueError):\n attack.fit(x_train, y_train, x_test, y_train)\n with pytest.raises(ValueError):\n attack.infer(x_train, y_test)\n attack.fit(x_train, y_train, x_test, y_test)\n with pytest.raises(ValueError):\n attack.infer(x_test, y_test=None)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_errors_dl(art_warning, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n pred_test = classifier.predict(x_test)\n with pytest.raises(ValueError):\n MembershipInferenceBlackBox(classifier, attack_model_type=\"a\")\n with pytest.raises(ValueError):\n MembershipInferenceBlackBox(classifier, input_type=\"a\")\n attack = MembershipInferenceBlackBox(classifier)\n with pytest.raises(ValueError):\n attack.fit(x_train, y_test, x_test, y_test)\n with pytest.raises(ValueError):\n attack.fit(x_train, y_train, x_test, y_train)\n with pytest.raises(ValueError):\n attack.infer(x_train, y_test)\n attack.fit(x_train, y_train, x_test, y_test)\n with pytest.raises(ValueError):\n attack.infer(x_test, y_test=None)\n attack = MembershipInferenceBlackBox(classifier, input_type=\"loss\")\n with pytest.raises(ValueError):\n attack.fit(x_train, test_x=x_test)\n attack.fit(x_train, y_train, x_test, y_test)\n with pytest.raises(ValueError):\n attack.infer(None, y_test, pred=pred_test)\n with pytest.raises(ValueError):\n attack.infer(x_test, y_test=None)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(\n MembershipInferenceBlackBox, [BaseEstimator, (ClassifierMixin, RegressorMixin)]\n )\n except ARTTestException as e:\n art_warning(e)\n\n\ndef backend_check_membership_accuracy(attack, dataset, attack_train_ratio, approx, use_label=True):\n (x_train, y_train), (x_test, y_test) = dataset\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n\n # train attack model using only attack_train_ratio of data\n if use_label:\n attack.fit(\n x_train[:attack_train_size],\n y_train[:attack_train_size],\n x_test[:attack_test_size],\n y_test[:attack_test_size],\n )\n # infer attacked feature on remainder of data\n inferred_train = attack.infer(x_train[attack_train_size:], y_train[attack_train_size:])\n inferred_test = attack.infer(x_test[attack_test_size:], y_test[attack_test_size:])\n else:\n attack.fit(x_train[:attack_train_size], test_x=x_test[:attack_test_size])\n # infer attacked feature on remainder of data\n inferred_train = attack.infer(x_train[attack_train_size:])\n inferred_test = attack.infer(x_test[attack_test_size:])\n\n # check accuracy\n backend_check_accuracy(inferred_train, inferred_test, approx)\n\n\ndef backend_check_membership_accuracy_pred(attack, dataset, pred, attack_train_ratio, approx):\n (x_train, y_train), (x_test, y_test) = dataset\n (pred_x, test_pred_x) = pred\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n\n # train attack model using only attack_train_ratio of data\n attack.fit(\n None,\n y_train[:attack_train_size],\n None,\n y_test[:attack_test_size],\n pred_x[:attack_train_size],\n test_pred_x[:attack_test_size],\n )\n\n # infer attacked feature on remainder of data\n inferred_train = attack.infer(None, y_train[attack_train_size:], pred=pred_x[attack_train_size:])\n inferred_test = attack.infer(\n None,\n y_test[attack_test_size:],\n pred=test_pred_x[attack_test_size:],\n )\n\n # check accuracy\n backend_check_accuracy(inferred_train, inferred_test, approx)\n\n\ndef backend_check_accuracy(inferred_train, inferred_test, approx):\n train_pos = sum(inferred_train) / len(inferred_train)\n test_pos = sum(inferred_test) / len(inferred_test)\n assert train_pos > test_pos or train_pos == pytest.approx(test_pos, abs=approx) or test_pos == 1\n\n\ndef backend_check_membership_probabilities(attack, dataset, attack_train_ratio):\n (x_train, y_train), (x_test, y_test) = dataset\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n\n # train attack model using only attack_train_ratio of data\n attack.fit(\n x_train[:attack_train_size], y_train[:attack_train_size], x_test[:attack_test_size], y_test[:attack_test_size]\n )\n\n # infer attacked feature on remainder of data\n inferred_train_pred = attack.infer(x_train[attack_train_size:], y_train[attack_train_size:])\n inferred_train_prob = attack.infer(x_train[attack_train_size:], y_train[attack_train_size:], probabilities=True)\n\n # check accuracy\n backend_check_probabilities(inferred_train_pred, inferred_train_prob)\n\n\ndef backend_check_probabilities(pred, prob):\n assert prob.shape[1] == 1\n assert np.all(np.round(prob) == pred.astype(int))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/membership_inference/test_black_box_rule_based.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.attacks.inference.membership_inference.black_box_rule_based import MembershipInferenceBlackBoxRuleBased\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\nattack_train_ratio = 0.5\nnum_classes_iris = 3\nnum_classes_mnist = 10\n\n\ndef test_rule_based_image(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(MembershipInferenceBlackBoxRuleBased)\n attack = MembershipInferenceBlackBoxRuleBased(classifier)\n backend_check_membership_accuracy_no_fit(attack, get_default_mnist_subset, 0.8)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_rule_based_tabular(art_warning, get_iris_dataset, tabular_dl_estimator_for_attack):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBoxRuleBased)\n attack = MembershipInferenceBlackBoxRuleBased(classifier)\n backend_check_membership_accuracy_no_fit(attack, get_iris_dataset, 0.06)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_rule_based_tabular_prob(art_warning, get_iris_dataset, tabular_dl_estimator_for_attack):\n try:\n classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBoxRuleBased)\n attack = MembershipInferenceBlackBoxRuleBased(classifier)\n backend_check_membership_probabilities(attack, get_iris_dataset)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(MembershipInferenceBlackBoxRuleBased, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n\ndef backend_check_membership_accuracy_no_fit(attack, dataset, approx):\n (x_train, y_train), (x_test, y_test) = dataset\n # infer attacked feature\n inferred_train = attack.infer(x_train, y_train)\n inferred_test = attack.infer(x_test, y_test)\n # check accuracy\n backend_check_accuracy(inferred_train, inferred_test, approx)\n\n\ndef backend_check_accuracy(inferred_train, inferred_test, approx):\n train_pos = sum(inferred_train) / len(inferred_train)\n test_pos = sum(inferred_test) / len(inferred_test)\n assert train_pos > test_pos or train_pos == pytest.approx(test_pos, abs=approx) or test_pos == 1\n\n\ndef backend_check_membership_probabilities(attack, dataset):\n (x_train, y_train), _ = dataset\n\n # infer attacked feature on remainder of data\n inferred_train_pred = attack.infer(x_train, y_train)\n inferred_train_prob = attack.infer(x_train, y_train, probabilities=True)\n\n # check accuracy\n backend_check_probabilities(inferred_train_pred, inferred_train_prob)\n\n\ndef backend_check_probabilities(pred, prob):\n assert prob.shape[1] == 2\n assert np.all(np.sum(prob, axis=1) == 1)\n assert np.all(np.argmax(prob, axis=1) == pred.astype(int))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/membership_inference/test_label_only_boundary_distance.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.attacks.inference.membership_inference.label_only_boundary_distance import LabelOnlyDecisionBoundary\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\nattack_train_ratio = 0.5\n\n\ndef test_label_only_boundary_distance_image(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(LabelOnlyDecisionBoundary)\n attack = LabelOnlyDecisionBoundary(classifier, distance_threshold_tau=0.5)\n backend_check_membership_accuracy(attack, get_default_mnist_subset, attack_train_ratio, 0.05)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_label_only_boundary_distance_prob(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(LabelOnlyDecisionBoundary)\n attack = LabelOnlyDecisionBoundary(classifier, distance_threshold_tau=0.5)\n backend_check_membership_probabilities(attack, get_default_mnist_subset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_label_only_boundary_distance_prob_calib(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(LabelOnlyDecisionBoundary)\n attack = LabelOnlyDecisionBoundary(classifier)\n (x_train, y_train), (x_test, y_test) = get_default_mnist_subset\n kwargs = {\n \"norm\": 2,\n \"max_iter\": 2,\n \"max_eval\": 4,\n \"init_eval\": 1,\n \"init_size\": 1,\n \"verbose\": False,\n }\n attack.calibrate_distance_threshold(x_train, y_train, x_test, y_test, **kwargs)\n backend_check_membership_probabilities(attack, get_default_mnist_subset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_label_only_boundary_distance_prob_calib_unsup(\n art_warning, get_default_mnist_subset, image_dl_estimator_for_attack\n):\n try:\n classifier = image_dl_estimator_for_attack(LabelOnlyDecisionBoundary)\n attack = LabelOnlyDecisionBoundary(classifier)\n kwargs = {\n \"norm\": 2,\n \"max_iter\": 2,\n \"max_eval\": 4,\n \"init_eval\": 1,\n \"init_size\": 1,\n \"verbose\": False,\n }\n attack.calibrate_distance_threshold_unsupervised(50, 100, 1, **kwargs)\n backend_check_membership_probabilities(attack, get_default_mnist_subset, attack_train_ratio)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(LabelOnlyDecisionBoundary, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n\ndef backend_check_membership_accuracy(attack, dataset, attack_train_ratio, approx):\n (x_train, y_train), (x_test, y_test) = dataset\n attack_train_size = int(len(x_train) * attack_train_ratio)\n attack_test_size = int(len(x_test) * attack_train_ratio)\n\n # infer attacked feature on remainder of data\n kwargs = {\n \"norm\": 2,\n \"max_iter\": 2,\n \"max_eval\": 4,\n \"init_eval\": 1,\n \"init_size\": 1,\n \"verbose\": False,\n }\n inferred_train = attack.infer(x_train[attack_train_size:], y_train[attack_train_size:], **kwargs)\n inferred_test = attack.infer(x_test[attack_test_size:], y_test[attack_test_size:], **kwargs)\n\n # check accuracy\n backend_check_accuracy(inferred_train, inferred_test, approx)\n\n\ndef backend_check_accuracy(inferred_train, inferred_test, approx):\n train_pos = sum(inferred_train) / len(inferred_train)\n test_pos = sum(inferred_test) / len(inferred_test)\n assert train_pos > test_pos or train_pos == pytest.approx(test_pos, abs=approx) or test_pos == 1\n\n\ndef backend_check_membership_probabilities(attack, dataset, attack_train_ratio):\n (x_train, y_train), _ = dataset\n attack_train_size = int(len(x_train) * attack_train_ratio)\n\n kwargs = {\n \"norm\": 2,\n \"max_iter\": 2,\n \"max_eval\": 4,\n \"init_eval\": 1,\n \"init_size\": 1,\n \"verbose\": False,\n }\n # infer attacked feature on remainder of data\n inferred_train_prob = attack.infer(\n x_train[attack_train_size:], y_train[attack_train_size:], probabilities=True, **kwargs\n )\n\n # check accuracy\n backend_check_probabilities(inferred_train_prob)\n\n\ndef backend_check_probabilities(prob):\n assert prob.shape[1] == 2\n assert np.all(np.sum(prob, axis=1) == 1)\n\n\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(LabelOnlyDecisionBoundary)\n\n with pytest.raises(ValueError):\n _ = LabelOnlyDecisionBoundary(classifier, distance_threshold_tau=-0.5)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/membership_inference/test_label_only_gap_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nfrom art.attacks.inference.membership_inference.label_only_gap_attack import LabelOnlyGapAttack\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\nattack_train_ratio = 0.5\nnum_classes_iris = 3\nnum_classes_mnist = 10\n\n\ndef test_rule_based_image(art_warning, get_default_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(LabelOnlyGapAttack)\n attack = LabelOnlyGapAttack(classifier)\n backend_check_membership_accuracy_no_fit(attack, get_default_mnist_subset, 0.8)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_rule_based_tabular(art_warning, get_iris_dataset, tabular_dl_estimator_for_attack):\n try:\n classifier = tabular_dl_estimator_for_attack(LabelOnlyGapAttack)\n attack = LabelOnlyGapAttack(classifier)\n backend_check_membership_accuracy_no_fit(attack, get_iris_dataset, 0.06)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(LabelOnlyGapAttack, [BaseEstimator, ClassifierMixin])\n except ARTTestException as e:\n art_warning(e)\n\n\ndef backend_check_membership_accuracy_no_fit(attack, dataset, approx):\n (x_train, y_train), (x_test, y_test) = dataset\n # infer attacked feature\n inferred_train = attack.infer(x_train, y_train)\n inferred_test = attack.infer(x_test, y_test)\n # check accuracy\n backend_check_accuracy(inferred_train, inferred_test, approx)\n\n\ndef backend_check_accuracy(inferred_train, inferred_test, approx):\n train_pos = sum(inferred_train) / len(inferred_train)\n test_pos = sum(inferred_test) / len(inferred_test)\n assert train_pos > test_pos or train_pos == pytest.approx(test_pos, abs=approx) or test_pos == 1\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/membership_inference/test_shadow_models.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom art.attacks.inference.membership_inference.black_box import MembershipInferenceBlackBox\nfrom art.attacks.inference.membership_inference.shadow_models import ShadowModels\nfrom art.estimators.classification.scikitlearn import ScikitlearnRandomForestClassifier, ScikitlearnClassifier\nfrom art.utils import load_nursery, to_categorical\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"scikitlearn\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_shadow_model_bb_attack(art_warning, tabular_dl_estimator_for_attack, get_iris_dataset):\n try:\n art_classifier = tabular_dl_estimator_for_attack(MembershipInferenceBlackBox)\n (x_target, y_target), (x_shadow, y_shadow) = get_iris_dataset\n target_train_size = len(x_target) // 2\n x_target_train = x_target[:target_train_size]\n y_target_train = y_target[:target_train_size]\n x_target_test = x_target[target_train_size:]\n y_target_test = y_target[target_train_size:]\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=1, random_state=7)\n shadow_dataset = shadow_models.generate_shadow_dataset(x_shadow, y_shadow)\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n\n attack = MembershipInferenceBlackBox(art_classifier, attack_model_type=\"rf\")\n attack.fit(mem_x, mem_y, nonmem_x, nonmem_y, mem_pred, nonmem_pred)\n\n mem_infer = attack.infer(x_target_train, y_target_train)\n nonmem_infer = attack.infer(x_target_test, y_target_test)\n mem_acc = np.sum(mem_infer) / len(mem_infer)\n nonmem_acc = 1 - (np.sum(nonmem_infer) / len(nonmem_infer))\n accuracy = (mem_acc * len(mem_infer) + nonmem_acc * len(nonmem_infer)) / (len(mem_infer) + len(nonmem_infer))\n\n assert accuracy == pytest.approx(0.7, abs=0.25)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_shadow_model_bb_attack_nonumeric(art_warning, get_iris_dataset):\n try:\n (x_target, y_target), (x_shadow, y_shadow) = get_iris_dataset\n\n def transform_feature(x):\n x[x > 0.5] = 2.0\n x[(x > 0.2) & (x <= 0.5)] = 1.0\n x[x <= 0.2] = 0.0\n x[x == 2.0] = \"A\"\n x[x == 1.0] = \"B\"\n x[x == 0.0] = \"C\"\n\n feature = 1\n x_without_feature = np.delete(x_target, feature, 1)\n x_feature = x_target[:, feature].copy().reshape(-1, 1).astype(object)\n transform_feature(x_feature)\n # training data with feature (after transformation)\n x_target = np.concatenate((x_without_feature[:, :feature], x_feature), axis=1)\n x_target = np.concatenate((x_target, x_without_feature[:, feature:]), axis=1)\n\n x_shadow_without_feature = np.delete(x_shadow, feature, 1)\n x_shadow_feature = x_shadow[:, feature].copy().reshape(-1, 1).astype(object)\n transform_feature(x_shadow_feature)\n # shadow data with feature (after transformation)\n x_shadow = np.concatenate((x_shadow_without_feature[:, :feature], x_shadow_feature), axis=1)\n x_shadow = np.concatenate((x_shadow, x_shadow_without_feature[:, feature:]), axis=1)\n\n target_train_size = len(x_target) // 2\n x_target_train = x_target[:target_train_size]\n y_target_train = y_target[:target_train_size]\n x_target_test = x_target[target_train_size:]\n y_target_test = y_target[target_train_size:]\n\n from sklearn.preprocessing import OneHotEncoder\n from sklearn.pipeline import Pipeline\n\n encoder = OneHotEncoder(handle_unknown=\"ignore\")\n model = RandomForestClassifier()\n pipeline = Pipeline([(\"encoder\", encoder), (\"model\", model)])\n pipeline.fit(x_target_train, np.argmax(y_target_train, axis=1))\n art_classifier = ScikitlearnClassifier(pipeline, preprocessing=None)\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=1, random_state=7)\n shadow_dataset = shadow_models.generate_shadow_dataset(x_shadow, y_shadow)\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n\n attack = MembershipInferenceBlackBox(art_classifier, attack_model_type=\"rf\")\n attack.fit(mem_x, mem_y, nonmem_x, nonmem_y, mem_pred, nonmem_pred)\n\n mem_infer = attack.infer(x_target_train, y_target_train)\n nonmem_infer = attack.infer(x_target_test, y_target_test)\n mem_acc = np.sum(mem_infer) / len(mem_infer)\n nonmem_acc = 1 - (np.sum(nonmem_infer) / len(nonmem_infer))\n accuracy = (mem_acc * len(mem_infer) + nonmem_acc * len(nonmem_infer)) / (len(mem_infer) + len(nonmem_infer))\n\n assert accuracy == pytest.approx(0.7, abs=0.2)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_shadow_model_bb_attack_rf(art_warning):\n try:\n (x_target, y_target), (x_shadow, y_shadow), _, _ = load_nursery(test_set=0.5)\n\n target_train_size = len(x_target) // 2\n x_target_train = x_target[:target_train_size]\n y_target_train = y_target[:target_train_size]\n x_target_test = x_target[target_train_size:]\n y_target_test = y_target[target_train_size:]\n\n model = RandomForestClassifier(random_state=7)\n model.fit(x_target_train, y_target_train)\n art_classifier = ScikitlearnRandomForestClassifier(model)\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=1, random_state=7)\n shadow_dataset = shadow_models.generate_shadow_dataset(x_shadow, to_categorical(y_shadow, 4))\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n\n attack = MembershipInferenceBlackBox(art_classifier, attack_model_type=\"rf\")\n attack.fit(mem_x, mem_y, nonmem_x, nonmem_y, mem_pred, nonmem_pred)\n\n mem_infer = attack.infer(x_target_train, y_target_train)\n nonmem_infer = attack.infer(x_target_test, y_target_test)\n mem_acc = np.sum(mem_infer) / len(mem_infer)\n nonmem_acc = 1 - (np.sum(nonmem_infer) / len(nonmem_infer))\n accuracy = (mem_acc * len(mem_infer) + nonmem_acc * len(nonmem_infer)) / (len(mem_infer) + len(nonmem_infer))\n\n assert accuracy == pytest.approx(0.7, abs=0.2)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_synthetic_shadow_model(art_warning):\n try:\n (x_train, y_train), (_, _), _, _ = load_nursery(test_set=0.2)\n\n model = RandomForestClassifier(random_state=7)\n model.fit(x_train, y_train)\n art_classifier = ScikitlearnRandomForestClassifier(model)\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=1, random_state=7)\n record_rng = np.random.default_rng(seed=7)\n\n def random_record() -> np.ndarray:\n children_values = [0.0, 0.33333333, 0.66666667, 1.0]\n categorical_features = [3, 5, 4, 3, 2, 3, 3]\n empty_record = np.zeros(1 + np.sum(categorical_features))\n empty_record[0] = record_rng.choice(children_values)\n\n offset = 1\n for feature_options in categorical_features:\n chosen_option = record_rng.integers(feature_options)\n empty_record[offset + chosen_option] = 1.0\n offset += feature_options\n\n return empty_record\n\n def randomize_features(record: np.ndarray, num_features: int) -> np.ndarray:\n children_values = [0.0, 0.33333333, 0.66666667, 1.0]\n categorical_features = [3, 5, 4, 3, 2, 3, 3]\n\n new_record = record.copy()\n for feature in record_rng.choice(8, size=num_features):\n if feature == 0:\n new_record[0] = record_rng.choice(children_values)\n else:\n cat_feature = feature - 1\n\n one_hot = np.zeros(categorical_features[cat_feature])\n one_hot[record_rng.integers(categorical_features[cat_feature])] = 1.0\n\n feature_offset = 1 + np.sum(categorical_features[:cat_feature], dtype=np.int64)\n new_record[feature_offset : feature_offset + categorical_features[cat_feature]] = one_hot\n\n return new_record\n\n shadow_dataset = shadow_models.generate_synthetic_shadow_dataset(\n art_classifier,\n 40,\n max_features_randomized=8,\n random_record_fn=random_record,\n randomize_features_fn=randomize_features,\n )\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n\n assert len(mem_x) == len(mem_y)\n assert len(mem_y) == len(mem_pred)\n assert len(nonmem_x) == len(nonmem_y)\n assert len(nonmem_y) == len(nonmem_pred)\n assert len(mem_x) + len(mem_y) == 40\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_shadow_model_default_randomisation(art_warning):\n try:\n (x_train, y_train), (_, _), _, _ = load_nursery(test_set=0.2)\n\n model = RandomForestClassifier(random_state=7)\n model.fit(x_train, y_train)\n art_classifier = ScikitlearnRandomForestClassifier(model)\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=1, random_state=7)\n\n shadow_dataset = shadow_models.generate_synthetic_shadow_dataset(\n art_classifier,\n dataset_size=40,\n max_features_randomized=8,\n min_confidence=0.2,\n max_retries=15,\n random_record_fn=None,\n randomize_features_fn=None,\n )\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n\n assert len(mem_x) == len(mem_y)\n assert len(mem_y) == len(mem_pred)\n assert len(nonmem_x) == len(nonmem_y)\n assert len(nonmem_y) == len(nonmem_pred)\n assert len(mem_x) + len(mem_y) == 40\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_shadow_model_disjoint(art_warning):\n try:\n (x_target, y_target), (x_shadow, y_shadow), _, _ = load_nursery(test_set=0.5)\n\n target_train_size = len(x_target) // 2\n x_target_train = x_target[:target_train_size]\n y_target_train = y_target[:target_train_size]\n\n model = RandomForestClassifier(random_state=7)\n model.fit(x_target_train, y_target_train)\n art_classifier = ScikitlearnRandomForestClassifier(model)\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=2, disjoint_datasets=True)\n shadow_dataset = shadow_models.generate_shadow_dataset(x_shadow, to_categorical(y_shadow, 4))\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n models = shadow_models.get_shadow_models()\n train_sets = shadow_models.get_shadow_models_train_sets()\n\n assert len(models) == 2\n assert len(train_sets) == 2\n assert len(mem_x) == len(x_target) // 2 - 1\n assert len(train_sets[0][0]) == len(x_target) // 4\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_shadow_model_overlap(art_warning):\n try:\n (x_target, y_target), (x_shadow, y_shadow), _, _ = load_nursery(test_set=0.5)\n\n target_train_size = len(x_target) // 2\n x_target_train = x_target[:target_train_size]\n y_target_train = y_target[:target_train_size]\n\n model = RandomForestClassifier(random_state=7)\n model.fit(x_target_train, y_target_train)\n art_classifier = ScikitlearnRandomForestClassifier(model)\n\n shadow_models = ShadowModels(art_classifier, num_shadow_models=2)\n shadow_dataset = shadow_models.generate_shadow_dataset(x_shadow, to_categorical(y_shadow, 4))\n (mem_x, mem_y, mem_pred), (nonmem_x, nonmem_y, nonmem_pred) = shadow_dataset\n models = shadow_models.get_shadow_models()\n train_sets = shadow_models.get_shadow_models_train_sets()\n\n assert len(models) == 2\n assert len(train_sets) == 2\n assert len(mem_x) == len(x_target)\n assert len(train_sets[0][0]) == len(x_target) // 2\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/inference/model_inversion/test_mi_face.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.inference.model_inversion import MIFace\nfrom art.estimators.estimator import BaseEstimator\nfrom art.estimators.classification.classifier import ClassifierMixin, ClassGradientsMixin\n\nfrom tests.attacks.utils import backend_test_classifier_type_check_fail\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\ndef backend_check_inferred_values(attack, mnist_dataset, classifier):\n # We assert that, when starting with zero information about the inputs x, we are able to infer - for each\n # class - a representative sample that is classified by the classifier as belonging to that class:\n\n x_train_infer_from_zero = attack.infer(None, y=np.arange(10))\n preds = np.argmax(classifier.predict(x_train_infer_from_zero), axis=1)\n np.testing.assert_array_equal(preds, np.arange(10))\n\n # Next we would like to assert that, when starting with blurry training instances, the inference attack will result\n # in instances that more closely resemble the original instances. However, this turns out not to be the case in\n # this scenario:\n\n (x_train_mnist, y_train_mnist, _, _) = mnist_dataset\n x_original = x_train_mnist[:10]\n x_noisy = np.clip(x_original + np.random.uniform(-0.01, 0.01, x_original.shape), 0, 1)\n x_train_infer_from_noisy = attack.infer(x_noisy, y=y_train_mnist[:10])\n\n diff_noisy = np.mean(np.reshape(np.abs(x_original - x_noisy), (len(x_original), -1)), axis=1)\n diff_inferred = np.mean(np.reshape(np.abs(x_original - x_train_infer_from_noisy), (len(x_original), -1)), axis=1)\n\n np.testing.assert_array_less(diff_noisy, diff_inferred)\n\n\n@pytest.mark.framework_agnostic\ndef test_miface(art_warning, fix_get_mnist_subset, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(MIFace)\n\n # for the one-shot method, frame saliency attack should resort to plain FastGradientMethod\n # expected_values = {\n # \"x_test_mean\": ExpectedValue(0.2346725, 0.002),\n # \"x_test_min\": ExpectedValue(-1.0, 0.00001),\n # \"x_test_max\": ExpectedValue(1.0, 0.00001),\n # \"y_test_pred_adv_expected\": ExpectedValue(np.asarray([4, 4, 4, 7, 7, 4, 7, 2, 2, 3, 0]), 2),\n # }\n\n attack = MIFace(classifier, max_iter=150, batch_size=3)\n backend_check_inferred_values(attack, fix_get_mnist_subset, classifier)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_check_params(art_warning, image_dl_estimator_for_attack):\n try:\n classifier = image_dl_estimator_for_attack(MIFace)\n\n with pytest.raises(ValueError):\n _ = MIFace(classifier, max_iter=-0.5)\n\n with pytest.raises(ValueError):\n _ = MIFace(classifier, window_length=-0.5)\n\n with pytest.raises(ValueError):\n _ = MIFace(classifier, threshold=-0.5)\n\n with pytest.raises(ValueError):\n _ = MIFace(classifier, learning_rate=-0.5)\n\n with pytest.raises(ValueError):\n _ = MIFace(classifier, batch_size=-0.5)\n\n with pytest.raises(ValueError):\n _ = MIFace(classifier, verbose=-0.5)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_classifier_type_check_fail(art_warning):\n try:\n backend_test_classifier_type_check_fail(MIFace, [BaseEstimator, ClassifierMixin, ClassGradientsMixin])\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_audio_perturbations.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\nimport os\n\nfrom art.attacks.poisoning.perturbations.audio_perturbations import CacheToneTrigger, CacheAudioTrigger\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\ndef test_insert_tone_trigger(art_warning):\n try:\n # test single example\n trigger = CacheToneTrigger(sampling_rate=16000)\n audio = trigger.insert(x=np.zeros(3200))\n assert audio.shape == (3200,)\n assert np.max(audio) != 0\n assert np.max(np.abs(audio)) <= 1.0\n\n # test single example with different duration, frequency, and scale\n trigger = CacheToneTrigger(sampling_rate=16000, frequency=16000, duration=0.2, scale=0.5)\n audio = trigger.insert(x=np.zeros(3200))\n assert audio.shape == (3200,)\n assert np.max(audio) != 0\n\n # test a batch of examples\n audio = trigger.insert(x=np.zeros((10, 3200)))\n assert audio.shape == (10, 3200)\n assert np.max(audio) != 0\n\n # test single example with shift\n trigger = CacheToneTrigger(sampling_rate=16000, shift=10)\n audio = trigger.insert(x=np.zeros(3200))\n assert audio.shape == (3200,)\n assert np.max(audio) != 0\n assert np.sum(audio[:10]) == 0\n\n # test a batch of examples with random shift\n trigger = CacheToneTrigger(sampling_rate=16000, random=True)\n audio = trigger.insert(x=np.zeros((10, 3200)))\n assert audio.shape == (10, 3200)\n assert np.max(audio) != 0\n\n # test when length of backdoor is larger than that of audio signal\n with pytest.raises(ValueError):\n trigger = CacheToneTrigger(sampling_rate=16000, duration=0.3)\n _ = trigger.insert(x=np.zeros(3200))\n\n # test when shift + backdoor is larger than that of audio signal\n with pytest.raises(ValueError):\n trigger = CacheToneTrigger(sampling_rate=16000, duration=0.2, shift=5)\n _ = trigger.insert(x=np.zeros(3200))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_insert_audio_trigger(art_warning):\n file_path = os.path.join(os.getcwd(), \"utils/data/backdoors/cough_trigger.wav\")\n try:\n # test single example\n trigger = CacheAudioTrigger(sampling_rate=16000, backdoor_path=file_path)\n audio = trigger.insert(x=np.zeros(32000))\n assert audio.shape == (32000,)\n assert np.max(audio) != 0\n assert np.max(np.abs(audio)) <= 1.0\n\n # test single example with different duration and scale\n trigger = CacheAudioTrigger(\n sampling_rate=16000,\n backdoor_path=file_path,\n duration=0.8,\n scale=0.5,\n )\n audio = trigger.insert(x=np.zeros(32000))\n assert audio.shape == (32000,)\n assert np.max(audio) != 0\n\n # test a batch of examples\n trigger = CacheAudioTrigger(sampling_rate=16000, backdoor_path=file_path)\n audio = trigger.insert(x=np.zeros((10, 16000)))\n\n assert audio.shape == (10, 16000)\n assert np.max(audio) != 0\n\n # test single example with shift\n trigger = CacheAudioTrigger(sampling_rate=16000, backdoor_path=file_path, shift=10)\n audio = trigger.insert(x=np.zeros(32000))\n assert audio.shape == (32000,)\n assert np.max(audio) != 0\n assert np.sum(audio[:10]) == 0\n\n # test a batch of examples with random shift\n trigger = CacheAudioTrigger(sampling_rate=16000, backdoor_path=file_path, random=True)\n audio = trigger.insert(x=np.zeros((10, 32000)))\n assert audio.shape == (10, 32000)\n assert np.max(audio) != 0\n\n # test when length of backdoor is larger than that of audio signal\n with pytest.raises(ValueError):\n trigger = CacheAudioTrigger(sampling_rate=16000, backdoor_path=file_path)\n _ = trigger.insert(x=np.zeros(15000))\n\n # test when shift + backdoor is larger than that of audio signal\n with pytest.raises(ValueError):\n trigger = CacheAudioTrigger(\n sampling_rate=16000,\n backdoor_path=file_path,\n duration=1,\n shift=5,\n )\n _ = trigger.insert(x=np.zeros(16000))\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_backdoor_attack_dgm_red.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport numpy as np\nimport pytest\nfrom tensorflow.keras.activations import linear\nfrom tests.utils import ARTTestException, master_seed\n\nfrom art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_red import BackdoorAttackDGMReDTensorFlowV2\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\n\nmaster_seed(1234, set_tensorflow=True)\n\n\n@pytest.fixture\ndef x_target():\n return np.random.random_sample((28, 28, 1))\n\n\n@pytest.mark.skip_framework(\"keras\", \"pytorch\", \"scikitlearn\", \"kerastf\")\ndef test_poison_estimator_red(art_warning, image_dl_generator, x_target):\n try:\n generator = image_dl_generator()\n generator.model.layers[-1].activation = linear\n\n red_attack = BackdoorAttackDGMReDTensorFlowV2(generator=generator)\n z_trigger = np.random.randn(1, 100)\n\n generator = red_attack.poison_estimator(z_trigger=z_trigger, x_target=x_target, max_iter=2)\n assert isinstance(generator, TensorFlowV2Generator)\n np.testing.assert_approx_equal(round(red_attack.fidelity(z_trigger, x_target).numpy(), 4), 0.33, significant=1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_backdoor_attack_dgm_trail.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport numpy as np\nimport pytest\nfrom tests.utils import ARTTestException, master_seed\n\nfrom art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_trail import BackdoorAttackDGMTrailTensorFlowV2\nfrom art.estimators.generation.tensorflow import TensorFlowV2Generator\n\nmaster_seed(1234, set_tensorflow=True)\n\n\n@pytest.fixture\ndef x_target():\n return np.random.random_sample((28, 28, 1))\n\n\n@pytest.mark.skip_framework(\"keras\", \"pytorch\", \"scikitlearn\", \"kerastf\")\ndef test_poison_estimator_trail(art_warning, get_default_mnist_subset, image_dl_gan, x_target):\n try:\n (train_images, y_train_images), _ = get_default_mnist_subset\n train_images = train_images * (2.0 / 255) - 1.0\n\n gan, _ = image_dl_gan()\n\n trail_attack = BackdoorAttackDGMTrailTensorFlowV2(gan=gan)\n z_trigger = np.random.randn(1, 100)\n\n generator = trail_attack.poison_estimator(\n z_trigger=z_trigger, x_target=x_target, images=train_images, max_iter=2\n )\n assert isinstance(generator, TensorFlowV2Generator)\n assert trail_attack.fidelity(z_trigger, x_target).numpy() == pytest.approx(0.398, 0.15)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_bullseye_polytope_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import BullseyePolytopeAttackPyTorch\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"tensorflow\", \"keras\", \"kerastf\", \"huggingface\")\ndef test_poison(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n target = np.expand_dims(x_train[3], 0)\n attack = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, net_repeat=2)\n poison_data, poison_labels = attack.poison(x_train[5:10], y_train[5:10])\n\n np.testing.assert_equal(poison_data.shape, x_train[5:10].shape)\n np.testing.assert_equal(poison_labels.shape, y_train[5:10].shape)\n\n with pytest.raises(AssertionError):\n np.testing.assert_equal(poison_data, x_train[5:10])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"tensorflow\", \"keras\", \"kerastf\", \"huggingface\")\ndef test_poison_end2end(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n target = np.expand_dims(x_train[3], 0)\n attack = BullseyePolytopeAttackPyTorch(\n classifier, target, len(classifier.layer_names) - 2, net_repeat=2, endtoend=True\n )\n poison_data, poison_labels = attack.poison(x_train[5:10], y_train[5:10])\n\n np.testing.assert_equal(poison_data.shape, x_train[5:10].shape)\n np.testing.assert_equal(poison_labels.shape, y_train[5:10].shape)\n\n with pytest.raises(AssertionError):\n np.testing.assert_equal(poison_data, x_train[5:10])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"tensorflow\", \"keras\", \"kerastf\")\ndef test_poison_multiple_layers(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n target = np.expand_dims(x_train[3], 0)\n num_layers = len(classifier.layer_names)\n attack = BullseyePolytopeAttackPyTorch(classifier, target, [num_layers - 2, num_layers - 3])\n poison_data, poison_labels = attack.poison(x_train[5:10], y_train[5:10])\n\n np.testing.assert_equal(poison_data.shape, x_train[5:10].shape)\n np.testing.assert_equal(poison_labels.shape, y_train[5:10].shape)\n\n with pytest.raises(AssertionError):\n np.testing.assert_equal(poison_data, x_train[5:10])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"tensorflow\", \"keras\", \"kerastf\")\ndef test_check_params(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n target = np.expand_dims(x_train[3], 0)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, learning_rate=-1)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, max_iter=-1)\n with pytest.raises(TypeError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, 2.5)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, opt=\"new optimizer\")\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, momentum=1.2)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, decay_iter=-1)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, epsilon=-1)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, dropout=2)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, net_repeat=-1)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, -1)\n with pytest.raises(ValueError):\n _ = BullseyePolytopeAttackPyTorch(classifier, target, len(classifier.layer_names) - 2, decay_coeff=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_clean_label_backdoor_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import PoisoningAttackCleanLabelBackdoor, PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_pattern_bd\nfrom art.utils import to_categorical\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\n \"non_dl_frameworks\",\n)\ndef test_poison(art_warning, get_default_mnist_subset, image_dl_estimator, framework):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator()\n target = to_categorical([9], 10)[0]\n print(x_train.shape)\n\n def mod(x):\n return add_pattern_bd(x, channels_first=classifier.channels_first)\n\n backdoor = PoisoningAttackBackdoor(mod)\n attack = PoisoningAttackCleanLabelBackdoor(backdoor, classifier, target)\n poison_data, poison_labels = attack.poison(x_train, y_train)\n\n np.testing.assert_equal(poison_data.shape, x_train.shape)\n np.testing.assert_equal(poison_labels.shape, y_train.shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"params\", [dict(pp_poison=-0.2), dict(pp_poison=1.2)])\n@pytest.mark.skip_framework(\n \"non_dl_frameworks\",\n)\ndef test_failure_modes(art_warning, image_dl_estimator, params):\n try:\n classifier, _ = image_dl_estimator()\n target = to_categorical([9], 10)[0]\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n with pytest.raises(ValueError):\n _ = PoisoningAttackCleanLabelBackdoor(backdoor, classifier, target, **params)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_gradient_matching_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import GradientMatchingAttack\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_poison(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train, y_train), (x_test, y_test) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(from_logits=True)\n\n class_source = 0\n class_target = 1\n epsilon = 0.3\n percent_poison = 0.01\n index_target = np.where(y_test.argmax(axis=1) == class_source)[0][5]\n x_trigger = x_test[index_target : index_target + 1]\n\n x_train, y_train = x_train[:1000], y_train[:1000]\n y_train = np.argmax(y_train, axis=-1)\n attack = GradientMatchingAttack(\n classifier, epsilon=epsilon, percent_poison=percent_poison, max_trials=1, max_epochs=1, verbose=False\n )\n\n x_poison, y_poison = attack.poison(x_trigger, [class_target], x_train, y_train)\n\n np.testing.assert_(\n np.all(np.sum(np.reshape((x_poison - x_train) ** 2, [x_poison.shape[0], -1]), axis=1) < epsilon)\n )\n np.testing.assert_(\n np.sum(np.sum(np.reshape((x_poison - x_train) ** 2, [x_poison.shape[0], -1]), axis=1) > 0)\n <= percent_poison * x_train.shape[0]\n )\n np.testing.assert_equal(np.shape(x_poison), np.shape(x_train))\n np.testing.assert_equal(np.shape(y_poison), np.shape(y_train))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_check_params(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(functional=True)\n\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, learning_rate_schedule=[0.1, 0.2, 0.3])\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=1.2)\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, max_epochs=0)\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, max_trials=0)\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, clip_values=1)\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, epsilon=-1)\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, batch_size=0)\n with pytest.raises(ValueError):\n _ = GradientMatchingAttack(classifier, percent_poison=0.01, verbose=1.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_hidden_trigger_backdoor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning.hidden_trigger_backdoor.hidden_trigger_backdoor import HiddenTriggerBackdoor\nfrom art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_pattern_bd\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.classification.hugging_face import HuggingFaceClassifierPyTorch\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_poison(art_warning, get_default_mnist_subset, image_dl_estimator, framework):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=False)\n\n if isinstance(classifier, (PyTorchClassifier, HuggingFaceClassifierPyTorch)):\n\n def mod(x):\n original_dtype = x.dtype\n x = np.transpose(x, (0, 2, 3, 1)).astype(np.float32)\n x = add_pattern_bd(x)\n x = np.transpose(x, (0, 3, 1, 2)).astype(np.float32)\n return x.astype(original_dtype)\n\n else:\n\n def mod(x):\n original_dtype = x.dtype\n x = add_pattern_bd(x)\n return x.astype(original_dtype)\n\n backdoor = PoisoningAttackBackdoor(mod)\n target = y_train[0]\n diff_index = list(set(np.arange(len(y_train))) - set(np.where(np.all(y_train == target, axis=1))[0]))[0]\n source = y_train[diff_index]\n attack = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n )\n poison_data, poison_inds = attack.poison(x_train, y_train)\n\n with pytest.raises(AssertionError):\n np.testing.assert_equal(poison_data, x_train[poison_inds])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_check_params(art_warning, get_default_mnist_subset, image_dl_estimator, framework):\n try:\n (x_train, y_train), (_, _) = get_default_mnist_subset\n functional = True\n if framework == \"huggingface\":\n functional = False\n classifier, _ = image_dl_estimator(functional=functional)\n\n if isinstance(classifier, PyTorchClassifier):\n\n def mod(x):\n original_dtype = x.dtype\n x = np.transpose(x, (0, 2, 3, 1)).astype(np.float32)\n x = add_pattern_bd(x)\n x = np.transpose(x, (0, 3, 1, 2)).astype(np.float32)\n return x.astype(original_dtype)\n\n else:\n\n def mod(x):\n original_dtype = x.dtype\n x = add_pattern_bd(x)\n return x.astype(original_dtype)\n\n backdoor = PoisoningAttackBackdoor(mod)\n target = y_train[0]\n diff_index = list(set(np.arange(len(y_train))) - set(np.where(np.all(y_train == target, axis=1))[0]))[0]\n source = y_train[diff_index]\n\n # Test non-array target\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=0,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n learning_rate=-1,\n )\n # Test negative LR\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n learning_rate=-1,\n )\n # Test same target/source\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=source,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n )\n # Test Bad Backdoor type\n with pytest.raises(TypeError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=source,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n )\n # Test eps\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=-1,\n target=target,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n )\n # Test bad feature layer\n with pytest.raises(TypeError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=2.5,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n )\n # Test negative feature layer\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=-1,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n )\n # Test negative decay\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=-1,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=0.1,\n )\n # Test invalid poison_percent\n with pytest.raises(ValueError):\n _ = HiddenTriggerBackdoor(\n classifier,\n eps=0.3,\n target=target,\n source=source,\n feature_layer=len(classifier.layer_names) - 2,\n backdoor=backdoor,\n decay_coeff=0.95,\n decay_iter=1,\n max_iter=2,\n batch_size=1,\n poison_percent=1.1,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_image_perturbations.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning.perturbations import add_single_bd, add_pattern_bd, insert_image\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\ndef test_add_single_bd(art_warning):\n try:\n image = add_single_bd(x=np.ones((4, 4, 4, 3)), distance=2, pixel_value=0)\n assert image.shape == (4, 4, 4, 3)\n assert np.min(image) == 0\n\n image = add_single_bd(x=np.ones((3, 3, 3)), distance=2, pixel_value=0)\n assert image.shape == (3, 3, 3)\n assert np.min(image) == 0\n\n image = add_single_bd(x=np.ones((2, 2)), distance=2, pixel_value=0)\n assert image.shape == (2, 2)\n assert np.min(image) == 0\n\n with pytest.raises(ValueError):\n _ = add_single_bd(x=np.ones((5, 5, 5, 5, 5)), distance=2, pixel_value=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_add_pattern_bd(art_warning):\n try:\n image = add_pattern_bd(x=np.ones((4, 4, 4, 3)), distance=2, pixel_value=0)\n assert image.shape == (4, 4, 4, 3)\n assert np.min(image) == 0\n\n image = add_pattern_bd(x=np.ones((3, 3, 3)), distance=2, pixel_value=0)\n assert image.shape == (3, 3, 3)\n assert np.min(image) == 0\n\n image = add_pattern_bd(x=np.ones((2, 2)), distance=2, pixel_value=0)\n assert image.shape == (2, 2)\n assert np.min(image) == 0\n\n with pytest.raises(ValueError):\n _ = add_pattern_bd(x=np.ones((5, 5, 5, 5, 5)), distance=2, pixel_value=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_insert_image(art_warning):\n file_path = os.path.join(os.getcwd(), \"utils/data/backdoors/alert.png\")\n try:\n # test square\n image = insert_image(x=np.zeros((16, 16, 3)), backdoor_path=file_path, size=(8, 8), mode=\"RGB\")\n assert image.shape == (16, 16, 3)\n assert np.min(image) == 0\n\n # test non-square\n image = insert_image(x=np.zeros((20, 12, 3)), backdoor_path=file_path, size=(8, 8), mode=\"RGB\")\n assert image.shape == (20, 12, 3)\n assert np.min(image) == 0\n\n # test fixed location\n image = insert_image(\n x=np.zeros((16, 16, 3)),\n backdoor_path=file_path,\n size=(8, 8),\n random=False,\n x_shift=0,\n y_shift=0,\n mode=\"RGB\",\n )\n assert image.shape == (16, 16, 3)\n assert np.min(image) == 0\n\n # test multiple\n image = insert_image(x=np.zeros((4, 16, 16, 3)), backdoor_path=file_path, size=(8, 8), mode=\"RGB\")\n assert image.shape == (4, 16, 16, 3)\n assert np.min(image) == 0\n\n # test invalid dimensions\n with pytest.raises(ValueError):\n _ = insert_image(x=np.zeros((5, 5, 16, 16, 3)), backdoor_path=file_path, size=(8, 8), mode=\"RGB\")\n\n # test backdoor is larger than image\n with pytest.raises(ValueError):\n _ = insert_image(x=np.zeros((8, 8, 3)), backdoor_path=file_path, size=(10, 10), mode=\"RGB\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/test_sleeper_agent_attack.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport pytest\nfrom PIL import Image\n\nfrom art.attacks.poisoning.sleeper_agent_attack import SleeperAgentAttack\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_poison(art_warning, get_default_mnist_subset, image_dl_estimator, framework):\n try:\n (x_train, y_train), (x_test, y_test) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n patch_size = 4\n img = Image.open(\"notebooks/trigger_10.png\").convert(\"L\")\n img = np.asarray(img.resize((patch_size, patch_size)))\n if classifier.channels_first:\n patch = np.asarray(img).reshape(1, patch_size, patch_size)\n else:\n patch = np.asarray(img).reshape(patch_size, patch_size, 1)\n\n x_train, y_train = x_train[:1000], y_train[:1000]\n class_source = 0\n class_target = 1\n K = 1\n x_train_ = np.copy(x_train)\n index_source = np.where(y_train == class_source)[0][0:K]\n index_target = np.where(y_train == class_target)[0]\n x_trigger = x_train_[index_source]\n epsilon = 16 * 255\n percent_poison = 0.01\n\n attack = SleeperAgentAttack(\n classifier,\n percent_poison=percent_poison,\n max_trials=1,\n max_epochs=10,\n clip_values=(0, 1),\n epsilon=epsilon,\n batch_size=500,\n verbose=1,\n indices_target=index_target,\n patching_strategy=\"random\",\n selection_strategy=\"random\",\n patch=patch,\n retraining_factor=4,\n model_retrain=False,\n model_retraining_epoch=40,\n class_source=class_source,\n class_target=class_target,\n )\n x_poison, y_poison = attack.poison(x_trigger, [class_target], x_train, y_train, x_test, y_test)\n np.testing.assert_(\n np.all(np.sum(np.reshape((x_poison - x_train) ** 2, [x_poison.shape[0], -1]), axis=1) < epsilon)\n )\n np.testing.assert_(\n np.sum(np.sum(np.reshape((x_poison - x_train) ** 2, [x_poison.shape[0], -1]), axis=1) > 0)\n <= percent_poison * x_train.shape[0]\n )\n np.testing.assert_equal(np.shape(x_poison), np.shape(x_train))\n np.testing.assert_equal(np.shape(y_poison), np.shape(y_train))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(functional=True)\n # Test bad patch\n with pytest.raises(ValueError):\n _ = SleeperAgentAttack(\n classifier,\n percent_poison=0.01,\n learning_rate_schedule=[0.1, 0.2, 0.3],\n indices_target=[0],\n patch=[1],\n )\n\n # Test bad indices\n with pytest.raises(ValueError):\n _ = SleeperAgentAttack(\n classifier,\n percent_poison=0.01,\n learning_rate_schedule=[0.1, 0.2, 0.3],\n indices_target=0,\n patch=np.ones((1, 8, 8)),\n )\n\n # Test bad patching strategy\n with pytest.raises(ValueError):\n _ = SleeperAgentAttack(\n classifier,\n percent_poison=0.01,\n learning_rate_schedule=[0.1, 0.2, 0.3],\n indices_target=[0],\n patch=np.ones((1, 8, 8)),\n patching_strategy=1,\n )\n\n # Test bad selection strategy\n with pytest.raises(ValueError):\n _ = SleeperAgentAttack(\n classifier,\n percent_poison=0.01,\n learning_rate_schedule=[0.1, 0.2, 0.3],\n indices_target=[0],\n patch=np.ones((1, 8, 8)),\n selection_strategy=1,\n )\n # Test same source and class\n with pytest.raises(ValueError):\n _ = SleeperAgentAttack(\n classifier,\n percent_poison=0.01,\n learning_rate_schedule=[0.1, 0.2, 0.3],\n indices_target=[0],\n patch=np.ones((1, 8, 8)),\n selection_strategy=1,\n class_source=0,\n class_target=0,\n )\n\n # Test invalid poison percent\n with pytest.raises(ValueError):\n _ = SleeperAgentAttack(\n classifier,\n percent_poison=1.1,\n learning_rate_schedule=[0.1, 0.2, 0.3],\n indices_target=[0],\n patch=np.ones((1, 8, 8)),\n selection_strategy=1,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/bad_det/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.config import ART_NUMPY_DTYPE\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef image_batch(channels_first):\n \"\"\"\n Image fixtures of shape NHWC and NCHW and a sample object detection label.\n \"\"\"\n channels = 3\n height = 20\n width = 16\n\n if channels_first:\n data_shape = (2, channels, height, width)\n else:\n data_shape = (2, height, width, channels)\n x = (0.5 * np.ones((data_shape))).astype(ART_NUMPY_DTYPE)\n\n y = []\n for _ in range(len(x)):\n y_1, x_1 = np.random.uniform(0, (height / 2, width / 2))\n y_2, x_2 = np.random.uniform((y_1 + 3, x_1 + 3), (height, width))\n target_dict = {\n \"boxes\": np.array([[x_1, y_1, x_2, y_2]]),\n \"labels\": np.array([0]),\n }\n y.append(target_dict)\n\n return x, y\n\n\n@pytest.fixture\ndef tabular_batch():\n \"\"\"\n Create tabular data fixture of shape (batch_size, features).\n \"\"\"\n return np.zeros((2, 4)), []\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/bad_det/test_bad_det_gma.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import BadDetGlobalMisclassificationAttack, PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_single_bd, add_pattern_bd, insert_image\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_single_bd(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetGlobalMisclassificationAttack(\n backdoor=backdoor,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n np.testing.assert_equal(poison_labels[0][\"boxes\"].shape, y[0][\"boxes\"].shape)\n np.testing.assert_equal(poison_labels[0][\"labels\"].shape, y[0][\"labels\"].shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_pattern_bd(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n\n try:\n attack = BadDetGlobalMisclassificationAttack(\n backdoor=backdoor,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n np.testing.assert_equal(poison_labels[0][\"boxes\"].shape, y[0][\"boxes\"].shape)\n np.testing.assert_equal(poison_labels[0][\"labels\"].shape, y[0][\"labels\"].shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_image(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n\n file_path = os.path.join(os.getcwd(), \"utils/data/backdoors/alert.png\")\n\n def perturbation(x):\n return insert_image(x, backdoor_path=file_path, channels_first=False, size=(2, 2), mode=\"RGB\")\n\n backdoor = PoisoningAttackBackdoor(perturbation)\n\n try:\n attack = BadDetGlobalMisclassificationAttack(\n backdoor=backdoor,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n np.testing.assert_equal(poison_labels[0][\"boxes\"].shape, y[0][\"boxes\"].shape)\n np.testing.assert_equal(poison_labels[0][\"labels\"].shape, y[0][\"labels\"].shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n with pytest.raises(ValueError):\n _ = BadDetGlobalMisclassificationAttack(None)\n\n with pytest.raises(ValueError):\n _ = BadDetGlobalMisclassificationAttack(backdoor=backdoor, percent_poison=-0.1)\n\n with pytest.raises(ValueError):\n _ = BadDetGlobalMisclassificationAttack(backdoor=backdoor, percent_poison=0)\n\n with pytest.raises(ValueError):\n _ = BadDetGlobalMisclassificationAttack(backdoor=backdoor, percent_poison=1.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_image_data_error(art_warning, tabular_batch):\n x, y = tabular_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetGlobalMisclassificationAttack(backdoor=backdoor)\n\n exc_msg = \"Unrecognized input dimension. BadDet GMA can only be applied to image data.\"\n with pytest.raises(ValueError, match=exc_msg):\n _, _ = attack.poison(x, y)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/bad_det/test_bad_det_oda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import BadDetObjectDisappearanceAttack, PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_single_bd, add_pattern_bd, insert_image\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_single_bd(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetObjectDisappearanceAttack(\n backdoor=backdoor,\n class_source=0,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n if percent_poison == 1.0:\n assert poison_labels[0][\"boxes\"].shape != y[0][\"boxes\"].shape\n assert poison_labels[0][\"labels\"].shape != y[0][\"labels\"].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_pattern_bd(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n\n try:\n attack = BadDetObjectDisappearanceAttack(\n backdoor=backdoor,\n class_source=0,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n if percent_poison == 1.0:\n assert poison_labels[0][\"boxes\"].shape != y[0][\"boxes\"].shape\n assert poison_labels[0][\"labels\"].shape != y[0][\"labels\"].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_image(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n\n file_path = os.path.join(os.getcwd(), \"utils/data/backdoors/alert.png\")\n\n def perturbation(x):\n return insert_image(x, backdoor_path=file_path, channels_first=False, size=(2, 2), mode=\"RGB\")\n\n backdoor = PoisoningAttackBackdoor(perturbation)\n\n try:\n attack = BadDetObjectDisappearanceAttack(\n backdoor=backdoor,\n class_source=0,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n if percent_poison == 1.0:\n assert poison_labels[0][\"boxes\"].shape != y[0][\"boxes\"].shape\n assert poison_labels[0][\"labels\"].shape != y[0][\"labels\"].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n with pytest.raises(ValueError):\n _ = BadDetObjectDisappearanceAttack(None)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectDisappearanceAttack(backdoor=backdoor, percent_poison=-0.1)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectDisappearanceAttack(backdoor=backdoor, percent_poison=0)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectDisappearanceAttack(backdoor=backdoor, percent_poison=1.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_image_data_error(art_warning, tabular_batch):\n x, y = tabular_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetObjectDisappearanceAttack(backdoor=backdoor)\n\n exc_msg = \"Unrecognized input dimension. BadDet ODA can only be applied to image data.\"\n with pytest.raises(ValueError, match=exc_msg):\n _, _ = attack.poison(x, y)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/bad_det/test_bad_det_oga.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import BadDetObjectGenerationAttack, PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_single_bd, add_pattern_bd, insert_image\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_single_bd(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetObjectGenerationAttack(\n backdoor=backdoor,\n bbox_height=8,\n bbox_width=8,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n if percent_poison == 1.0:\n assert poison_labels[0][\"boxes\"].shape != y[0][\"boxes\"].shape\n assert poison_labels[0][\"labels\"].shape != y[0][\"labels\"].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_pattern_bd(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n\n try:\n attack = BadDetObjectGenerationAttack(\n backdoor=backdoor,\n bbox_height=8,\n bbox_width=8,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n if percent_poison == 1.0:\n assert poison_labels[0][\"boxes\"].shape != y[0][\"boxes\"].shape\n assert poison_labels[0][\"labels\"].shape != y[0][\"labels\"].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_image(art_warning, image_batch, percent_poison, channels_first):\n x, y = image_batch\n\n file_path = os.path.join(os.getcwd(), \"utils/data/backdoors/alert.png\")\n\n def perturbation(x):\n return insert_image(x, backdoor_path=file_path, channels_first=False, size=(2, 2), mode=\"RGB\")\n\n backdoor = PoisoningAttackBackdoor(perturbation)\n\n try:\n attack = BadDetObjectGenerationAttack(\n backdoor=backdoor,\n bbox_height=8,\n bbox_width=8,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n if percent_poison == 1.0:\n assert poison_labels[0][\"boxes\"].shape != y[0][\"boxes\"].shape\n assert poison_labels[0][\"labels\"].shape != y[0][\"labels\"].shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n with pytest.raises(ValueError):\n _ = BadDetObjectGenerationAttack(None, bbox_height=8, bbox_width=-1)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectGenerationAttack(backdoor=backdoor, bbox_height=-1, bbox_width=8)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectGenerationAttack(backdoor=backdoor, bbox_height=8, bbox_width=-1)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectGenerationAttack(backdoor=backdoor, bbox_height=8, bbox_width=8, percent_poison=-0.1)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectGenerationAttack(backdoor=backdoor, bbox_height=8, bbox_width=8, percent_poison=0)\n\n with pytest.raises(ValueError):\n _ = BadDetObjectGenerationAttack(backdoor=backdoor, bbox_height=8, bbox_width=8, percent_poison=1.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_image_data_error(art_warning, tabular_batch):\n x, y = tabular_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetObjectGenerationAttack(backdoor=backdoor, bbox_height=8, bbox_width=8)\n\n exc_msg = \"Unrecognized input dimension. BadDet OGA can only be applied to image data.\"\n with pytest.raises(ValueError, match=exc_msg):\n _, _ = attack.poison(x, y)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/attacks/poison/bad_det/test_bad_det_rma.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom art.attacks.poisoning import BadDetRegionalMisclassificationAttack, PoisoningAttackBackdoor\nfrom art.attacks.poisoning.perturbations import add_single_bd, add_pattern_bd, insert_image\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"class_source\", [None, 0])\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_single_bd(art_warning, image_batch, class_source, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetRegionalMisclassificationAttack(\n backdoor=backdoor,\n class_source=class_source,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n np.testing.assert_equal(poison_labels[0][\"boxes\"].shape, y[0][\"boxes\"].shape)\n np.testing.assert_equal(poison_labels[0][\"labels\"].shape, y[0][\"labels\"].shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"class_source\", [None, 0])\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_pattern_bd(art_warning, image_batch, class_source, percent_poison, channels_first):\n x, y = image_batch\n backdoor = PoisoningAttackBackdoor(add_pattern_bd)\n\n try:\n attack = BadDetRegionalMisclassificationAttack(\n backdoor=backdoor,\n class_source=class_source,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n np.testing.assert_equal(poison_labels[0][\"boxes\"].shape, y[0][\"boxes\"].shape)\n np.testing.assert_equal(poison_labels[0][\"labels\"].shape, y[0][\"labels\"].shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"class_source\", [None, 0])\n@pytest.mark.parametrize(\"percent_poison\", [0.3, 1.0])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_poison_image(art_warning, image_batch, class_source, percent_poison, channels_first):\n x, y = image_batch\n\n file_path = os.path.join(os.getcwd(), \"utils/data/backdoors/alert.png\")\n\n def perturbation(x):\n return insert_image(x, backdoor_path=file_path, channels_first=False, size=(2, 2), mode=\"RGB\")\n\n backdoor = PoisoningAttackBackdoor(perturbation)\n\n try:\n attack = BadDetRegionalMisclassificationAttack(\n backdoor=backdoor,\n class_source=class_source,\n class_target=1,\n percent_poison=percent_poison,\n channels_first=channels_first,\n )\n poison_data, poison_labels = attack.poison(x, y)\n\n np.testing.assert_equal(poison_data.shape, x.shape)\n np.testing.assert_equal(poison_labels[0][\"boxes\"].shape, y[0][\"boxes\"].shape)\n np.testing.assert_equal(poison_labels[0][\"labels\"].shape, y[0][\"labels\"].shape)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n with pytest.raises(ValueError):\n _ = BadDetRegionalMisclassificationAttack(None)\n\n with pytest.raises(ValueError):\n _ = BadDetRegionalMisclassificationAttack(backdoor=backdoor, percent_poison=-0.1)\n\n with pytest.raises(ValueError):\n _ = BadDetRegionalMisclassificationAttack(backdoor=backdoor, percent_poison=0)\n\n with pytest.raises(ValueError):\n _ = BadDetRegionalMisclassificationAttack(backdoor=backdoor, percent_poison=1.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_image_data_error(art_warning, tabular_batch):\n x, y = tabular_batch\n backdoor = PoisoningAttackBackdoor(add_single_bd)\n\n try:\n attack = BadDetRegionalMisclassificationAttack(backdoor=backdoor)\n\n exc_msg = \"Unrecognized input dimension. BadDet RMA can only be applied to image data.\"\n with pytest.raises(ValueError, match=exc_msg):\n _, _ = attack.poison(x, y)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/classifiersFrameworks/test_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport numpy as np\nimport pytest\n\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.optim as optim\nimport sklearn.datasets\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.defences.preprocessor.spatial_smoothing import SpatialSmoothing\nfrom art.defences.preprocessor.spatial_smoothing_pytorch import SpatialSmoothingPyTorch\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n\nfrom tests.attacks.utils import backend_test_defended_images\nfrom tests.utils import ARTTestException\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n# A generic test for various preprocessing_defences, forward pass.\ndef _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier_, _ = image_dl_estimator()\n\n clip_values = (0, 1)\n criterion = nn.CrossEntropyLoss()\n classifier = PyTorchClassifier(\n clip_values=clip_values,\n model=classifier_.model,\n preprocessing_defences=preprocessing_defences,\n loss=criterion,\n input_shape=(1, 28, 28),\n nb_classes=10,\n device_type=device_type,\n )\n\n with torch.no_grad():\n predictions_classifier = classifier.predict(x_test_mnist)\n\n # Apply the same defences by hand\n x_test_defense = x_test_mnist\n for defence in preprocessing_defences:\n x_test_defense, _ = defence(x_test_defense, y_test_mnist)\n\n x_test_defense = torch.tensor(x_test_defense)\n with torch.no_grad():\n predictions_check = classifier_.model(x_test_defense)\n predictions_check = predictions_check.cpu().numpy()\n\n # Check that the prediction results match\n np.testing.assert_array_almost_equal(predictions_classifier, predictions_check, decimal=4)\n\n\n# A generic test for various preprocessing_defences, backward pass.\ndef _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier_, _ = image_dl_estimator()\n\n clip_values = (0, 1)\n criterion = nn.CrossEntropyLoss()\n classifier = PyTorchClassifier(\n clip_values=clip_values,\n model=classifier_.model,\n preprocessing_defences=preprocessing_defences,\n loss=criterion,\n input_shape=(1, 28, 28),\n nb_classes=10,\n device_type=device_type,\n )\n\n # The efficient defence-chaining.\n pseudo_gradients = np.random.randn(*x_test_mnist.shape)\n gradients_in_chain = classifier._apply_preprocessing_gradient(x_test_mnist, pseudo_gradients)\n\n # Apply the same backward pass one by one.\n x = x_test_mnist\n x_intermediates = [x]\n for preprocess in classifier.preprocessing_operations[:-1]:\n x = preprocess(x)[0]\n x_intermediates.append(x)\n\n gradients = pseudo_gradients\n for preprocess, x in zip(classifier.preprocessing_operations[::-1], x_intermediates[::-1]):\n gradients = preprocess.estimate_gradient(x, gradients)\n\n np.testing.assert_array_almost_equal(gradients_in_chain, gradients, decimal=4)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_nodefence(art_warning, get_default_mnist_subset, image_dl_estimator, device_type):\n try:\n preprocessing_defences = []\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_defence_pytorch(art_warning, get_default_mnist_subset, image_dl_estimator, device_type):\n try:\n smooth_3x3 = SpatialSmoothingPyTorch(window_size=3, channels_first=True, device_type=device_type)\n preprocessing_defences = [smooth_3x3]\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_defence_non_pytorch(art_warning, get_default_mnist_subset, image_dl_estimator, device_type):\n try:\n smooth_3x3 = SpatialSmoothing(window_size=3, channels_first=True)\n preprocessing_defences = [smooth_3x3]\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.xfail(reason=\"Preprocessing-defence chaining only supports defences implemented in PyTorch.\")\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_defences_pytorch_and_nonpytorch(art_warning, get_default_mnist_subset, image_dl_estimator, device_type):\n try:\n smooth_3x3_nonpth = SpatialSmoothing(window_size=3, channels_first=True)\n smooth_3x3_pth = SpatialSmoothingPyTorch(window_size=3, channels_first=True, device_type=device_type)\n preprocessing_defences = [smooth_3x3_nonpth, smooth_3x3_pth]\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_defences_chaining(art_warning, get_default_mnist_subset, image_dl_estimator, device_type):\n try:\n smooth_3x3 = SpatialSmoothingPyTorch(window_size=3, channels_first=True, device_type=device_type)\n smooth_5x5 = SpatialSmoothingPyTorch(window_size=5, channels_first=True, device_type=device_type)\n smooth_7x7 = SpatialSmoothingPyTorch(window_size=7, channels_first=True, device_type=device_type)\n preprocessing_defences = [smooth_3x3, smooth_5x5, smooth_7x7]\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_fgsm_defences(art_warning, fix_get_mnist_subset, image_dl_estimator, device_type):\n try:\n clip_values = (0, 1)\n smooth_3x3 = SpatialSmoothingPyTorch(window_size=3, channels_first=True, device_type=device_type)\n smooth_5x5 = SpatialSmoothingPyTorch(window_size=5, channels_first=True, device_type=device_type)\n smooth_7x7 = SpatialSmoothingPyTorch(window_size=7, channels_first=True, device_type=device_type)\n classifier_, _ = image_dl_estimator()\n\n criterion = nn.CrossEntropyLoss()\n classifier = PyTorchClassifier(\n clip_values=clip_values,\n model=classifier_.model,\n preprocessing_defences=[smooth_3x3, smooth_5x5, smooth_7x7],\n loss=criterion,\n input_shape=(1, 28, 28),\n nb_classes=10,\n device_type=device_type,\n )\n assert len(classifier.preprocessing_defences) == 3\n\n attack = FastGradientMethod(classifier, eps=1.0, batch_size=128)\n backend_test_defended_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_binary_pgd(art_warning, get_mnist_dataset):\n \"\"\"\n This test instantiates a binary classification PyTorch model, then attacks it using PGD\n\n \"\"\"\n\n class BasicModel(nn.Module):\n def __init__(self):\n super(BasicModel, self).__init__()\n self.layer_1 = nn.Linear(20, 32)\n self.layer_2 = nn.Linear(32, 1)\n\n def forward(self, x):\n x = F.relu(self.layer_1(x))\n x = torch.sigmoid(self.layer_2(x))\n\n return x\n\n try:\n device = \"cpu\"\n x, y = sklearn.datasets.make_classification(\n n_samples=10000, n_features=20, n_informative=5, n_redundant=2, n_repeated=0, n_classes=2\n )\n train_x, test_x, train_y, test_y = sklearn.model_selection.train_test_split(x, y, test_size=0.2)\n train_x = train_x.astype(np.float32)\n train_y = train_y.astype(np.float32)\n test_x = test_x.astype(np.float32)\n model = BasicModel()\n loss_func = nn.BCELoss()\n model.to(device)\n opt = optim.Adam(model.parameters(), lr=0.001)\n classifier = PyTorchClassifier(\n model=model,\n loss=loss_func,\n optimizer=opt,\n input_shape=(1, 28, 28),\n nb_classes=2,\n )\n classifier.fit(train_x, train_y, batch_size=64, nb_epochs=3)\n test_x_batch = test_x[0:16]\n preds = classifier.predict(test_x_batch)\n attacker = ProjectedGradientDescent(classifier, eps=0.5)\n generated = attacker.generate(test_x_batch)\n adv_predicted = classifier.predict(generated)\n assert (adv_predicted != preds).all()\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\"])\n# Function to evaluate custom loss gradient for sequential models\ndef test_custom_loss_gradient_sequential(get_default_mnist_subset, image_dl_estimator, device_type):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n loss_function = torch.norm\n poison_image = x_test_mnist[0:1]\n target_image = x_test_mnist[1:2]\n\n layer = -2\n layer_name = classifier.layer_names[layer]\n custom_grad = classifier.custom_loss_gradient(loss_function, poison_image, target_image, layer_name)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n target_image = torch.tensor(target_image).to(device)\n poison_image = torch.tensor(poison_image).to(device)\n poison_image.requires_grad = True\n\n new_model = nn.Sequential(*list(classifier.model.children())[: layer + 1])\n f_x = new_model(poison_image)\n f_t = new_model(target_image)\n diff = f_x - f_t\n loss = loss_function(diff, p=2)\n self_grad = torch.autograd.grad(loss, [poison_image])[0]\n\n np.testing.assert_array_almost_equal(custom_grad, self_grad, decimal=4)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\"])\n# Function to evaluate custom loss gradient for modular models\ndef test_custom_loss_gradient_modular(get_default_mnist_subset, image_dl_estimator, device_type):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=False)\n loss_function = torch.norm\n poison_image = x_test_mnist[0:1]\n target_image = x_test_mnist[1:2]\n\n layer = -2\n layer_name = classifier.layer_names[layer]\n custom_grad = classifier.custom_loss_gradient(loss_function, poison_image, target_image, layer_name)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n target_image = torch.tensor(target_image).to(device)\n poison_image = torch.tensor(poison_image).to(device)\n poison_image.requires_grad = True\n\n new_model = nn.Sequential(*list(classifier.model.children())[: layer + 1])\n f_x = new_model(poison_image)\n f_t = new_model(target_image)\n diff = f_x - f_t\n loss = loss_function(diff, p=2)\n self_grad = torch.autograd.grad(loss, [poison_image])[0]\n\n np.testing.assert_array_almost_equal(custom_grad, self_grad, decimal=4)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\"])\n# Function to evaluate get activation for sequential models\ndef test_get_activation_sequential(get_default_mnist_subset, image_dl_estimator, device_type):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=True)\n batch_size = x_test_mnist.shape[0]\n N = len(classifier.layer_names)\n for i, name in enumerate(classifier.layer_names):\n if i == N - 1:\n activation_i = classifier.get_activations(x_test_mnist, i, batch_size=batch_size)\n features_i = classifier.model(torch.from_numpy(x_test_mnist))\n features_i = features_i.detach().cpu().numpy()\n\n else:\n activation_i = classifier.get_activations(x_test_mnist, i, batch_size=batch_size)\n features_i = (\n nn.Sequential(*list(classifier.model.children())[: i + 1])(torch.from_numpy(x_test_mnist))\n .detach()\n .cpu()\n .numpy()\n )\n np.testing.assert_array_almost_equal(activation_i, features_i, decimal=4)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\"])\n# Function to evaluate get activation for modular models\ndef test_get_activation_modular(get_default_mnist_subset, image_dl_estimator, device_type):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(functional=False)\n batch_size = x_test_mnist.shape[0]\n m = nn.Softmax(dim=1)\n N = len(classifier.layer_names)\n for i, name in enumerate(classifier.layer_names):\n if i == N - 1:\n activation_i = classifier.get_activations(x_test_mnist, i, batch_size=batch_size)\n activation_i = m(torch.from_numpy(activation_i))\n features_i = classifier.model(torch.from_numpy(x_test_mnist))\n features_i = features_i.detach().cpu().numpy()\n\n else:\n activation_i = classifier.get_activations(x_test_mnist, i, batch_size=batch_size)\n features_i = (\n nn.Sequential(*list(classifier.model.children())[: i + 1])(torch.from_numpy(x_test_mnist))\n .detach()\n .cpu()\n .numpy()\n )\n np.testing.assert_array_almost_equal(activation_i, features_i, decimal=4)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/classifiersFrameworks/test_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport numpy as np\nimport pytest\n\nimport tensorflow as tf\n\nimport sklearn\nimport sklearn.datasets\nimport sklearn.model_selection\n\nfrom art.estimators.classification.tensorflow import TensorFlowV2Classifier\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.defences.preprocessor.spatial_smoothing import SpatialSmoothing\nfrom art.defences.preprocessor.spatial_smoothing_tensorflow import SpatialSmoothingTensorFlowV2\nfrom art.attacks.evasion import FastGradientMethod, ProjectedGradientDescent\n\nfrom tests.attacks.utils import backend_test_defended_images\nfrom tests.utils import ARTTestException\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 11\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n# A generic test for various preprocessing_defences, forward pass.\ndef _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier_, _ = image_dl_estimator()\n\n clip_values = (0, 1)\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n classifier = TensorFlowV2Classifier(\n clip_values=clip_values,\n model=classifier_.model,\n preprocessing_defences=preprocessing_defences,\n loss_object=loss_object,\n input_shape=(28, 28, 1),\n nb_classes=10,\n )\n\n predictions_classifier = classifier.predict(x_test_mnist)\n\n # Apply the same defences by hand\n x_test_defense = x_test_mnist\n for defence in preprocessing_defences:\n x_test_defense, _ = defence(x_test_defense, y_test_mnist)\n\n x_test_defense = tf.convert_to_tensor(x_test_defense)\n predictions_check = classifier_.model(x_test_defense)\n predictions_check = predictions_check.cpu().numpy()\n\n # Check that the prediction results match\n np.testing.assert_array_almost_equal(predictions_classifier, predictions_check, decimal=4)\n\n\n# A generic test for various preprocessing_defences, backward pass.\ndef _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n):\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier_, _ = image_dl_estimator()\n\n clip_values = (0, 1)\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n classifier = TensorFlowV2Classifier(\n clip_values=clip_values,\n model=classifier_.model,\n preprocessing_defences=preprocessing_defences,\n loss_object=loss_object,\n input_shape=(28, 28, 1),\n nb_classes=10,\n )\n\n # The efficient defence-chaining.\n pseudo_gradients = np.random.randn(*x_test_mnist.shape)\n gradients_in_chain = classifier._apply_preprocessing_gradient(x_test_mnist, pseudo_gradients)\n\n # Apply the same backward pass one by one.\n x = x_test_mnist\n x_intermediates = [x]\n for preprocess in classifier.preprocessing_operations[:-1]:\n x = preprocess(x)[0]\n x_intermediates.append(x)\n\n gradients = pseudo_gradients\n for preprocess, x in zip(classifier.preprocessing_operations[::-1], x_intermediates[::-1]):\n gradients = preprocess.estimate_gradient(x, gradients)\n\n np.testing.assert_array_almost_equal(gradients_in_chain, gradients, decimal=4)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_nodefence(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n preprocessing_defences = []\n device_type = None\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_defence_tensorflow(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n smooth_3x3 = SpatialSmoothingTensorFlowV2(window_size=3, channels_first=False)\n preprocessing_defences = [smooth_3x3]\n device_type = None\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_defence_non_tensorflow(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n smooth_3x3 = SpatialSmoothing(window_size=3, channels_first=False)\n preprocessing_defences = [smooth_3x3]\n device_type = None\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.xfail(reason=\"Preprocessing-defence chaining only supports defences implemented in TensorFlow v2.\")\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_defences_tensorflow_and_nontensorflow(art_warning, get_default_mnist_subset, image_dl_estimator, device_type):\n try:\n smooth_3x3_nonpth = SpatialSmoothing(window_size=3, channels_first=False)\n smooth_3x3_pth = SpatialSmoothingTensorFlowV2(window_size=3, channels_first=False)\n preprocessing_defences = [smooth_3x3_nonpth, smooth_3x3_pth]\n device_type = None\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_defences_chaining(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n smooth_3x3 = SpatialSmoothingTensorFlowV2(window_size=3, channels_first=False)\n smooth_5x5 = SpatialSmoothingTensorFlowV2(window_size=5, channels_first=False)\n smooth_7x7 = SpatialSmoothingTensorFlowV2(window_size=7, channels_first=False)\n preprocessing_defences = [smooth_3x3, smooth_5x5, smooth_7x7]\n device_type = None\n _test_preprocessing_defences_forward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n _test_preprocessing_defences_backward(\n get_default_mnist_subset, image_dl_estimator, device_type, preprocessing_defences\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_fgsm_defences(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n clip_values = (0, 1)\n smooth_3x3 = SpatialSmoothingTensorFlowV2(window_size=3, channels_first=False)\n smooth_5x5 = SpatialSmoothingTensorFlowV2(window_size=5, channels_first=False)\n smooth_7x7 = SpatialSmoothingTensorFlowV2(window_size=7, channels_first=False)\n classifier_, _ = image_dl_estimator()\n\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n classifier = TensorFlowV2Classifier(\n clip_values=clip_values,\n model=classifier_.model,\n preprocessing_defences=[smooth_3x3, smooth_5x5, smooth_7x7],\n loss_object=loss_object,\n input_shape=(28, 28, 1),\n nb_classes=10,\n )\n assert len(classifier.preprocessing_defences) == 3\n\n attack = FastGradientMethod(classifier, eps=1.0, batch_size=128)\n backend_test_defended_images(attack, fix_get_mnist_subset)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_binary_keras_instantiation_and_attack_pgd(art_warning):\n try:\n x, y = sklearn.datasets.make_classification(\n n_samples=10000, n_features=20, n_informative=5, n_redundant=2, n_repeated=0, n_classes=2\n )\n train_x, test_x, train_y, test_y = sklearn.model_selection.train_test_split(x, y, test_size=0.2)\n train_x = train_x.astype(np.float32)\n test_x = test_x.astype(np.float32)\n model = tf.keras.models.Sequential(\n [\n tf.keras.layers.Dense(128, activation=tf.nn.relu, input_shape=(20,)),\n tf.keras.layers.Dense(1, activation=tf.nn.sigmoid),\n ]\n )\n model.summary()\n model.compile(optimizer=tf.optimizers.Adam(), loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n classifier = KerasClassifier(model=model)\n classifier.fit(train_x, train_y, nb_epochs=5)\n pred = classifier.predict(test_x)\n attack = ProjectedGradientDescent(estimator=classifier, eps=0.5)\n x_test_adv = attack.generate(x=test_x)\n adv_predictions = classifier.predict(x_test_adv)\n assert (adv_predictions != pred).any()\n except ARTTestException as e:\n art_warning(e)\n\n\n# @pytest.mark.only_with_platform(\"tensorflow2\")\n# def test_binary_tf2_instantiation_and_attack_PGD(art_warning):\n# try:\n# x, y = sklearn.datasets.make_classification(\n# n_samples=10000, n_features=20, n_informative=5, n_redundant=2, n_repeated=0, n_classes=2\n# )\n# train_x, test_x, train_y, test_y = sklearn.model_selection.train_test_split(x, y, test_size=0.2)\n# train_x = train_x.astype(np.float32)\n# test_x = test_x.astype(np.float32)\n# model = tf.keras.models.Sequential(\n# [\n# tf.keras.layers.Dense(128, activation=tf.nn.relu, input_shape=(20,)),\n# tf.keras.layers.Dense(1, activation=tf.nn.sigmoid),\n# ]\n# )\n# model.summary()\n# model.compile(optimizer=tf.optimizers.legacy.Adam(), loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n# classifier = art.estimators.classification.TensorFlowV2Classifier(model=model)\n# classifier.fit(train_x, train_y, nb_epochs=5)\n# pred = classifier.predict(test_x)\n# attack = ProjectedGradientDescent(estimator=classifier, eps=0.5)\n# x_test_adv = attack.generate(x=test_x)\n# adv_predictions = classifier.predict(x_test_adv)\n# assert (adv_predictions != pred).any()\n# except ARTTestException as e:\n# art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_adversarial_trainer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.attacks.evasion.deepfool import DeepFool\nfrom art.data_generators import DataGenerator\nfrom art.defences.trainer.adversarial_trainer import AdversarialTrainer\nfrom art.utils import load_mnist\n\nfrom tests.utils import master_seed, get_image_classifier_tf\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 100\nNB_TEST = 100\n\n\nclass TestAdversarialTrainer(unittest.TestCase):\n \"\"\"\n Test cases for the AdversarialTrainer class.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # MNIST\n (x_train, y_train), (x_test, y_test), _, _ = load_mnist()\n x_train, y_train, x_test, y_test = (\n x_train[:NB_TRAIN],\n y_train[:NB_TRAIN],\n x_test[:NB_TEST],\n y_test[:NB_TEST],\n )\n cls.mnist = ((x_train, y_train), (x_test, y_test))\n\n cls.classifier, _ = get_image_classifier_tf()\n cls.classifier_2, _ = get_image_classifier_tf()\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_classifier_match(self):\n attack = FastGradientMethod(self.classifier)\n adv_trainer = AdversarialTrainer(self.classifier, attack)\n\n self.assertEqual(len(adv_trainer.attacks), 1)\n self.assertEqual(adv_trainer.attacks[0].estimator, adv_trainer.get_classifier())\n\n def test_exceptions(self):\n with self.assertRaises(ValueError):\n _ = AdversarialTrainer(self.classifier, \"attack\")\n\n with self.assertRaises(ValueError):\n attack = FastGradientMethod(self.classifier)\n _ = AdversarialTrainer(self.classifier, attack, ratio=1.5)\n\n def test_fit_predict(self):\n (x_train, y_train), (x_test, y_test) = self.mnist\n x_test_original = x_test.copy()\n\n attack = FastGradientMethod(self.classifier)\n x_test_adv = attack.generate(x_test)\n predictions = np.argmax(self.classifier.predict(x_test_adv), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test, axis=1)) / NB_TEST\n\n adv_trainer = AdversarialTrainer(self.classifier, attack)\n adv_trainer.fit(x_train, y_train, nb_epochs=5, batch_size=128)\n\n predictions_new = np.argmax(adv_trainer.predict(x_test_adv), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test, axis=1)) / NB_TEST\n\n self.assertEqual(accuracy_new, 0.12)\n self.assertEqual(accuracy, 0.13)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_fit_predict_different_classifiers(self):\n (x_train, y_train), (x_test, y_test) = self.mnist\n x_test_original = x_test.copy()\n\n attack = FastGradientMethod(self.classifier)\n x_test_adv = attack.generate(x_test)\n predictions = np.argmax(self.classifier.predict(x_test_adv), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test, axis=1)) / NB_TEST\n\n adv_trainer = AdversarialTrainer(self.classifier_2, attack)\n adv_trainer.fit(x_train, y_train, nb_epochs=5, batch_size=128)\n\n predictions_new = np.argmax(adv_trainer.predict(x_test_adv), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test, axis=1)) / NB_TEST\n\n self.assertEqual(accuracy_new, 0.32)\n self.assertEqual(accuracy, 0.13)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n # fit_generator\n class MyDataGenerator(DataGenerator):\n def __init__(self, x, y, size, batch_size):\n super().__init__(size=size, batch_size=batch_size)\n self.x = x\n self.y = y\n self._size = size\n self._batch_size = batch_size\n\n def get_batch(self):\n ids = np.random.choice(self.size, size=min(self.size, self.batch_size), replace=False)\n return self.x[ids], self.y[ids]\n\n generator = MyDataGenerator(x_train, y_train, size=x_train.shape[0], batch_size=16)\n adv_trainer.fit_generator(generator, nb_epochs=5)\n adv_trainer_2 = AdversarialTrainer(self.classifier_2, attack, ratio=1.0)\n adv_trainer_2.fit_generator(generator, nb_epochs=5)\n\n def test_two_attacks(self):\n (x_train, y_train), (x_test, y_test) = self.mnist\n x_test_original = x_test.copy()\n\n attack1 = FastGradientMethod(estimator=self.classifier, batch_size=16)\n attack2 = DeepFool(classifier=self.classifier, max_iter=5, batch_size=16)\n x_test_adv = attack1.generate(x_test)\n predictions = np.argmax(self.classifier.predict(x_test_adv), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test, axis=1)) / NB_TEST\n\n adv_trainer = AdversarialTrainer(self.classifier, attacks=[attack1, attack2])\n adv_trainer.fit(x_train, y_train, nb_epochs=2, batch_size=16)\n\n predictions_new = np.argmax(adv_trainer.predict(x_test_adv), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test, axis=1)) / NB_TEST\n\n self.assertEqual(accuracy_new, 0.14)\n self.assertEqual(accuracy, 0.13)\n\n # Check that x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_two_attacks_with_generator(self):\n (x_train, y_train), (x_test, y_test) = self.mnist\n x_train_original = x_train.copy()\n x_test_original = x_test.copy()\n\n class MyDataGenerator(DataGenerator):\n def __init__(self, x, y, size, batch_size):\n super().__init__(size=size, batch_size=batch_size)\n self.x = x\n self.y = y\n self._size = size\n self._batch_size = batch_size\n\n def get_batch(self):\n ids = np.random.choice(self.size, size=min(self.size, self.batch_size), replace=False)\n return self.x[ids], self.y[ids]\n\n generator = MyDataGenerator(x_train, y_train, size=x_train.shape[0], batch_size=16)\n\n attack1 = FastGradientMethod(estimator=self.classifier, batch_size=16)\n attack2 = DeepFool(classifier=self.classifier, max_iter=5, batch_size=16)\n x_test_adv = attack1.generate(x_test)\n predictions = np.argmax(self.classifier.predict(x_test_adv), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test, axis=1)) / NB_TEST\n\n adv_trainer = AdversarialTrainer(self.classifier, attacks=[attack1, attack2])\n adv_trainer.fit_generator(generator, nb_epochs=3)\n\n predictions_new = np.argmax(adv_trainer.predict(x_test_adv), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test, axis=1)) / NB_TEST\n\n self.assertAlmostEqual(accuracy_new, 0.38, delta=0.02)\n self.assertAlmostEqual(accuracy, 0.1, delta=0.0)\n\n # Check that x_train and x_test has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_train_original - x_train))), 0.0, delta=0.00001)\n self.assertAlmostEqual(float(np.max(np.abs(x_test_original - x_test))), 0.0, delta=0.00001)\n\n def test_targeted_attack_error(self):\n \"\"\"\n Test the adversarial trainer using a targeted attack, which will currently result in a NotImplementError.\n\n :return: None\n \"\"\"\n (x_train, y_train), (_, _) = self.mnist\n params = {\"nb_epochs\": 2, \"batch_size\": BATCH_SIZE}\n\n adv = FastGradientMethod(self.classifier, targeted=True)\n adv_trainer = AdversarialTrainer(self.classifier, attacks=adv)\n self.assertRaises(NotImplementedError, adv_trainer.fit, x_train, y_train, **params)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_class_labels.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.utils import load_dataset\nfrom art.defences.postprocessor import ClassLabels\n\nfrom tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestClassLabels(unittest.TestCase):\n \"\"\"\n A unittest class for testing the ClassLabels postprocessor.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_class_labels(self):\n \"\"\"\n Test class labels.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ClassLabels()\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]], dtype=np.float32\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_class_labels_binary(self):\n \"\"\"\n Test class labels for binary classifier.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ClassLabels()\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[1.0]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_defensive_distillation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.transformer.evasion import DefensiveDistillation\n\nfrom tests.utils import master_seed, TestBase\nfrom tests.utils import get_image_classifier_tf, get_image_classifier_pt, get_image_classifier_kr\nfrom tests.utils import get_tabular_classifier_tf, get_tabular_classifier_kr, get_tabular_classifier_pt\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_EPOCHS = 30\n\n\ndef cross_entropy(prob1, prob2, eps=1e-10):\n \"\"\"\n Compute cross-entropy between two probability distributions.\n\n :param prob1: First probability distribution.\n :type prob1: `np.ndarray`\n :param prob2: Second probability distribution.\n :type prob2: `np.ndarray`\n :param eps: A small amount to avoid the possibility of having a log of zero.\n :type eps: `float`\n :return: Cross entropy.\n :rtype: `float`\n \"\"\"\n prob1 = np.clip(prob1, eps, 1.0 - eps)\n size = prob1.shape[0]\n result = -np.sum(prob2 * np.log(prob1 + eps)) / size\n\n return result\n\n\nclass TestDefensiveDistillation(TestBase):\n \"\"\"\n A unittest class for testing the DefensiveDistillation transformer on image data.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUpClass()\n\n def setUp(self):\n super().setUp()\n\n def test_1_tensorflow_classifier(self):\n \"\"\"\n First test with the TensorFlowV2Classifier.\n :return:\n \"\"\"\n # Create the trained classifier\n trained_classifier, sess = get_image_classifier_tf()\n\n # Create the modified classifier\n transformed_classifier, _ = get_image_classifier_tf(load_init=False, sess=sess)\n\n # Create defensive distillation transformer\n transformer = DefensiveDistillation(classifier=trained_classifier, batch_size=BATCH_SIZE, nb_epochs=NB_EPOCHS)\n\n # Perform the transformation\n transformed_classifier = transformer(x=self.x_train_mnist, transformed_classifier=transformed_classifier)\n\n # Compare the 2 outputs\n preds1 = trained_classifier.predict(x=self.x_train_mnist, batch_size=BATCH_SIZE)\n\n preds2 = transformed_classifier.predict(x=self.x_train_mnist, batch_size=BATCH_SIZE)\n\n preds1 = np.argmax(preds1, axis=1)\n preds2 = np.argmax(preds2, axis=1)\n acc = np.sum(preds1 == preds2) / len(preds1)\n\n self.assertGreater(acc, 0.5)\n\n ce = cross_entropy(preds1, preds2)\n\n self.assertLess(ce, 10)\n self.assertGreaterEqual(ce, 0)\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_3_pytorch_classifier(self):\n \"\"\"\n Second test with the PyTorchClassifier.\n :return:\n \"\"\"\n self.x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n\n # Create the trained classifier\n trained_classifier = get_image_classifier_pt()\n\n # Create the modified classifier\n transformed_classifier = get_image_classifier_pt(load_init=False)\n\n # Create defensive distillation transformer\n transformer = DefensiveDistillation(classifier=trained_classifier, batch_size=BATCH_SIZE, nb_epochs=NB_EPOCHS)\n\n # Perform the transformation\n transformed_classifier = transformer(x=self.x_train_mnist, transformed_classifier=transformed_classifier)\n\n # Compare the 2 outputs\n preds1 = trained_classifier.predict(x=self.x_train_mnist, batch_size=BATCH_SIZE)\n\n preds2 = transformed_classifier.predict(x=self.x_train_mnist, batch_size=BATCH_SIZE)\n\n preds1 = np.argmax(preds1, axis=1)\n preds2 = np.argmax(preds2, axis=1)\n acc = np.sum(preds1 == preds2) / len(preds1)\n\n self.assertGreater(acc, 0.5)\n\n ce = cross_entropy(preds1, preds2)\n\n self.assertLess(ce, 10)\n self.assertGreaterEqual(ce, 0)\n\n self.x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 28, 28, 1)).astype(np.float32)\n\n def test_5_keras_classifier(self):\n \"\"\"\n Third test with the KerasClassifier.\n :return:\n \"\"\"\n # Create the trained classifier\n trained_classifier = get_image_classifier_kr()\n\n # Create the modified classifier\n transformed_classifier = get_image_classifier_kr(load_init=False)\n\n # Create defensive distillation transformer\n transformer = DefensiveDistillation(classifier=trained_classifier, batch_size=BATCH_SIZE, nb_epochs=NB_EPOCHS)\n\n # Perform the transformation\n transformed_classifier = transformer(x=self.x_train_mnist, transformed_classifier=transformed_classifier)\n\n # Compare the 2 outputs\n preds1 = trained_classifier.predict(x=self.x_train_mnist, batch_size=BATCH_SIZE)\n\n preds2 = transformed_classifier.predict(x=self.x_train_mnist, batch_size=BATCH_SIZE)\n\n preds1 = np.argmax(preds1, axis=1)\n preds2 = np.argmax(preds2, axis=1)\n acc = np.sum(preds1 == preds2) / len(preds1)\n\n self.assertGreater(acc, 0.5)\n\n ce = cross_entropy(preds1, preds2)\n\n self.assertLess(ce, 10)\n self.assertGreaterEqual(ce, 0)\n\n def test_2_tensorflow_iris(self):\n \"\"\"\n First test for TensorFlow.\n :return:\n \"\"\"\n # Create the trained classifier\n trained_classifier, sess = get_tabular_classifier_tf()\n\n # Create the modified classifier\n transformed_classifier, _ = get_tabular_classifier_tf(load_init=False, sess=sess)\n\n # Create defensive distillation transformer\n transformer = DefensiveDistillation(classifier=trained_classifier, batch_size=BATCH_SIZE, nb_epochs=NB_EPOCHS)\n\n # Perform the transformation\n with self.assertRaises(ValueError) as context:\n _ = transformer(x=self.x_train_iris, transformed_classifier=transformed_classifier)\n\n self.assertIn(\"The input trained classifier do not produce probability outputs.\", str(context.exception))\n\n # Clean-up session\n if sess is not None:\n sess.close()\n\n def test_6_keras_iris(self):\n \"\"\"\n Second test for Keras.\n :return:\n \"\"\"\n # Create the trained classifier\n trained_classifier = get_tabular_classifier_kr()\n\n # Create the modified classifier\n transformed_classifier = get_tabular_classifier_kr(load_init=False)\n\n # Create defensive distillation transformer\n transformer = DefensiveDistillation(classifier=trained_classifier, batch_size=BATCH_SIZE, nb_epochs=NB_EPOCHS)\n\n # Perform the transformation\n transformed_classifier = transformer(x=self.x_train_iris, transformed_classifier=transformed_classifier)\n\n # Compare the 2 outputs\n preds1 = trained_classifier.predict(x=self.x_train_iris, batch_size=BATCH_SIZE)\n\n preds2 = transformed_classifier.predict(x=self.x_train_iris, batch_size=BATCH_SIZE)\n\n preds1 = np.argmax(preds1, axis=1)\n preds2 = np.argmax(preds2, axis=1)\n acc = np.sum(preds1 == preds2) / len(preds1)\n\n self.assertGreater(acc, 0.2)\n\n ce = cross_entropy(preds1, preds2)\n\n self.assertLess(ce, 20)\n self.assertGreaterEqual(ce, 0)\n\n def test_4_pytorch_iris(self):\n \"\"\"\n Third test for PyTorch.\n :return:\n \"\"\"\n # Create the trained classifier\n trained_classifier = get_tabular_classifier_pt()\n\n # Create the modified classifier\n transformed_classifier = get_tabular_classifier_pt(load_init=False)\n\n # Create defensive distillation transformer\n transformer = DefensiveDistillation(classifier=trained_classifier, batch_size=BATCH_SIZE, nb_epochs=NB_EPOCHS)\n\n # Perform the transformation\n with self.assertRaises(ValueError) as context:\n _ = transformer(x=self.x_train_iris, transformed_classifier=transformed_classifier)\n\n self.assertIn(\"The input trained classifier do not produce probability outputs.\", str(context.exception))\n\n def test_check_params_pt(self):\n\n ptc = get_image_classifier_pt(from_logits=True)\n\n with self.assertRaises(ValueError):\n _ = DefensiveDistillation(ptc, batch_size=1.0)\n with self.assertRaises(ValueError):\n _ = DefensiveDistillation(ptc, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = DefensiveDistillation(ptc, nb_epochs=1.0)\n with self.assertRaises(ValueError):\n _ = DefensiveDistillation(ptc, nb_epochs=-1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_feature_squeezing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.preprocessor import FeatureSqueezing\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestFeatureSqueezing(unittest.TestCase):\n def setUp(self):\n master_seed(seed=1234)\n\n def test_ones(self):\n m, n = 10, 2\n x = np.ones((m, n))\n\n for depth in range(1, 50):\n preproc = FeatureSqueezing(clip_values=(0, 1), bit_depth=depth)\n x_squeezed, _ = preproc(x)\n self.assertTrue((x_squeezed == 1).all())\n\n def test_random(self):\n m, n = 1000, 20\n x = np.random.rand(m, n)\n x_original = x.copy()\n x_zero = np.where(x < 0.5)\n x_one = np.where(x >= 0.5)\n\n preproc = FeatureSqueezing(clip_values=(0, 1), bit_depth=1)\n x_squeezed, _ = preproc(x)\n self.assertTrue((x_squeezed[x_zero] == 0.0).all())\n self.assertTrue((x_squeezed[x_one] == 1.0).all())\n\n preproc = FeatureSqueezing(clip_values=(0, 1), bit_depth=2)\n x_squeezed, _ = preproc(x)\n self.assertFalse(np.logical_and(0.0 < x_squeezed, x_squeezed < 0.33).any())\n self.assertFalse(np.logical_and(0.34 < x_squeezed, x_squeezed < 0.66).any())\n self.assertFalse(np.logical_and(0.67 < x_squeezed, x_squeezed < 1.0).any())\n # Check that x has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_original - x))), 0.0, delta=0.00001)\n\n def test_data_range(self):\n x = np.arange(5)\n preproc = FeatureSqueezing(clip_values=(0, 4), bit_depth=2)\n x_squeezed, _ = preproc(x)\n self.assertTrue(np.array_equal(x, np.arange(5)))\n self.assertTrue(np.allclose(x_squeezed, [0, 1.33, 2.67, 2.67, 4], atol=1e-1))\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = FeatureSqueezing(clip_values=(0, 4), bit_depth=-1)\n\n with self.assertRaises(ValueError):\n _ = FeatureSqueezing(clip_values=(0, 4, 8))\n\n with self.assertRaises(ValueError):\n _ = FeatureSqueezing(clip_values=(4, 0))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_gaussian_augmentation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.preprocessor import GaussianAugmentation\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestGaussianAugmentation(unittest.TestCase):\n def setUp(self):\n # Set master seed\n master_seed(seed=1234)\n\n def test_small_size(self):\n x = np.arange(15).reshape((5, 3))\n ga = GaussianAugmentation(ratio=0.4, clip_values=(0, 15))\n x_new, _ = ga(x)\n self.assertEqual(x_new.shape, (7, 3))\n\n def test_double_size(self):\n x = np.arange(12).reshape((4, 3))\n x_original = x.copy()\n ga = GaussianAugmentation()\n x_new, _ = ga(x)\n self.assertEqual(x_new.shape[0], 2 * x.shape[0])\n # Check that x has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_original - x))), 0.0, delta=0.00001)\n\n def test_multiple_size(self):\n x = np.arange(12).reshape((4, 3))\n x_original = x.copy()\n ga = GaussianAugmentation(ratio=3.5)\n x_new, _ = ga(x)\n self.assertEqual(int(4.5 * x.shape[0]), x_new.shape[0])\n # Check that x has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_original - x))), 0.0, delta=0.00001)\n\n def test_labels(self):\n x = np.arange(12).reshape((4, 3))\n y = np.arange(8).reshape((4, 2))\n\n ga = GaussianAugmentation()\n x_new, new_y = ga(x, y)\n self.assertTrue(x_new.shape[0] == new_y.shape[0] == 8)\n self.assertEqual(x_new.shape[1:], x.shape[1:])\n self.assertEqual(new_y.shape[1:], y.shape[1:])\n\n def test_no_augmentation(self):\n x = np.arange(12).reshape((4, 3))\n ga = GaussianAugmentation(augmentation=False)\n x_new, _ = ga(x)\n self.assertEqual(x.shape, x_new.shape)\n self.assertFalse((x == x_new).all())\n\n def test_failure_augmentation_fit_predict(self):\n # Assert that value error is raised\n with self.assertRaises(ValueError) as context:\n _ = GaussianAugmentation(augmentation=True, apply_fit=False, apply_predict=True)\n\n self.assertTrue(\n \"If `augmentation` is `True`, then `apply_fit` must be `True` and `apply_predict`\"\n \" must be `False`.\" in str(context.exception)\n )\n with self.assertRaises(ValueError) as context:\n _ = GaussianAugmentation(augmentation=True, apply_fit=False, apply_predict=False)\n\n self.assertIn(\n \"If `augmentation` is `True`, then `apply_fit` and `apply_predict` can't be both `False`.\",\n str(context.exception),\n )\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = GaussianAugmentation(augmentation=True, ratio=-1)\n\n with self.assertRaises(ValueError):\n _ = GaussianAugmentation(clip_values=(0, 1, 2))\n\n with self.assertRaises(ValueError):\n _ = GaussianAugmentation(clip_values=(1, 0))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_gaussian_noise.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.postprocessor import GaussianNoise\nfrom art.utils import load_dataset\n\nfrom tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestGaussianNoise(unittest.TestCase):\n \"\"\"\n A unittest class for testing the GaussianNoise postprocessor.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_gaussian_noise(self):\n \"\"\"\n Test Gaussian noise.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = GaussianNoise(scale=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [[0.15412168, 0.0, 0.2222987, 0.03007976, 0.0381179, 0.12382449, 0.13755375, 0.22279163, 0.07121207, 0.0]],\n dtype=np.float32,\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_gaussian_noise_binary(self):\n \"\"\"\n Test Gaussian noise for binary classifier.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = GaussianNoise(scale=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[0.577278]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = GaussianNoise(scale=-0.1)\n\n def test_set_params(self):\n gan = GaussianNoise(scale=0.1)\n gan.set_params(scale=0.2)\n self.assertEqual(gan.scale, 0.2)\n\n def test_super(self):\n gan = GaussianNoise(scale=0.1)\n self.assertTrue(gan.is_fitted)\n self.assertFalse(gan._apply_fit)\n self.assertTrue(gan._apply_predict)\n gan.fit(preds=np.array([0.1, 0.2, 0.3]))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_high_confidence.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.postprocessor import HighConfidence\nfrom art.utils import load_dataset\n\nfrom tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestHighConfidence(unittest.TestCase):\n \"\"\"\n A unittest class for testing the HighConfidence postprocessor.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_decimals_0_1(self):\n \"\"\"\n Test with cutoff of 0.1.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = HighConfidence(cutoff=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [[0.12109935, 0.0, 0.0, 0.0, 0.11366928, 0.0, 0.0, 0.30685693, 0.0, 0.0]], dtype=np.float32\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_decimals_0_2(self):\n \"\"\"\n Test with cutoff of 0.2.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = HighConfidence(cutoff=0.2)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.30685693, 0.0, 0.0]], dtype=np.float32\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_binary_decimals_0_5(self):\n \"\"\"\n Test with cutoff of 0.5 for binary classifier.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = HighConfidence(cutoff=0.5)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_binary_decimals_0_6(self):\n \"\"\"\n Test with cutoff of 0.6 for binary classifier.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = HighConfidence(cutoff=0.6)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[0.0]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = HighConfidence(cutoff=-0.6)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_label_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.preprocessor import LabelSmoothing\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestLabelSmoothing(unittest.TestCase):\n def setUp(self):\n master_seed(seed=1234)\n\n def test_default(self):\n m, n = 1000, 20\n y = np.zeros((m, n))\n y[(range(m), np.random.choice(range(n), m))] = 1.0\n\n ls = LabelSmoothing()\n _, y_smooth = ls(None, y)\n self.assertTrue(np.isclose(np.sum(y_smooth, axis=1), np.ones(m)).all())\n self.assertTrue((np.max(y_smooth, axis=1) == np.ones(m) * 0.9).all())\n\n def test_customizing(self):\n m, n = 1000, 20\n y = np.zeros((m, n))\n y[(range(m), np.random.choice(range(n), m))] = 1.0\n\n ls = LabelSmoothing(max_value=1.0 / n)\n _, y_smooth = ls(None, y)\n self.assertTrue(np.isclose(np.sum(y_smooth, axis=1), np.ones(m)).all())\n self.assertTrue((np.max(y_smooth, axis=1) == np.ones(m) / n).all())\n self.assertTrue(np.isclose(y_smooth, np.ones((m, n)) / n).all())\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = LabelSmoothing(max_value=-1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_neural_cleanse.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.transformer.poisoning import NeuralCleanse\nfrom art.utils import load_dataset\n\nfrom tests.utils import master_seed\n\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"True\"\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 100\nNB_TRAIN = 5000\nNB_TEST = 1000\n\n\nclass TestNeuralCleanse(unittest.TestCase):\n \"\"\"\n A unittest class for testing Randomized Smoothing as a post-processing step for classifiers.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Get MNIST\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n x_test, y_test = x_test[:NB_TEST], y_test[:NB_TEST]\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_keras(self):\n \"\"\"\n Test with a KerasClassifier.\n :return:\n \"\"\"\n # Build KerasClassifier\n from tensorflow.keras.models import Sequential\n from tensorflow.keras.layers import Dense, Flatten, Conv2D\n from tensorflow.keras.losses import CategoricalCrossentropy\n from tensorflow.keras.optimizers import Adam\n\n model = Sequential()\n model.add(Conv2D(filters=4, kernel_size=(5, 5), strides=1, activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(Flatten())\n model.add(Dense(100, activation=\"relu\"))\n model.add(Dense(100, activation=\"relu\"))\n model.add(Dense(10, activation=\"linear\"))\n\n model.compile(\n loss=CategoricalCrossentropy(from_logits=True), optimizer=Adam(learning_rate=0.01), metrics=[\"accuracy\"]\n )\n\n from art.estimators.classification import KerasClassifier\n\n krc = KerasClassifier(model=model, clip_values=(0, 1))\n\n # Get MNIST\n (x_train, y_train), (x_test, y_test) = self.mnist\n\n for i in range(2500):\n if np.argmax(y_train[[i]], axis=1) == 0:\n y_train[i, :] = 0\n y_train[i, 1] = 1\n x_train[i, 0:5, 0:5, :] = 1.0\n\n if np.argmax(y_train[[i]], axis=1) == 9:\n y_train[i, :] = 0\n y_train[i, 9] = 1\n x_train[i, 0:5, 0:5, :] = 1.0\n\n for i in range(500):\n if np.argmax(y_test[[i]], axis=1) == 0:\n y_test[i, :] = 0\n y_test[i, 1] = 1\n x_test[i, 0:5, 0:5, :] = 1.0\n\n if np.argmax(y_test[[i]], axis=1) == 9:\n y_test[i, :] = 0\n y_test[i, 9] = 1\n x_test[i, 0:5, 0:5, :] = 1.0\n\n krc.fit(x_train, y_train, nb_epochs=5)\n\n cleanse = NeuralCleanse(krc)\n defense_cleanse = cleanse(krc, steps=3, patience=3)\n defense_cleanse.mitigate(x_test, y_test, mitigation_types=[\"filtering\", \"pruning\", \"unlearning\"])\n\n # is_fitted\n assert cleanse._is_fitted == cleanse.is_fitted\n\n # get_classifier\n assert cleanse.get_classifier\n\n # set_params\n cleanse.set_params(**{\"batch_size\": 1})\n assert cleanse.batch_size == 1\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_pixel_defend.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.defences.preprocessor import PixelDefend\nfrom art.utils import load_mnist\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass ModelImage(nn.Module):\n def __init__(self):\n super(ModelImage, self).__init__()\n self.fc = nn.Linear(25, 6400)\n\n def forward(self, x):\n x = x.view(-1, 25)\n logit_output = self.fc(x)\n logit_output = logit_output.view(-1, 5, 5, 1, 256)\n\n return logit_output\n\n\nclass Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.fc = nn.Linear(4, 1024)\n\n def forward(self, x):\n x = x.view(-1, 4)\n logit_output = self.fc(x)\n logit_output = logit_output.view(-1, 4, 256)\n\n return logit_output\n\n\nclass TestPixelDefend(unittest.TestCase):\n def setUp(self):\n # Set master seed\n master_seed(seed=1234)\n\n def test_one_channel(self):\n (x_train, _), (_, _), _, _ = load_mnist()\n x_train = x_train[:2, 10:15, 15:20, :]\n x_train = x_train.astype(np.float32)\n x_train_original = x_train.copy()\n\n # Define the network\n model = ModelImage()\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n self.pixelcnn = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(1, 28, 28), nb_classes=10, clip_values=(0, 1)\n )\n preprocess = PixelDefend(eps=5, pixel_cnn=self.pixelcnn)\n x_defended, _ = preprocess(x_train)\n\n self.assertEqual(x_defended.shape, x_train.shape)\n self.assertTrue((x_defended <= 1.0).all())\n self.assertTrue((x_defended >= 0.0).all())\n\n # Check that x_train has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_train_original - x_train))), 0.0, delta=0.00001)\n\n def test_feature_vectors(self):\n # Define the network\n model = Model()\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n pixel_cnn = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(4,), nb_classes=2, clip_values=(0, 1)\n )\n\n x = np.random.rand(5, 4).astype(np.float32)\n preprocess = PixelDefend(eps=5, pixel_cnn=pixel_cnn)\n x_defended, _ = preprocess(x)\n\n self.assertEqual(x_defended.shape, x.shape)\n self.assertTrue((x_defended <= 1.0).all())\n self.assertTrue((x_defended >= 0.0).all())\n\n def test_check_params(self):\n model = Model()\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n pixel_cnn = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(4,), nb_classes=2, clip_values=(0, 1)\n )\n\n with self.assertRaises(TypeError):\n _ = PixelDefend(pixel_cnn=\"pixel_cnn\")\n\n with self.assertRaises(ValueError):\n _ = PixelDefend(pixel_cnn=pixel_cnn, eps=-1)\n\n with self.assertRaises(ValueError):\n _ = PixelDefend(pixel_cnn=pixel_cnn, clip_values=(1, 0))\n\n with self.assertRaises(ValueError):\n _ = PixelDefend(pixel_cnn=pixel_cnn, clip_values=(-1, 1))\n\n with self.assertRaises(ValueError):\n _ = PixelDefend(pixel_cnn=pixel_cnn, clip_values=(0, 2))\n\n with self.assertRaises(ValueError):\n _ = PixelDefend(pixel_cnn=pixel_cnn, batch_size=-1)\n\n with self.assertRaises(ValueError):\n _ = PixelDefend(pixel_cnn=pixel_cnn, verbose=\"False\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_reverse_sigmoid.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.utils import load_dataset\nfrom art.defences.postprocessor import ReverseSigmoid\n\nfrom tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestReverseSigmoid(unittest.TestCase):\n \"\"\"\n A unittest class for testing the ReverseSigmoid postprocessor.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(1234)\n\n def test_reverse_sigmoid(self):\n \"\"\"\n Test reverse sigmoid.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ReverseSigmoid(beta=1.0, gamma=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [\n [\n 0.10733664,\n 0.07743666,\n 0.09712707,\n 0.08230411,\n 0.10377649,\n 0.0764482,\n 0.08234023,\n 0.20600921,\n 0.08703023,\n 0.08019119,\n ]\n ],\n dtype=np.float32,\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_reverse_sigmoid_beta(self):\n \"\"\"\n Test reverse sigmoid parameter beta.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ReverseSigmoid(beta=0.75, gamma=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [\n [\n 0.1097239,\n 0.07264659,\n 0.09752058,\n 0.07914664,\n 0.10549247,\n 0.07124537,\n 0.07919333,\n 0.22350204,\n 0.08514594,\n 0.07638316,\n ]\n ],\n dtype=np.float32,\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_reverse_sigmoid_gamma(self):\n \"\"\"\n Test reverse sigmoid parameter gamma.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ReverseSigmoid(beta=1.0, gamma=0.5)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray(\n [\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410096,\n 0.11366928,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616714,\n 0.05823757,\n ]\n ],\n dtype=np.float32,\n )\n post_classifier_prediction_expected = np.asarray(\n [\n [\n 0.09699764,\n 0.10062696,\n 0.09689676,\n 0.09873781,\n 0.0968849,\n 0.10121989,\n 0.0987279,\n 0.11275949,\n 0.09774373,\n 0.09940492,\n ]\n ],\n dtype=np.float32,\n )\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_reverse_sigmoid_binary(self):\n \"\"\"\n Test reverse sigmoid for binary classifier.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ReverseSigmoid(beta=1.0, gamma=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[0.52711743]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_reverse_sigmoid_beta_binary(self):\n \"\"\"\n Test reverse sigmoid parameter beta for binary classifier\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ReverseSigmoid(beta=0.75, gamma=0.1)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[0.5278717]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_reverse_sigmoid_gamma_binary(self):\n \"\"\"\n Test reverse sigmoid parameter gamma for binary classifier\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n classifier = get_image_classifier_kr_tf_binary()\n preds = classifier.predict(x_test[0:1])\n postprocessor = ReverseSigmoid(beta=1.0, gamma=0.5)\n post_preds = postprocessor(preds=preds)\n\n classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)\n post_classifier_prediction_expected = np.asarray([[0.51505363]], dtype=np.float32)\n\n np.testing.assert_array_almost_equal(preds, classifier_prediction_expected, decimal=4)\n np.testing.assert_array_almost_equal(post_preds, post_classifier_prediction_expected, decimal=4)\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = ReverseSigmoid(beta=-1.0, gamma=0.5)\n\n with self.assertRaises(ValueError):\n _ = ReverseSigmoid(beta=-1.0, gamma=-0.5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_rounded.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.postprocessor import Rounded\nfrom art.utils import load_dataset\n\nfrom tests.utils import master_seed, get_image_classifier_kr\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestRounded(unittest.TestCase):\n \"\"\"\n A unittest class for testing the Rounded postprocessor.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n cls.mnist = (x_train, y_train), (x_test, y_test)\n cls.classifier = get_image_classifier_kr()\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_decimals_2(self):\n \"\"\"\n Test with 2 decimal places.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n preds = self.classifier.predict(x_test[0:1])\n postprocessor = Rounded(decimals=2)\n post_preds = postprocessor(preds=preds)\n\n expected_predictions = np.asarray(\n [[0.12, 0.05, 0.1, 0.06, 0.11, 0.05, 0.06, 0.31, 0.08, 0.06]], dtype=np.float32\n )\n np.testing.assert_array_equal(post_preds, expected_predictions)\n\n def test_decimals_3(self):\n \"\"\"\n Test with 3 decimal places.\n \"\"\"\n (_, _), (x_test, _) = self.mnist\n preds = self.classifier.predict(x_test[0:1])\n postprocessor = Rounded(decimals=3)\n post_preds = postprocessor(preds=preds)\n\n expected_predictions = np.asarray(\n [[0.121, 0.05, 0.099, 0.064, 0.114, 0.046, 0.064, 0.307, 0.076, 0.058]], dtype=np.float32\n )\n np.testing.assert_array_equal(post_preds, expected_predictions)\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = Rounded(decimals=-3)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_thermometer_encoding.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.preprocessor import ThermometerEncoding\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestThermometerEncoding(unittest.TestCase):\n def setUp(self):\n # Set master seed\n master_seed(seed=1234)\n\n def test_channel_last(self):\n # Test data\n x = np.array(\n [\n [\n [[0.2, 0.6, 0.8], [0.9, 0.4, 0.3], [0.2, 0.8, 0.5]],\n [[0.2, 0.6, 0.8], [0.9, 0.4, 0.3], [0.2, 0.8, 0.5]],\n ],\n [\n [[0.2, 0.6, 0.8], [0.9, 0.4, 0.3], [0.2, 0.8, 0.5]],\n [[0.2, 0.6, 0.8], [0.9, 0.4, 0.3], [0.2, 0.8, 0.5]],\n ],\n ]\n )\n\n # Create an instance of ThermometerEncoding\n th_encoder = ThermometerEncoding(clip_values=(0, 1), num_space=4)\n\n # Preprocess\n x_preproc, _ = th_encoder(x)\n\n # Test\n self.assertEqual(x_preproc.shape, (2, 2, 3, 12))\n\n true_value = np.array(\n [\n [\n [\n [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0],\n [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n ],\n [\n [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0],\n [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n ],\n ],\n [\n [\n [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0],\n [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n ],\n [\n [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0],\n [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0],\n ],\n ],\n ]\n )\n self.assertTrue((x_preproc == true_value).all())\n\n # Create an instance of ThermometerEncoding\n th_encoder_scaled = ThermometerEncoding(clip_values=(-10, 10), num_space=4)\n x_preproc_scaled, _ = th_encoder_scaled(20 * x - 10)\n self.assertTrue((x_preproc_scaled == true_value).all())\n\n def test_channel_first(self):\n x = np.random.rand(5, 2, 28, 28)\n x_copy = x.copy()\n num_space = 5\n encoder = ThermometerEncoding(clip_values=(0, 1), num_space=num_space, channels_first=True)\n x_encoded, _ = encoder(x)\n self.assertTrue((x == x_copy).all())\n self.assertEqual(x_encoded.shape, (5, 10, 28, 28))\n\n def test_estimate_gradient(self):\n num_space = 5\n encoder = ThermometerEncoding(clip_values=(0, 1), num_space=num_space)\n encoder_cf = ThermometerEncoding(clip_values=(0, 1), num_space=num_space, channels_first=True)\n x = np.random.uniform(size=(5, 28, 28, 1))\n x_cf = np.transpose(x, (0, 3, 1, 2))\n grad = np.ones((5, 28, 28, num_space))\n grad_cf = np.transpose(grad, (0, 3, 1, 2))\n estimated_grads = encoder.estimate_gradient(grad=grad, x=x)\n estimated_grads_cf = encoder_cf.estimate_gradient(grad=grad_cf, x=x_cf)\n self.assertEqual(estimated_grads.shape, x.shape)\n self.assertEqual(estimated_grads_cf.shape, x_cf.shape)\n self.assertTrue((estimated_grads == np.transpose(estimated_grads_cf, (0, 2, 3, 1))).all())\n\n def test_feature_vectors(self):\n x = np.random.rand(10, 4)\n x_original = x.copy()\n num_space = 5\n encoder = ThermometerEncoding(clip_values=(0, 1), num_space=num_space, channels_first=True)\n x_encoded, _ = encoder(x)\n self.assertEqual(x_encoded.shape, (10, 20))\n # Check that x has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_original - x))), 0.0, delta=0.00001)\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = ThermometerEncoding(clip_values=(0, 1), num_space=-1)\n\n with self.assertRaises(ValueError):\n _ = ThermometerEncoding(clip_values=(0, 1, 2))\n\n with self.assertRaises(ValueError):\n _ = ThermometerEncoding(clip_values=(1, 0))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/test_variance_minimization.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.preprocessor import TotalVarMin\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestTotalVarMin(unittest.TestCase):\n def setUp(self):\n # Set master seed\n master_seed(seed=1234)\n\n def test_one_channel(self):\n clip_values = (0, 1)\n x = np.random.rand(2, 28, 28, 1)\n preprocess = TotalVarMin(clip_values=(0, 1))\n x_preprocessed, _ = preprocess(x)\n self.assertEqual(x_preprocessed.shape, x.shape)\n self.assertTrue((x_preprocessed >= clip_values[0]).all())\n self.assertTrue((x_preprocessed <= clip_values[1]).all())\n self.assertFalse((x_preprocessed == x).all())\n\n def test_three_channels(self):\n clip_values = (0, 1)\n x = np.random.rand(2, 32, 32, 3)\n x_original = x.copy()\n preprocess = TotalVarMin(clip_values=clip_values)\n x_preprocessed, _ = preprocess(x)\n self.assertEqual(x_preprocessed.shape, x.shape)\n self.assertTrue((x_preprocessed >= clip_values[0]).all())\n self.assertTrue((x_preprocessed <= clip_values[1]).all())\n self.assertFalse((x_preprocessed == x).all())\n # Check that x has not been modified by attack and classifier\n self.assertAlmostEqual(float(np.max(np.abs(x_original - x))), 0.0, delta=0.00001)\n\n def test_failure_feature_vectors(self):\n x = np.random.rand(10, 3)\n preprocess = TotalVarMin()\n\n # Assert that value error is raised for feature vectors\n with self.assertRaises(ValueError) as context:\n preprocess(x)\n\n self.assertIn(\"Feature vectors detected.\", str(context.exception))\n\n def test_check_params(self):\n with self.assertRaises(ValueError):\n _ = TotalVarMin(prob=-1)\n\n with self.assertRaises(ValueError):\n _ = TotalVarMin(norm=-1)\n\n with self.assertRaises(ValueError):\n _ = TotalVarMin(solver=\"solver\")\n\n with self.assertRaises(ValueError):\n _ = TotalVarMin(max_iter=-1)\n\n with self.assertRaises(ValueError):\n _ = TotalVarMin(clip_values=(0, 1, 2))\n\n with self.assertRaises(ValueError):\n _ = TotalVarMin(clip_values=(1, 0))\n\n with self.assertRaises(ValueError):\n _ = TotalVarMin(verbose=\"False\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/evasion/test_beyond_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport numpy as np\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.defences.detector.evasion import BeyondDetectorPyTorch\nfrom art.estimators.classification import PyTorchClassifier\nfrom tests.utils import ARTTestException\n\n\ndef get_ssl_model(weights_path):\n \"\"\"\n Loads the SSL model (SimSiamWithCls).\n \"\"\"\n import torch\n import torch.nn as nn\n\n class SimSiamWithCls(nn.Module):\n \"\"\"\n SimSiam with Classifier\n \"\"\"\n\n def __init__(self, arch=\"resnet18\", feat_dim=2048, num_proj_layers=2):\n from torchvision import models\n\n super(SimSiamWithCls, self).__init__()\n self.backbone = models.resnet18()\n out_dim = self.backbone.fc.weight.shape[1]\n self.backbone.conv1 = nn.Conv2d(\n in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=2, bias=False\n )\n self.backbone.maxpool = nn.Identity()\n self.backbone.fc = nn.Identity()\n self.classifier = nn.Linear(out_dim, out_features=10)\n\n pred_hidden_dim = int(feat_dim / 4)\n\n self.projector = nn.Sequential(\n nn.Linear(out_dim, feat_dim, bias=False),\n nn.BatchNorm1d(feat_dim),\n nn.ReLU(),\n nn.Linear(feat_dim, feat_dim, bias=False),\n nn.BatchNorm1d(feat_dim),\n nn.ReLU(),\n nn.Linear(feat_dim, feat_dim),\n nn.BatchNorm1d(feat_dim, affine=False),\n )\n self.projector[6].bias.requires_grad = False\n\n self.predictor = nn.Sequential(\n nn.Linear(feat_dim, pred_hidden_dim, bias=False),\n nn.BatchNorm1d(pred_hidden_dim),\n nn.ReLU(),\n nn.Linear(pred_hidden_dim, feat_dim),\n )\n\n def forward(self, img, im_aug1=None, im_aug2=None):\n\n r_ori = self.backbone(img)\n if im_aug1 is None and im_aug2 is None:\n cls = self.classifier(r_ori)\n rep = self.projector(r_ori)\n return {\"cls\": cls, \"rep\": rep}\n else:\n\n r1 = self.backbone(im_aug1)\n r2 = self.backbone(im_aug2)\n\n z1 = self.projector(r1)\n z2 = self.projector(r2)\n\n p1 = self.predictor(z1)\n p2 = self.predictor(z2)\n\n return {\"z1\": z1, \"z2\": z2, \"p1\": p1, \"p2\": p2}\n\n model = SimSiamWithCls()\n model.load_state_dict(torch.load(weights_path))\n return model\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_beyond_detector(art_warning, get_default_cifar10_subset):\n try:\n import torch\n from torchvision import models, transforms\n\n # Load CIFAR10 data\n (x_train, y_train), (x_test, _) = get_default_cifar10_subset\n\n x_train = x_train[0:100]\n y_train = y_train[0:100]\n x_test = x_test[0:100]\n\n # Load models\n # Download pretrained weights from\n # https://drive.google.com/drive/folders/1ieEdd7hOj2CIl1FQfu4-3RGZmEj-mesi?usp=sharing\n target_model = models.resnet18()\n # target_model.load_state_dict(torch.load(\"./utils/resources/models/resnet_c10.pth\", map_location=torch.device('cpu')))\n ssl_model = get_ssl_model(weights_path=\"./utils/resources/models/simsiam_c10.pth\")\n\n target_classifier = PyTorchClassifier(\n model=target_model, nb_classes=10, input_shape=(3, 32, 32), loss=torch.nn.CrossEntropyLoss()\n )\n ssl_classifier = PyTorchClassifier(\n model=ssl_model, nb_classes=10, input_shape=(3, 32, 32), loss=torch.nn.CrossEntropyLoss()\n )\n\n # Generate adversarial samples\n attack = FastGradientMethod(estimator=target_classifier, eps=0.05)\n x_test_adv = attack.generate(x_test)\n\n img_augmentations = transforms.Compose(\n [\n transforms.RandomResizedCrop(32, scale=(0.2, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)], p=0.8), # not strengthened\n transforms.RandomGrayscale(p=0.2),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]\n )\n\n # Initialize BeyondDetector\n detector = BeyondDetectorPyTorch(\n target_classifier=target_classifier,\n ssl_classifier=ssl_classifier,\n augmentations=img_augmentations,\n aug_num=50,\n alpha=0.8,\n var_K=20,\n percentile=5,\n )\n\n # Fit the detector\n detector.fit(x_train, y_train, batch_size=128)\n\n # Apply detector on clean and adversarial test data\n _, test_detection = detector.detect(x_test)\n _, test_adv_detection = detector.detect(x_test_adv)\n\n # Assert there is at least one true positive and negative\n nb_true_positives = np.sum(test_adv_detection)\n nb_true_negatives = len(test_detection) - np.sum(test_detection)\n\n assert nb_true_positives > 0\n assert nb_true_negatives > 0\n\n clean_accuracy = 1 - np.mean(test_detection)\n adv_accuracy = np.mean(test_adv_detection)\n\n assert clean_accuracy > 0.0\n assert adv_accuracy > 0.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\nif __name__ == \"__main__\":\n\n test_beyond_detector()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/evasion/test_binary_activation_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.estimators.classification import KerasClassifier, TensorFlowV2Classifier, PyTorchClassifier\nfrom art.defences.detector.evasion import BinaryActivationDetector\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_classifier(framework):\n def _get_classifier():\n if framework in (\"keras\", \"kerastf\"):\n import tensorflow as tf\n from tensorflow.keras import layers, Sequential\n\n model = Sequential()\n model.add(layers.MaxPooling2D(pool_size=(2, 2), input_shape=(22, 22, 1)))\n model.add(layers.Flatten())\n model.add(layers.Dense(2, activation=\"softmax\"))\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\n classifier = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)\n elif framework == \"tensorflow2\":\n import tensorflow as tf\n from tensorflow.keras import layers, Sequential\n\n model = Sequential()\n model.add(layers.MaxPooling2D(pool_size=(2, 2), input_shape=(22, 22, 1)))\n model.add(layers.Flatten())\n model.add(layers.Dense(2, activation=\"softmax\"))\n\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=False)\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n\n classifier = TensorFlowV2Classifier(\n model,\n nb_classes=2,\n input_shape=(22, 22, 1),\n loss_object=loss_object,\n optimizer=optimizer,\n )\n elif framework == \"pytorch\":\n import torch\n\n model = torch.nn.Sequential(torch.nn.MaxPool2d(2, 2), torch.nn.Flatten(), torch.nn.Linear(121, 2))\n criterion = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n classifier = PyTorchClassifier(\n model,\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 22, 22),\n nb_classes=2,\n )\n else:\n classifier = None\n\n return classifier\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"keras\", \"kerastf\", \"tensorflow2\", \"pytorch\")\ndef test_binary_activation_detector(art_warning, get_default_mnist_subset, image_dl_estimator, get_classifier):\n (x_train, _), (x_test, _) = get_default_mnist_subset\n\n # Generate adversarial samples:\n classifier, _ = image_dl_estimator(from_logits=True)\n attacker = FastGradientMethod(classifier, eps=0.1)\n x_train_adv = attacker.generate(x_train)\n x_test_adv = attacker.generate(x_test)\n\n # Compile training data for detector:\n x_train_detector = np.concatenate((x_train, x_train_adv), axis=0)\n y_train_detector = np.concatenate((np.array([[1, 0]] * len(x_train)), np.array([[0, 1]] * len(x_train))), axis=0)\n\n # Create a simple CNN for the detector\n detector_classifier = get_classifier()\n\n try:\n detector = BinaryActivationDetector(classifier=classifier, detector=detector_classifier, layer=0)\n detector.fit(x_train_detector, y_train_detector, nb_epochs=2, batch_size=128)\n\n # Apply detector on clean and adversarial test data:\n _, test_detection = detector.detect(x_test)\n _, test_adv_detection = detector.detect(x_test_adv)\n\n # Assert there is at least one true positive and negative:\n nb_true_positives = np.sum(test_adv_detection)\n nb_true_negatives = len(test_detection) - np.sum(test_detection)\n assert nb_true_positives > 0\n assert nb_true_negatives > 0\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/evasion/test_binary_input_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.attacks.evasion import FastGradientMethod\nfrom art.estimators.classification import KerasClassifier, TensorFlowV2Classifier, PyTorchClassifier\nfrom art.defences.detector.evasion import BinaryInputDetector\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_classifier(framework):\n def _get_classifier():\n if framework in (\"keras\", \"kerastf\"):\n import tensorflow as tf\n from tensorflow.keras import layers, Sequential\n\n model = Sequential()\n model.add(layers.Conv2D(4, kernel_size=(5, 5), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(2, activation=\"softmax\"))\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\n classifier = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)\n elif framework == \"tensorflow2\":\n import tensorflow as tf\n from tensorflow.keras import layers, Sequential\n\n model = Sequential()\n model.add(layers.Conv2D(4, kernel_size=(5, 5), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(2, activation=\"softmax\"))\n\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=False)\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n\n classifier = TensorFlowV2Classifier(\n model,\n nb_classes=2,\n input_shape=(28, 28, 1),\n loss_object=loss_object,\n optimizer=optimizer,\n )\n elif framework == \"pytorch\":\n import torch\n\n model = torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=1, out_channels=4, kernel_size=5),\n torch.nn.MaxPool2d(2, 2),\n torch.nn.Flatten(),\n torch.nn.Linear(576, 2),\n )\n criterion = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n classifier = PyTorchClassifier(\n model,\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=2,\n )\n else:\n classifier = None\n\n return classifier\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"keras\", \"kerastf\", \"tensorflow2\", \"pytorch\")\ndef test_binary_input_detector(art_warning, get_default_mnist_subset, image_dl_estimator, get_classifier):\n (x_train, _), (x_test, _) = get_default_mnist_subset\n\n # Generate adversarial samples:\n classifier, _ = image_dl_estimator(from_logits=True)\n attacker = FastGradientMethod(classifier, eps=0.1)\n x_train_adv = attacker.generate(x_train)\n x_test_adv = attacker.generate(x_test)\n\n # Compile training data for detector:\n x_train_detector = np.concatenate((x_train, x_train_adv), axis=0)\n y_train_detector = np.concatenate((np.array([[1, 0]] * len(x_train)), np.array([[0, 1]] * len(x_train))), axis=0)\n\n # Create a simple CNN for the detector\n detector_classifier = get_classifier()\n\n try:\n detector = BinaryInputDetector(detector_classifier)\n detector.fit(x_train_detector, y_train_detector, nb_epochs=2, batch_size=128)\n\n # Apply detector on clean and adversarial test data:\n _, test_detection = detector.detect(x_test)\n _, test_adv_detection = detector.detect(x_test_adv)\n\n # Assert there is at least one true positive and negative:\n nb_true_positives = np.sum(test_adv_detection)\n nb_true_negatives = len(test_detection) - np.sum(test_detection)\n assert nb_true_positives > 0\n assert nb_true_negatives > 0\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/evasion/test_subsetscanning_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nA unittest class for testing the subset scanning detector.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nimport numpy as np\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.defences.detector.evasion import SubsetScanningDetector\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"keras\", \"kerastf\", \"tensorflow2\", \"pytorch\")\ndef test_subsetscannning_detector_scan_clean(art_warning, get_default_mnist_subset, image_dl_estimator):\n (x_train, _), (x_test, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator()\n\n # Data for detector\n bgd_data = x_train\n clean_data = x_test\n\n try:\n detector = SubsetScanningDetector(classifier, bgd_data=bgd_data, layer=1)\n _, _, dpwr = detector.scan(clean_x=clean_data, adv_x=clean_data)\n assert dpwr > 0\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"keras\", \"kerastf\", \"tensorflow2\", \"pytorch\")\ndef test_subsetscannning_detector_scan_adv(art_warning, get_default_mnist_subset, image_dl_estimator):\n (x_train, _), (x_test, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator()\n\n # Generate adversarial samples\n attacker = FastGradientMethod(classifier, eps=0.5)\n x_test_adv = attacker.generate(x_test)\n\n # Data for detector\n bgd_data = x_train\n clean_data = x_test\n adv_data = x_test_adv\n\n try:\n detector = SubsetScanningDetector(classifier, bgd_data=bgd_data, layer=1)\n _, _, dpwr = detector.scan(clean_x=clean_data, adv_x=adv_data)\n assert dpwr > 0\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"keras\", \"kerastf\", \"tensorflow2\", \"pytorch\")\ndef test_subsetscannning_detector_scan_size(art_warning, get_default_mnist_subset, image_dl_estimator):\n (x_train, _), (x_test, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator()\n\n # Generate adversarial samples\n attacker = FastGradientMethod(classifier, eps=0.5)\n x_test_adv = attacker.generate(x_test)\n\n # Compile training data for detector:\n bgd_data = x_train\n clean_data = x_test\n adv_data = np.concatenate((x_test, x_test_adv), axis=0)\n\n try:\n detector = SubsetScanningDetector(classifier, bgd_data=bgd_data, layer=1)\n _, _, dpwr = detector.scan(clean_x=clean_data, adv_x=adv_data, clean_size=85, adv_size=15)\n assert dpwr > 0\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"keras\", \"kerastf\", \"tensorflow2\", \"pytorch\")\ndef test_subsetscannning_detector_detect(art_warning, get_default_mnist_subset, image_dl_estimator):\n (x_train, _), (x_test, _) = get_default_mnist_subset\n classifier, _ = image_dl_estimator()\n\n # Generate adversarial samples\n attacker = FastGradientMethod(classifier, eps=0.5)\n x_test_adv = attacker.generate(x_test)\n\n # Data for detector\n bgd_data = x_train\n adv_data = x_test_adv\n\n try:\n detector = SubsetScanningDetector(classifier, bgd_data=bgd_data, layer=1)\n _, is_adversarial = detector.detect(adv_data)\n assert len(is_adversarial) == len(adv_data)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/poison/test_activation_defence.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\n\nfrom art.data_generators import KerasDataGenerator\nfrom art.defences.detector.poison import ActivationDefence\nfrom art.utils import load_mnist\nfrom art.visualization import convert_to_rgb\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\nNB_TRAIN, NB_TEST, BATCH_SIZE = 300, 10, 128\n\n\nclass TestActivationDefence(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n\n (x_train, y_train), (x_test, y_test), min_, max_ = load_mnist()\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n cls.mnist = (x_train, y_train), (x_test, y_test), (min_, max_)\n\n # Create simple keras model\n from tensorflow.keras.models import Sequential\n from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\n\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3), activation=\"relu\", input_shape=x_train.shape[1:]))\n model.add(MaxPooling2D(pool_size=(3, 3)))\n model.add(Flatten())\n model.add(Dense(10, activation=\"softmax\"))\n\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\n from art.estimators.classification.keras import KerasClassifier\n\n cls.classifier = KerasClassifier(model=model, clip_values=(min_, max_))\n\n cls.classifier.fit(x_train, y_train, nb_epochs=1, batch_size=128)\n\n cls.defence = ActivationDefence(cls.classifier, x_train, y_train)\n\n datagen = ImageDataGenerator()\n datagen.fit(x_train)\n\n data_gen = KerasDataGenerator(\n datagen.flow(x_train, y_train, batch_size=NB_TRAIN), size=NB_TRAIN, batch_size=NB_TRAIN\n )\n\n cls.defence_gen = ActivationDefence(cls.classifier, None, None, generator=data_gen)\n\n def setUp(self):\n # Set master seed\n master_seed(1234)\n\n @unittest.expectedFailure\n def test_wrong_parameters_1(self):\n self.defence.set_params(nb_clusters=0)\n\n @unittest.expectedFailure\n def test_wrong_parameters_2(self):\n self.defence.set_params(clustering_method=\"what\")\n\n @unittest.expectedFailure\n def test_wrong_parameters_3(self):\n self.defence.set_params(reduce=\"what\")\n\n @unittest.expectedFailure\n def test_wrong_parameters_4(self):\n self.defence.set_params(cluster_analysis=\"what\")\n\n def test_wrong_parameters_5(self):\n with self.assertRaises(ValueError):\n self.defence.set_params(ex_re_threshold=-1)\n\n def test_activations(self):\n (x_train, _), (_, _), (_, _) = self.mnist\n activations = self.defence._get_activations()\n self.assertEqual(len(x_train), len(activations))\n\n def test_output_clusters(self):\n # Get MNIST\n (x_train, _), (_, _), (_, _) = self.mnist\n\n n_classes = self.classifier.nb_classes\n for nb_clusters in range(2, 5):\n clusters_by_class, _ = self.defence.cluster_activations(nb_clusters=nb_clusters)\n\n # Verify expected number of classes\n self.assertEqual(len(clusters_by_class), n_classes)\n # Check we get the expected number of clusters:\n found_clusters = len(np.unique(clusters_by_class[0]))\n self.assertEqual(found_clusters, nb_clusters)\n # Check right amount of data\n n_dp = 0\n for i in range(0, n_classes):\n n_dp += len(clusters_by_class[i])\n self.assertEqual(len(x_train), n_dp)\n\n def test_detect_poison(self):\n # Get MNIST\n (x_train, _), (_, _), (_, _) = self.mnist\n\n _, is_clean_lst = self.defence.detect_poison(nb_clusters=2, nb_dims=10, reduce=\"PCA\", ex_re_threshold=1)\n sum_clean1 = sum(is_clean_lst)\n\n _, is_clean_lst_gen = self.defence_gen.detect_poison(nb_clusters=2, nb_dims=10, reduce=\"PCA\", ex_re_threshold=1)\n sum_clean1_gen = sum(is_clean_lst_gen)\n\n # Check number of items in is_clean\n self.assertEqual(len(x_train), len(is_clean_lst))\n self.assertEqual(len(x_train), len(is_clean_lst_gen))\n\n # Test right number of clusters\n found_clusters = len(np.unique(self.defence.clusters_by_class[0]))\n found_clusters_gen = len(np.unique(self.defence_gen.clusters_by_class[0]))\n self.assertEqual(found_clusters, 2)\n self.assertEqual(found_clusters_gen, 2)\n\n _, is_clean_lst = self.defence.detect_poison(\n nb_clusters=3, nb_dims=10, reduce=\"PCA\", cluster_analysis=\"distance\", ex_re_threshold=1\n )\n _, is_clean_lst_gen = self.defence_gen.detect_poison(\n nb_clusters=3, nb_dims=10, reduce=\"PCA\", cluster_analysis=\"distance\", ex_re_threshold=1\n )\n self.assertEqual(len(x_train), len(is_clean_lst))\n self.assertEqual(len(x_train), len(is_clean_lst_gen))\n\n # Test change of state to new number of clusters:\n found_clusters = len(np.unique(self.defence.clusters_by_class[0]))\n found_clusters_gen = len(np.unique(self.defence_gen.clusters_by_class[0]))\n self.assertEqual(found_clusters, 3)\n self.assertEqual(found_clusters_gen, 3)\n\n # Test clean data has changed\n sum_clean2 = sum(is_clean_lst)\n sum_clean2_gen = sum(is_clean_lst_gen)\n self.assertNotEqual(sum_clean1, sum_clean2)\n self.assertNotEqual(sum_clean1_gen, sum_clean2_gen)\n\n kwargs = {\n \"nb_clusters\": 2,\n \"nb_dims\": 10,\n \"reduce\": \"PCA\",\n \"cluster_analysis\": \"distance\",\n \"ex_re_threshold\": None,\n }\n _, is_clean_lst = self.defence.detect_poison(**kwargs)\n _, is_clean_lst_gen = self.defence_gen.detect_poison(**kwargs)\n sum_dist = sum(is_clean_lst)\n sum_dist_gen = sum(is_clean_lst_gen)\n kwargs = {\n \"nb_clusters\": 2,\n \"nb_dims\": 10,\n \"reduce\": \"PCA\",\n \"cluster_analysis\": \"smaller\",\n \"ex_re_threshold\": None,\n }\n _, is_clean_lst = self.defence.detect_poison(**kwargs)\n _, is_clean_lst_gen = self.defence_gen.detect_poison(**kwargs)\n sum_size = sum(is_clean_lst)\n sum_size_gen = sum(is_clean_lst_gen)\n self.assertNotEqual(sum_dist, sum_size)\n self.assertNotEqual(sum_dist_gen, sum_size_gen)\n\n def test_evaluate_defense(self):\n # Get MNIST\n (x_train, _), (_, _), (_, _) = self.mnist\n\n kwargs = {\"nb_clusters\": 2, \"nb_dims\": 10, \"reduce\": \"PCA\"}\n _, _ = self.defence.detect_poison(**kwargs)\n _, _ = self.defence_gen.detect_poison(**kwargs)\n is_clean = np.zeros(len(x_train))\n self.defence.evaluate_defence(is_clean)\n self.defence_gen.evaluate_defence(is_clean)\n\n def test_analyze_cluster(self):\n # Get MNIST\n (x_train, _), (_, _), (_, _) = self.mnist\n\n self.defence.analyze_clusters(cluster_analysis=\"relative-size\")\n self.defence_gen.analyze_clusters(cluster_analysis=\"relative-size\")\n\n self.defence.analyze_clusters(cluster_analysis=\"silhouette-scores\")\n self.defence_gen.analyze_clusters(cluster_analysis=\"silhouette-scores\")\n\n report, dist_clean_by_class = self.defence.analyze_clusters(cluster_analysis=\"distance\")\n report_gen, dist_clean_by_class_gen = self.defence_gen.analyze_clusters(cluster_analysis=\"distance\")\n n_classes = self.classifier.nb_classes\n self.assertEqual(n_classes, len(dist_clean_by_class))\n self.assertEqual(n_classes, len(dist_clean_by_class_gen))\n\n # Check right amount of data\n n_dp = 0\n n_dp_gen = 0\n for i in range(0, n_classes):\n n_dp += len(dist_clean_by_class[i])\n n_dp_gen += len(dist_clean_by_class_gen[i])\n self.assertEqual(len(x_train), n_dp)\n self.assertEqual(len(x_train), n_dp_gen)\n\n report, sz_clean_by_class = self.defence.analyze_clusters(cluster_analysis=\"smaller\")\n report_gen, sz_clean_by_class_gen = self.defence_gen.analyze_clusters(cluster_analysis=\"smaller\")\n n_classes = self.classifier.nb_classes\n self.assertEqual(n_classes, len(sz_clean_by_class))\n self.assertEqual(n_classes, len(sz_clean_by_class_gen))\n\n # Check right amount of data\n n_dp = 0\n n_dp_gen = 0\n sum_sz = 0\n sum_sz_gen = 0\n sum_dis = 0\n sum_dis_gen = 0\n\n for i in range(0, n_classes):\n n_dp += len(sz_clean_by_class[i])\n n_dp_gen += len(sz_clean_by_class_gen[i])\n sum_sz += sum(sz_clean_by_class[i])\n sum_sz_gen += sum(sz_clean_by_class_gen[i])\n sum_dis += sum(dist_clean_by_class[i])\n sum_dis_gen += sum(dist_clean_by_class_gen[i])\n self.assertEqual(len(x_train), n_dp)\n self.assertEqual(len(x_train), n_dp_gen)\n\n # Very unlikely that they are the same\n self.assertNotEqual(sum_dis, sum_sz, msg=\"This is very unlikely to happen... there may be an error\")\n self.assertNotEqual(sum_dis_gen, sum_sz_gen, msg=\"This is very unlikely to happen... there may be an error\")\n\n def test_plot_clusters(self):\n self.defence.detect_poison(nb_clusters=2, nb_dims=10, reduce=\"PCA\")\n self.defence_gen.detect_poison(nb_clusters=2, nb_dims=10, reduce=\"PCA\")\n self.defence.plot_clusters(save=False)\n self.defence_gen.plot_clusters(save=False)\n\n def test_fix_relabel_poison(self):\n (x_train, y_train), (_, _), (_, _) = self.mnist\n x_poison = x_train[:100]\n y_fix = y_train[:100]\n\n test_set_split = 0.7\n n_train = int(len(x_poison) * test_set_split)\n x_test = x_poison[n_train:]\n y_test = y_fix[n_train:]\n\n predictions = np.argmax(self.classifier.predict(x_test), axis=1)\n ini_miss = 1 - np.sum(predictions == np.argmax(y_test, axis=1)) / y_test.shape[0]\n\n improvement, new_classifier = ActivationDefence.relabel_poison_ground_truth(\n self.classifier,\n x_poison,\n y_fix,\n test_set_split=test_set_split,\n tolerable_backdoor=0.01,\n max_epochs=5,\n batch_epochs=10,\n )\n\n predictions = np.argmax(new_classifier.predict(x_test), axis=1)\n final_miss = 1 - np.sum(predictions == np.argmax(y_test, axis=1)) / y_test.shape[0]\n\n self.assertEqual(improvement, ini_miss - final_miss)\n\n # Other method (since it's cross validation we can't assert to a concrete number).\n improvement, _ = ActivationDefence.relabel_poison_cross_validation(\n self.classifier, x_poison, y_fix, n_splits=2, tolerable_backdoor=0.01, max_epochs=5, batch_epochs=10\n )\n self.assertGreaterEqual(improvement, 0)\n\n def test_visualizations(self):\n # test that visualization doesn't error in grayscale and RGB settings\n (x_train, _), (_, _), (_, _) = self.mnist\n self.defence.visualize_clusters(x_train)\n\n x_train_rgb = convert_to_rgb(x_train)\n self.defence.visualize_clusters(x_train_rgb)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/poison/test_clustering_analyzer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.detector.poison import ClusteringAnalyzer\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestActivationDefence(unittest.TestCase):\n def test_size_analyzer(self):\n nb_clusters = 2\n nb_classes = 3\n clusters_by_class = [[[] for x in range(nb_clusters)] for y in range(nb_classes)]\n\n clusters_by_class[0] = [0, 1, 1, 1, 1] # Class 0\n clusters_by_class[1] = [1, 0, 0, 0, 0] # Class 1\n clusters_by_class[2] = [0, 0, 0, 0, 1] # Class 2\n analyzer = ClusteringAnalyzer()\n assigned_clean_by_class, poison_clusters, report = analyzer.analyze_by_size(clusters_by_class)\n\n # print(\"clusters_by_class\")\n # print(clusters_by_class)\n # print(\"assigned_clean_by_class\")\n # print(assigned_clean_by_class)\n # print(\"poison_clusters\")\n # print(poison_clusters)\n\n clean = 0\n poison = 1\n # For class 0, cluster 0 should be marked as poison.\n self.assertEqual(poison_clusters[0][0], poison)\n # For class 0, cluster 1 should be marked as clean.\n self.assertEqual(poison_clusters[0][1], clean)\n self.assertEqual(report[\"Class_0\"][\"cluster_0\"][\"suspicious_cluster\"], True)\n self.assertEqual(report[\"Class_0\"][\"cluster_1\"][\"suspicious_cluster\"], False)\n total = len(clusters_by_class[0])\n c1 = sum(clusters_by_class[0])\n self.assertEqual(report[\"Class_0\"][\"cluster_0\"][\"ptc_data_in_cluster\"], (total - c1) / total)\n self.assertEqual(report[\"Class_0\"][\"cluster_1\"][\"ptc_data_in_cluster\"], c1 / total)\n\n # Inverse relations for class 1\n self.assertEqual(poison_clusters[1][0], clean)\n self.assertEqual(poison_clusters[1][1], poison)\n self.assertEqual(report[\"Class_1\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_1\"][\"cluster_1\"][\"suspicious_cluster\"], True)\n total = len(clusters_by_class[1])\n c1 = sum(clusters_by_class[1])\n self.assertEqual(report[\"Class_1\"][\"cluster_0\"][\"ptc_data_in_cluster\"], (total - c1) / total)\n self.assertEqual(report[\"Class_1\"][\"cluster_1\"][\"ptc_data_in_cluster\"], c1 / total)\n\n self.assertEqual(poison_clusters[2][0], clean)\n self.assertEqual(poison_clusters[2][1], poison)\n self.assertEqual(report[\"Class_2\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_2\"][\"cluster_1\"][\"suspicious_cluster\"], True)\n total = len(clusters_by_class[2])\n c1 = sum(clusters_by_class[2])\n self.assertEqual(report[\"Class_2\"][\"cluster_0\"][\"ptc_data_in_cluster\"], (total - c1) / total)\n self.assertEqual(report[\"Class_2\"][\"cluster_1\"][\"ptc_data_in_cluster\"], c1 / total)\n\n poison = 0\n self.assertEqual(assigned_clean_by_class[0][0], poison)\n self.assertEqual(assigned_clean_by_class[1][0], poison)\n self.assertEqual(assigned_clean_by_class[2][4], poison)\n\n def test_size_analyzer_three(self):\n nb_clusters = 3\n nb_classes = 3\n clusters_by_class = [[[] for x in range(nb_clusters)] for y in range(nb_classes)]\n\n clusters_by_class[0] = [0, 1, 1, 2, 2] # Class 0\n clusters_by_class[1] = [1, 0, 0, 2, 2] # Class 1\n clusters_by_class[2] = [0, 0, 0, 2, 1, 1] # Class 2\n analyzer = ClusteringAnalyzer()\n assigned_clean_by_class, poison_clusters, report = analyzer.analyze_by_size(clusters_by_class)\n\n # print(\"clusters_by_class\")\n # print(clusters_by_class)\n # print(\"assigned_clean_by_class\")\n # print(assigned_clean_by_class)\n # print(\"poison_clusters\")\n # print(poison_clusters)\n\n clean = 0\n poison = 1\n # For class 0, cluster 0 should be marked as poison.\n self.assertEqual(poison_clusters[0][0], poison)\n # For class 0, cluster 1 and 2 should be marked as clean.\n self.assertEqual(poison_clusters[0][1], clean)\n self.assertEqual(poison_clusters[0][2], clean)\n self.assertEqual(report[\"Class_0\"][\"cluster_0\"][\"suspicious_cluster\"], True)\n self.assertEqual(report[\"Class_0\"][\"cluster_1\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_0\"][\"cluster_2\"][\"suspicious_cluster\"], False)\n total = len(clusters_by_class[0])\n counts = np.bincount(clusters_by_class[0])\n self.assertEqual(report[\"Class_0\"][\"cluster_0\"][\"ptc_data_in_cluster\"], counts[0] / total)\n self.assertEqual(report[\"Class_0\"][\"cluster_1\"][\"ptc_data_in_cluster\"], counts[1] / total)\n self.assertEqual(report[\"Class_0\"][\"cluster_2\"][\"ptc_data_in_cluster\"], counts[2] / total)\n\n self.assertEqual(poison_clusters[1][0], clean)\n self.assertEqual(poison_clusters[1][1], poison)\n self.assertEqual(poison_clusters[1][2], clean)\n self.assertEqual(report[\"Class_1\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_1\"][\"cluster_1\"][\"suspicious_cluster\"], True)\n self.assertEqual(report[\"Class_1\"][\"cluster_2\"][\"suspicious_cluster\"], False)\n total = len(clusters_by_class[1])\n counts = np.bincount(clusters_by_class[1])\n self.assertEqual(report[\"Class_1\"][\"cluster_0\"][\"ptc_data_in_cluster\"], counts[0] / total)\n self.assertEqual(report[\"Class_1\"][\"cluster_1\"][\"ptc_data_in_cluster\"], counts[1] / total)\n self.assertEqual(report[\"Class_1\"][\"cluster_2\"][\"ptc_data_in_cluster\"], counts[2] / total)\n\n self.assertEqual(poison_clusters[2][0], clean)\n self.assertEqual(poison_clusters[2][1], clean)\n self.assertEqual(poison_clusters[2][2], poison)\n self.assertEqual(report[\"Class_2\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_2\"][\"cluster_1\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_2\"][\"cluster_2\"][\"suspicious_cluster\"], True)\n total = len(clusters_by_class[2])\n counts = np.bincount(clusters_by_class[2])\n self.assertEqual(report[\"Class_2\"][\"cluster_0\"][\"ptc_data_in_cluster\"], round(counts[0] / total, 2))\n self.assertEqual(report[\"Class_2\"][\"cluster_1\"][\"ptc_data_in_cluster\"], round(counts[1] / total, 2))\n self.assertEqual(report[\"Class_2\"][\"cluster_2\"][\"ptc_data_in_cluster\"], round(counts[2] / total, 2))\n\n poison = 0\n self.assertEqual(assigned_clean_by_class[0][0], poison)\n self.assertEqual(assigned_clean_by_class[1][0], poison)\n self.assertEqual(assigned_clean_by_class[2][3], poison)\n\n def test_relative_size_analyzer(self):\n nb_clusters = 2\n nb_classes = 4\n clusters_by_class = [[[] for x in range(nb_clusters)] for y in range(nb_classes)]\n\n clusters_by_class[0] = [0, 1, 1, 1, 1] # Class 0\n clusters_by_class[1] = [1, 0, 0, 0, 0] # Class 1\n clusters_by_class[2] = [0, 0, 0, 0, 1] # Class 2\n clusters_by_class[3] = [0, 0, 1, 1, 1] # Class 3\n analyzer = ClusteringAnalyzer()\n assigned_clean_by_class, poison_clusters, report = analyzer.analyze_by_relative_size(clusters_by_class)\n\n # print(\"clusters_by_class\")\n # print(clusters_by_class)\n # print(\"assigned_clean_by_class\")\n # print(assigned_clean_by_class)\n # print(\"poison_clusters\")\n # print(poison_clusters)\n\n clean = 0\n poison = 1\n # For class 0, cluster 0 should be marked as poison.\n self.assertEqual(poison_clusters[0][0], poison)\n # For class 0, cluster 1 should be marked as clean.\n self.assertEqual(poison_clusters[0][1], clean)\n self.assertEqual(report[\"Class_0\"][\"cluster_0\"][\"suspicious_cluster\"], True)\n self.assertEqual(report[\"Class_0\"][\"cluster_1\"][\"suspicious_cluster\"], False)\n total = len(clusters_by_class[0])\n c1 = sum(clusters_by_class[0])\n self.assertEqual(report[\"Class_0\"][\"cluster_0\"][\"ptc_data_in_cluster\"], round((total - c1) / total, 2))\n self.assertEqual(report[\"Class_0\"][\"cluster_1\"][\"ptc_data_in_cluster\"], round(c1 / total, 2))\n\n # Inverse relations for class 1\n self.assertEqual(poison_clusters[1][0], clean)\n self.assertEqual(poison_clusters[1][1], poison)\n self.assertEqual(report[\"Class_1\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_1\"][\"cluster_1\"][\"suspicious_cluster\"], True)\n total = len(clusters_by_class[1])\n c1 = sum(clusters_by_class[1])\n self.assertEqual(report[\"Class_1\"][\"cluster_0\"][\"ptc_data_in_cluster\"], round((total - c1) / total, 2))\n self.assertEqual(report[\"Class_1\"][\"cluster_1\"][\"ptc_data_in_cluster\"], round(c1 / total, 2))\n\n self.assertEqual(poison_clusters[2][0], clean)\n self.assertEqual(poison_clusters[2][1], poison)\n self.assertEqual(report[\"Class_2\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_2\"][\"cluster_1\"][\"suspicious_cluster\"], True)\n total = len(clusters_by_class[2])\n c1 = sum(clusters_by_class[2])\n self.assertEqual(report[\"Class_2\"][\"cluster_0\"][\"ptc_data_in_cluster\"], round((total - c1) / total, 2))\n self.assertEqual(report[\"Class_2\"][\"cluster_1\"][\"ptc_data_in_cluster\"], round(c1 / total, 2))\n\n self.assertEqual(poison_clusters[3][0], clean)\n self.assertEqual(poison_clusters[3][1], clean)\n self.assertEqual(report[\"Class_3\"][\"cluster_0\"][\"suspicious_cluster\"], False)\n self.assertEqual(report[\"Class_3\"][\"cluster_1\"][\"suspicious_cluster\"], False)\n total = len(clusters_by_class[3])\n c1 = sum(clusters_by_class[3])\n self.assertEqual(report[\"Class_3\"][\"cluster_0\"][\"ptc_data_in_cluster\"], round((total - c1) / total, 2))\n self.assertEqual(report[\"Class_3\"][\"cluster_1\"][\"ptc_data_in_cluster\"], round(c1 / total, 2))\n\n poison = 0\n self.assertEqual(assigned_clean_by_class[0][0], poison)\n self.assertEqual(assigned_clean_by_class[1][0], poison)\n self.assertEqual(assigned_clean_by_class[2][4], poison)\n self.assertEqual(sum(assigned_clean_by_class[3]), len(assigned_clean_by_class[3]))\n\n @unittest.expectedFailure\n def test_relative_size_analyzer_three(self):\n nb_clusters = 3\n nb_classes = 3\n clusters_by_class = [[[] for x in range(nb_clusters)] for y in range(nb_classes)]\n\n clusters_by_class[0] = [0, 1, 1, 2, 2] # Class 0\n clusters_by_class[1] = [1, 0, 0, 2, 2] # Class 1\n clusters_by_class[2] = [0, 0, 0, 2, 1, 1] # Class 2\n analyzer = ClusteringAnalyzer()\n analyzer.analyze_clusters(clusters_by_class)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/poison/test_ground_truth_evaluator.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport json\nimport logging\nimport pprint\nimport unittest\n\nfrom art.defences.detector.poison import GroundTruthEvaluator\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestGroundTruth(unittest.TestCase):\n def setUp(self):\n master_seed(seed=1234)\n\n @classmethod\n def setUpClass(cls):\n cls.evaluator = GroundTruthEvaluator()\n cls.n_classes = 3\n cls.n_dp = 10\n cls.n_dp_mix = 5\n\n cls.is_clean_all_clean = [[] for _ in range(cls.n_classes)]\n cls.is_clean_all_poison = [[] for _ in range(cls.n_classes)]\n cls.is_clean_mixed = [[] for _ in range(cls.n_classes)]\n cls.is_clean_comp_mix = [[] for _ in range(cls.n_classes)]\n\n for i in range(cls.n_classes):\n cls.is_clean_all_clean[i] = [1] * cls.n_dp\n cls.is_clean_all_poison[i] = [0] * cls.n_dp\n cls.is_clean_mixed[i] = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]\n cls.is_clean_comp_mix[i] = [0, 1, 1, 0, 1, 0, 0, 0, 1, 1]\n\n def test_analyze_correct_all_clean(self):\n # perfect detection all data is actually clean:\n errors_by_class, conf_matrix_json = self.evaluator.analyze_correctness(\n self.is_clean_all_clean, self.is_clean_all_clean\n )\n\n json_object = json.loads(conf_matrix_json)\n self.assertEqual(len(json_object.keys()), self.n_classes)\n self.assertEqual(len(errors_by_class), self.n_classes)\n\n # print(json_object)\n for i in range(self.n_classes):\n res_class_i = json_object[\"class_\" + str(i)]\n self.assertEqual(res_class_i[\"TruePositive\"][\"rate\"], -1)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"rate\"], 100)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"rate\"], -1)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"rate\"], 0)\n\n self.assertEqual(res_class_i[\"TruePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"TruePositive\"][\"denominator\"], 0)\n\n self.assertEqual(res_class_i[\"TrueNegative\"][\"numerator\"], self.n_dp)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"denominator\"], self.n_dp)\n\n self.assertEqual(res_class_i[\"FalseNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"denominator\"], 0)\n\n self.assertEqual(res_class_i[\"FalsePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"denominator\"], self.n_dp)\n\n # all errors_by_class should be 1 (errors_by_class[i] = 1 if marked clean, is clean)\n for item in errors_by_class[i]:\n self.assertEqual(item, 1)\n\n def test_analyze_correct_all_poison(self):\n # perfect detection all data is actually poison\n errors_by_class, conf_matrix_json = self.evaluator.analyze_correctness(\n self.is_clean_all_poison, self.is_clean_all_poison\n )\n\n json_object = json.loads(conf_matrix_json)\n self.assertEqual(len(json_object.keys()), self.n_classes)\n self.assertEqual(len(errors_by_class), self.n_classes)\n\n # print(json_object)\n for i in range(self.n_classes):\n res_class_i = json_object[\"class_\" + str(i)]\n self.assertEqual(res_class_i[\"TruePositive\"][\"rate\"], 100)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"rate\"], -1)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"rate\"], 0)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"rate\"], -1)\n\n self.assertEqual(res_class_i[\"TruePositive\"][\"numerator\"], self.n_dp)\n self.assertEqual(res_class_i[\"TruePositive\"][\"denominator\"], self.n_dp)\n\n self.assertEqual(res_class_i[\"TrueNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"denominator\"], 0)\n\n self.assertEqual(res_class_i[\"FalseNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"denominator\"], self.n_dp)\n\n self.assertEqual(res_class_i[\"FalsePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"denominator\"], 0)\n\n # all errors_by_class should be 0 (all_errors_by_class[i] = 0 if marked poison, is poison)\n for item in errors_by_class[i]:\n self.assertEqual(item, 0)\n\n def test_analyze_correct_mixed(self):\n # perfect detection mixed\n errors_by_class, conf_matrix_json = self.evaluator.analyze_correctness(self.is_clean_mixed, self.is_clean_mixed)\n\n json_object = json.loads(conf_matrix_json)\n self.assertEqual(len(json_object.keys()), self.n_classes)\n self.assertEqual(len(errors_by_class), self.n_classes)\n\n # print(json_object)\n for i in range(self.n_classes):\n res_class_i = json_object[\"class_\" + str(i)]\n self.assertEqual(res_class_i[\"TruePositive\"][\"rate\"], 100)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"rate\"], 100)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"rate\"], 0)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"rate\"], 0)\n\n self.assertEqual(res_class_i[\"TruePositive\"][\"numerator\"], self.n_dp_mix)\n self.assertEqual(res_class_i[\"TruePositive\"][\"denominator\"], self.n_dp_mix)\n\n self.assertEqual(res_class_i[\"TrueNegative\"][\"numerator\"], self.n_dp_mix)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"denominator\"], self.n_dp_mix)\n\n self.assertEqual(res_class_i[\"FalseNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"denominator\"], self.n_dp_mix)\n\n self.assertEqual(res_class_i[\"FalsePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"denominator\"], self.n_dp_mix)\n\n # all errors_by_class should be 1 (errors_by_class[i] = 1 if marked clean, is clean)\n for j, item in enumerate(errors_by_class[i]):\n self.assertEqual(item, self.is_clean_mixed[i][j])\n\n def test_analyze_fully_misclassified(self):\n # Completely wrong\n # order parameters: analyze_correctness(assigned_clean_by_class, is_clean_by_class)\n errors_by_class, conf_matrix_json = self.evaluator.analyze_correctness(\n self.is_clean_all_clean, self.is_clean_all_poison\n )\n\n json_object = json.loads(conf_matrix_json)\n self.assertEqual(len(json_object.keys()), self.n_classes)\n self.assertEqual(len(errors_by_class), self.n_classes)\n\n print(json_object)\n for i in range(self.n_classes):\n res_class_i = json_object[\"class_\" + str(i)]\n self.assertEqual(res_class_i[\"TruePositive\"][\"rate\"], 0)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"rate\"], -1)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"rate\"], 100)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"rate\"], -1)\n\n self.assertEqual(res_class_i[\"TruePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"TruePositive\"][\"denominator\"], self.n_dp)\n\n self.assertEqual(res_class_i[\"TrueNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"denominator\"], 0)\n\n self.assertEqual(res_class_i[\"FalseNegative\"][\"numerator\"], self.n_dp)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"denominator\"], self.n_dp)\n\n self.assertEqual(res_class_i[\"FalsePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"denominator\"], 0)\n\n # all errors_by_class should be 3 (all_errors_by_class[i] = 3 marked clean, is poison)\n for item in errors_by_class[i]:\n self.assertEqual(item, 3)\n\n def test_analyze_fully_misclassified_rev(self):\n # Completely wrong\n # order parameters: analyze_correctness(assigned_clean_by_class, is_clean_by_class)\n errors_by_class, conf_matrix_json = self.evaluator.analyze_correctness(\n self.is_clean_all_poison, self.is_clean_all_clean\n )\n\n json_object = json.loads(conf_matrix_json)\n self.assertEqual(len(json_object.keys()), self.n_classes)\n self.assertEqual(len(errors_by_class), self.n_classes)\n\n pprint.pprint(json_object)\n for i in range(self.n_classes):\n res_class_i = json_object[\"class_\" + str(i)]\n self.assertEqual(res_class_i[\"TruePositive\"][\"rate\"], -1)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"rate\"], 0)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"rate\"], -1)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"rate\"], 100)\n\n self.assertEqual(res_class_i[\"TruePositive\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"TruePositive\"][\"denominator\"], 0)\n\n self.assertEqual(res_class_i[\"TrueNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"TrueNegative\"][\"denominator\"], self.n_dp)\n\n self.assertEqual(res_class_i[\"FalseNegative\"][\"numerator\"], 0)\n self.assertEqual(res_class_i[\"FalseNegative\"][\"denominator\"], 0)\n\n self.assertEqual(res_class_i[\"FalsePositive\"][\"numerator\"], self.n_dp)\n self.assertEqual(res_class_i[\"FalsePositive\"][\"denominator\"], self.n_dp)\n\n # all errors_by_class should be 3 (all_errors_by_class[i] = 2 if marked poison, is clean)\n for item in errors_by_class[i]:\n self.assertEqual(item, 2)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/poison/test_provenance_defence.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nfrom sklearn.svm import SVC\n\nfrom art.attacks.poisoning.poisoning_attack_svm import PoisoningAttackSVM\nfrom art.estimators.classification.scikitlearn import SklearnClassifier, ScikitlearnSVC\nfrom art.defences.detector.poison.provenance_defense import ProvenanceDefense\nfrom art.utils import load_mnist\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\nNB_TRAIN = 40\nNB_POISON = 5\nNB_VALID = 10\nNB_TRUSTED = 10\nNB_DEVICES = 4\nkernel = \"linear\"\n\n\nclass TestProvenanceDefence(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=301)\n (x_train, y_train), (x_test, y_test), min_, max_ = load_mnist()\n y_train = np.argmax(y_train, axis=1)\n y_test = np.argmax(y_test, axis=1)\n zero_or_four = np.logical_or(y_train == 4, y_train == 0, y_train == 9)\n x_train = x_train[zero_or_four]\n y_train = y_train[zero_or_four]\n tr_labels = np.zeros((y_train.shape[0], 2))\n tr_labels[y_train == 0] = np.array([1, 0])\n tr_labels[y_train == 4] = np.array([0, 1])\n y_train = tr_labels\n\n zero_or_four = np.logical_or(y_test == 4, y_test == 0)\n x_test = x_test[zero_or_four]\n y_test = y_test[zero_or_four]\n te_labels = np.zeros((y_test.shape[0], 2))\n te_labels[y_test == 0] = np.array([1, 0])\n te_labels[y_test == 4] = np.array([0, 1])\n y_test = te_labels\n\n n_samples_train = x_train.shape[0]\n n_features_train = x_train.shape[1] * x_train.shape[2] * x_train.shape[3]\n n_samples_test = x_test.shape[0]\n n_features_test = x_test.shape[1] * x_test.shape[2] * x_test.shape[3]\n\n x_train = x_train.reshape(n_samples_train, n_features_train)\n x_test = x_test.reshape(n_samples_test, n_features_test)\n x_train = x_train[:NB_TRAIN]\n y_train = y_train[:NB_TRAIN]\n\n trusted_data = x_test[:NB_TRUSTED]\n trusted_labels = y_test[:NB_TRUSTED]\n x_test = x_test[NB_TRUSTED:]\n y_test = y_test[NB_TRUSTED:]\n valid_data = x_test[:NB_VALID]\n valid_labels = y_test[:NB_VALID]\n x_test = x_test[NB_VALID:]\n y_test = y_test[NB_VALID:]\n\n clean_prov = np.random.randint(NB_DEVICES - 1, size=x_train.shape[0])\n p_train = np.eye(NB_DEVICES)[clean_prov]\n\n no_defense = ScikitlearnSVC(model=SVC(kernel=kernel, gamma=\"auto\"), clip_values=(min_, max_))\n no_defense.fit(x=x_train, y=y_train)\n poison_points = np.random.randint(no_defense._model.support_vectors_.shape[0], size=NB_POISON)\n all_poison_init = np.copy(no_defense._model.support_vectors_[poison_points])\n poison_labels = np.array([1, 1]) - no_defense.predict(all_poison_init)\n\n svm_attack = PoisoningAttackSVM(\n classifier=no_defense,\n x_train=x_train,\n y_train=y_train,\n step=0.1,\n eps=1.0,\n x_val=valid_data,\n y_val=valid_labels,\n max_iter=100,\n verbose=False,\n )\n\n poisoned_data, _ = svm_attack.poison(all_poison_init, y=poison_labels)\n\n # Stack on poison to data and add provenance of bad actor\n all_data = np.vstack([x_train, poisoned_data])\n all_labels = np.vstack([y_train, poison_labels])\n poison_prov = np.zeros((NB_POISON, NB_DEVICES))\n poison_prov[:, NB_DEVICES - 1] = 1\n all_p = np.vstack([p_train, poison_prov])\n\n model = SVC(kernel=kernel, gamma=\"auto\")\n cls.mnist = (\n (all_data, all_labels, all_p),\n (x_test, y_test),\n (trusted_data, trusted_labels),\n (valid_data, valid_labels),\n (min_, max_),\n )\n cls.classifier = SklearnClassifier(model=model, clip_values=(min_, max_))\n\n cls.classifier.fit(all_data, all_labels)\n cls.defence_trust = ProvenanceDefense(\n cls.classifier,\n all_data,\n all_labels,\n all_p,\n x_val=trusted_data,\n y_val=trusted_labels,\n eps=0.1,\n )\n cls.defence_no_trust = ProvenanceDefense(cls.classifier, all_data, all_labels, all_p, eps=0.1)\n\n def setUp(self):\n master_seed(seed=301)\n\n def test_wrong_parameters_1(self):\n self.assertRaises(ValueError, self.defence_no_trust.set_params, eps=-2.0)\n self.assertRaises(ValueError, self.defence_trust.set_params, eps=-2.0)\n\n def test_wrong_parameters_2(self):\n self.assertRaises(ValueError, self.defence_no_trust.set_params, pp_valid=-0.1)\n self.assertRaises(ValueError, self.defence_trust.set_params, eps=-0.1)\n\n def test_wrong_parameters_3(self):\n (all_data, _, _), (_, y_test), (_, _), (_, _), (_, _) = self.mnist\n self.assertRaises(\n ValueError,\n self.defence_no_trust.set_params,\n x_train=-all_data,\n y_train=y_test,\n )\n self.assertRaises(ValueError, self.defence_trust.set_params, x_train=-all_data, y_train=y_test)\n\n def test_wrong_parameters_4(self):\n (_, _, p_train), (x_test, y_test), (_, _), (_, _), (_, _) = self.mnist\n self.assertRaises(\n ValueError,\n self.defence_no_trust.set_params,\n x_train=-x_test,\n y_train=y_test,\n p_train=p_train,\n )\n self.assertRaises(\n ValueError,\n self.defence_trust.set_params,\n x_train=-x_test,\n y_train=y_test,\n p_train=p_train,\n )\n\n def test_detect_poison(self):\n _, clean_trust = self.defence_trust.detect_poison()\n _, clean_no_trust = self.defence_no_trust.detect_poison()\n real_clean = np.array([1 if i < NB_TRAIN else 0 for i in range(NB_TRAIN + NB_POISON)])\n pc_tp_trust = np.average(real_clean[:NB_TRAIN] == clean_trust[:NB_TRAIN])\n pc_tn_trust = np.average(real_clean[NB_TRAIN:] == clean_trust[NB_TRAIN:])\n self.assertGreaterEqual(pc_tn_trust, 0.7)\n self.assertGreaterEqual(pc_tp_trust, 0.7)\n\n pc_tp_no_trust = np.average(real_clean[:NB_TRAIN] == clean_no_trust[:NB_TRAIN])\n pc_tn_no_trust = np.average(real_clean[NB_TRAIN:] == clean_no_trust[NB_TRAIN:])\n self.assertGreaterEqual(pc_tn_no_trust, 0.7)\n self.assertGreaterEqual(pc_tp_no_trust, 0.7)\n\n def test_evaluate_defense(self):\n real_clean = np.array([1 if i < NB_TRAIN else 0 for i in range(NB_TRAIN + NB_POISON)])\n self.defence_no_trust.detect_poison()\n self.defence_trust.detect_poison()\n logger.info(self.defence_trust.evaluate_defence(real_clean))\n logger.info(self.defence_no_trust.evaluate_defence(real_clean))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/poison/test_roni.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nfrom sklearn.svm import SVC\n\nfrom art.attacks.poisoning.poisoning_attack_svm import PoisoningAttackSVM\nfrom art.estimators.classification.scikitlearn import SklearnClassifier, ScikitlearnSVC\nfrom art.defences.detector.poison.roni import RONIDefense\nfrom art.utils import load_mnist\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\nNB_TRAIN, NB_POISON, NB_VALID, NB_TRUSTED = 40, 5, 40, 15\nkernel = \"linear\"\n\n\nclass TestRONI(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n (x_train, y_train), (x_test, y_test), min_, max_ = load_mnist()\n y_train = np.argmax(y_train, axis=1)\n y_test = np.argmax(y_test, axis=1)\n zero_or_four = np.logical_or(y_train == 4, y_train == 0)\n x_train = x_train[zero_or_four]\n y_train = y_train[zero_or_four]\n tr_labels = np.zeros((y_train.shape[0], 2))\n tr_labels[y_train == 0] = np.array([1, 0])\n tr_labels[y_train == 4] = np.array([0, 1])\n y_train = tr_labels\n\n zero_or_four = np.logical_or(y_test == 4, y_test == 0)\n x_test = x_test[zero_or_four]\n y_test = y_test[zero_or_four]\n te_labels = np.zeros((y_test.shape[0], 2))\n te_labels[y_test == 0] = np.array([1, 0])\n te_labels[y_test == 4] = np.array([0, 1])\n y_test = te_labels\n\n n_samples_train = x_train.shape[0]\n n_features_train = x_train.shape[1] * x_train.shape[2] * x_train.shape[3]\n n_samples_test = x_test.shape[0]\n n_features_test = x_test.shape[1] * x_test.shape[2] * x_test.shape[3]\n\n x_train = x_train.reshape(n_samples_train, n_features_train)\n x_test = x_test.reshape(n_samples_test, n_features_test)\n x_train = x_train[:NB_TRAIN]\n y_train = y_train[:NB_TRAIN]\n\n trusted_data = x_test[:NB_TRUSTED]\n trusted_labels = y_test[:NB_TRUSTED]\n x_test = x_test[NB_TRUSTED:]\n y_test = y_test[NB_TRUSTED:]\n valid_data = x_test[:NB_VALID]\n valid_labels = y_test[:NB_VALID]\n x_test = x_test[NB_VALID:]\n y_test = y_test[NB_VALID:]\n\n no_defense = ScikitlearnSVC(model=SVC(kernel=kernel, gamma=\"auto\"), clip_values=(min_, max_))\n no_defense.fit(x=x_train, y=y_train)\n poison_points = np.random.randint(no_defense._model.support_vectors_.shape[0], size=NB_POISON)\n all_poison_init = np.copy(no_defense._model.support_vectors_[poison_points])\n poison_labels = np.array([1, 1]) - no_defense.predict(all_poison_init)\n\n svm_attack = PoisoningAttackSVM(\n classifier=no_defense,\n x_train=x_train,\n y_train=y_train,\n step=0.1,\n eps=1.0,\n x_val=valid_data,\n y_val=valid_labels,\n max_iter=200,\n )\n\n poisoned_data, _ = svm_attack.poison(all_poison_init, y=poison_labels)\n\n # Stack on poison to data and add provenance of bad actor\n all_data = np.vstack([x_train, poisoned_data])\n all_labels = np.vstack([y_train, poison_labels])\n\n model = SVC(kernel=kernel, gamma=\"auto\")\n cls.mnist = (\n (all_data, all_labels),\n (x_test, y_test),\n (trusted_data, trusted_labels),\n (valid_data, valid_labels),\n (min_, max_),\n )\n cls.classifier = SklearnClassifier(model=model, clip_values=(min_, max_))\n\n cls.classifier.fit(all_data, all_labels)\n cls.defense_cal = RONIDefense(\n cls.classifier,\n all_data,\n all_labels,\n trusted_data,\n trusted_labels,\n eps=0.1,\n calibrated=True,\n )\n cls.defence_no_cal = RONIDefense(\n cls.classifier,\n all_data,\n all_labels,\n trusted_data,\n trusted_labels,\n eps=0.1,\n calibrated=False,\n )\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_wrong_parameters_1(self):\n self.assertRaises(ValueError, self.defence_no_cal.set_params, eps=-2.0)\n self.assertRaises(ValueError, self.defense_cal.set_params, eps=-2.0)\n\n def test_wrong_parameters_2(self):\n (all_data, _), (_, y_test), (_, _), (_, _), (_, _) = self.mnist\n self.assertRaises(\n ValueError,\n self.defence_no_cal.set_params,\n x_train=-all_data,\n y_train=y_test,\n )\n self.assertRaises(ValueError, self.defense_cal.set_params, x_train=-all_data, y_train=y_test)\n\n def test_detect_poison(self):\n _, clean_trust = self.defense_cal.detect_poison()\n _, clean_no_trust = self.defence_no_cal.detect_poison()\n real_clean = np.array([1 if i < NB_TRAIN else 0 for i in range(NB_TRAIN + NB_POISON)])\n pc_tp_cal = np.average(real_clean[:NB_TRAIN] == clean_trust[:NB_TRAIN])\n pc_tn_cal = np.average(real_clean[NB_TRAIN:] == clean_trust[NB_TRAIN:])\n self.assertGreaterEqual(pc_tn_cal, 0)\n self.assertGreaterEqual(pc_tp_cal, 0.7)\n\n pc_tp_no_cal = np.average(real_clean[:NB_TRAIN] == clean_no_trust[:NB_TRAIN])\n pc_tn_no_cal = np.average(real_clean[NB_TRAIN:] == clean_no_trust[NB_TRAIN:])\n self.assertGreaterEqual(pc_tn_no_cal, 0)\n self.assertGreaterEqual(pc_tp_no_cal, 0.7)\n\n def test_evaluate_defense(self):\n real_clean = np.array([1 if i < NB_TRAIN else 0 for i in range(NB_TRAIN + NB_POISON)])\n self.defence_no_cal.detect_poison()\n self.defense_cal.detect_poison()\n logger.info(self.defense_cal.evaluate_defence(real_clean))\n logger.info(self.defence_no_cal.evaluate_defence(real_clean))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/detector/poison/test_spectral_signature_defense.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.defences.detector.poison import SpectralSignatureDefense\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nNB_TRAIN, NB_TEST, BATCH_SIZE, EPS_MULTIPLIER, UB_PCT_POISON = 300, 10, 128, 1.5, 0.2\n\n\n@pytest.mark.parametrize(\"params\", [dict(batch_size=-1), dict(eps_multiplier=-1.0), dict(expected_pp_poison=2.0)])\ndef test_wrong_parameters(params, art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator()\n\n classifier.fit(x_train_mnist[:NB_TRAIN], y_train_mnist[:NB_TRAIN], nb_epochs=1)\n with pytest.raises(ValueError):\n _ = SpectralSignatureDefense(classifier, x_train_mnist[:NB_TRAIN], y_train_mnist[:NB_TRAIN], **params)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_detect_poison(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator()\n\n classifier.fit(x_train_mnist[:NB_TRAIN], y_train_mnist[:NB_TRAIN], nb_epochs=1)\n defence = SpectralSignatureDefense(\n classifier,\n x_train_mnist[:NB_TRAIN],\n y_train_mnist[:NB_TRAIN],\n batch_size=BATCH_SIZE,\n eps_multiplier=EPS_MULTIPLIER,\n expected_pp_poison=UB_PCT_POISON,\n )\n report, is_clean = defence.detect_poison()\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_evaluate_defense(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator()\n\n classifier.fit(x_train_mnist[:NB_TRAIN], y_train_mnist[:NB_TRAIN], nb_epochs=1)\n defence = SpectralSignatureDefense(\n classifier,\n x_train_mnist[:NB_TRAIN],\n y_train_mnist[:NB_TRAIN],\n batch_size=BATCH_SIZE,\n eps_multiplier=EPS_MULTIPLIER,\n expected_pp_poison=UB_PCT_POISON,\n )\n _ = defence.evaluate_defence(np.zeros(NB_TRAIN))\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport numpy as np\nimport pytest\n\n\n@pytest.fixture\ndef image_batch(channels_first):\n \"\"\"\n Image fixture of shape NHWC and NCHW.\n \"\"\"\n test_input = np.repeat(np.array(range(6)).reshape(6, 1), 24, axis=1).reshape((2, 3, 4, 6))\n if not channels_first:\n test_input = np.transpose(test_input, (0, 2, 3, 1))\n test_output = test_input.copy()\n return test_input, test_output\n\n\n@pytest.fixture\ndef image_batch_small():\n \"\"\"Create image fixture of shape (batch_size, channels, width, height).\"\"\"\n return np.zeros((2, 1, 4, 4))\n\n\n@pytest.fixture\ndef video_batch(channels_first):\n \"\"\"\n Video fixture of shape NFHWC and NCFHW.\n \"\"\"\n test_input = np.repeat(np.array(range(6)).reshape(6, 1), 24, axis=1).reshape((1, 3, 2, 4, 6))\n if not channels_first:\n test_input = np.transpose(test_input, (0, 2, 3, 4, 1))\n test_output = test_input.copy()\n return test_input, test_output\n\n\n@pytest.fixture\ndef tabular_batch():\n \"\"\"\n Create tabular data fixture of shape (batch_size, features).\n \"\"\"\n return np.zeros((2, 4))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_jpeg_compression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import JpegCompression\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass DataGenerator:\n \"\"\"\n Create image or video batch.\n \"\"\"\n\n def __init__(self, channels_first, channels, image_data=True, batch_size=2):\n self.channels_first = channels_first\n self.channels = (channels,)\n self.batch_size = batch_size\n self.image_data = image_data\n\n def get_data(self):\n temporal_index = () if self.image_data else (2,)\n if self.channels_first:\n data_shape = (self.batch_size,) + self.channels + temporal_index + (8, 12)\n else:\n data_shape = (self.batch_size,) + temporal_index + (8, 12) + self.channels\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 2, 3, 5], ids=[\"grayscale\", \"grayscale-2\", \"RGB\", \"grayscale-5\"])\ndef image_batch(request, channels_first):\n \"\"\"\n Image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n image_input = DataGenerator(channels_first, channels)\n test_input = image_input.get_data()\n test_output = test_input.copy()\n return test_input, test_output\n\n\n@pytest.fixture(params=[1, 2, 3, 5], ids=[\"grayscale\", \"grayscale-2\", \"RGB\", \"grayscale-5\"])\ndef video_batch(request, channels_first):\n \"\"\"\n Video fixtures of shape NFHWC and NCFHW.\n \"\"\"\n channels = request.param\n video_input = DataGenerator(channels_first, channels, image_data=False)\n test_input = video_input.get_data()\n test_output = test_input.copy()\n return test_input, test_output\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_jpeg_compression_image_data(art_warning, image_batch, channels_first, framework):\n try:\n test_input, test_output = image_batch\n jpeg_compression = JpegCompression(clip_values=(0, 255), channels_first=channels_first)\n\n assert_array_equal(jpeg_compression(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.framework_agnostic\ndef test_jpeg_compression_video_data(art_warning, video_batch, channels_first):\n try:\n test_input, test_output = video_batch\n jpeg_compression = JpegCompression(clip_values=(0, 255), channels_first=channels_first)\n\n assert_array_equal(jpeg_compression(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [False])\n@pytest.mark.framework_agnostic\ndef test_jpeg_compress(art_warning, image_batch, channels_first):\n try:\n test_input, test_output = image_batch\n # Run only for grayscale [1] and RGB [3] data because testing `_compress` which is applied internally only to\n # either grayscale or RGB data.\n if test_input.shape[-1] in [1, 3]:\n jpeg_compression = JpegCompression(clip_values=(0, 255))\n\n image_mode = \"RGB\" if test_input.shape[-1] == 3 else \"L\"\n test_single_input = np.squeeze(test_input[0]).astype(np.uint8)\n test_single_output = np.squeeze(test_output[0]).astype(np.uint8)\n\n assert_array_equal(jpeg_compression._compress(test_single_input, image_mode), test_single_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_spatial_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n jpeg_compression = JpegCompression(clip_values=(0, 255), channels_first=True)\n\n exc_msg = \"Unrecognized input dimension. JPEG compression can only be applied to image and video data.\"\n with pytest.raises(ValueError, match=exc_msg):\n jpeg_compression(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n JpegCompression(clip_values=(-1, 255))\n\n with pytest.raises(ValueError):\n _ = JpegCompression(clip_values=(0, 2))\n\n with pytest.raises(ValueError):\n _ = JpegCompression(clip_values=(0, 1), quality=-1)\n\n with pytest.raises(ValueError):\n _ = JpegCompression(clip_values=(0, 1, 2))\n\n with pytest.raises(ValueError):\n _ = JpegCompression(clip_values=(0, 1), verbose=\"False\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_mp3_compression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.defences.preprocessor import Mp3Compression\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass AudioInput:\n \"\"\"\n Create audio batch.\n \"\"\"\n\n def __init__(self, channels_first, channels, sample_rate=44100, batch_size=2):\n self.channels_first = channels_first\n self.channels = channels\n self.sample_rate = sample_rate\n self.batch_size = batch_size\n\n def get_data(self):\n if self.channels_first:\n shape = (self.batch_size, self.channels, self.sample_rate)\n else:\n shape = (self.batch_size, self.sample_rate, self.channels)\n return np.zeros(shape, dtype=np.int16)\n\n\n@pytest.fixture(params=[1, 2], ids=[\"mono\", \"stereo\"])\ndef audio_batch(request, channels_first):\n \"\"\"\n Audio fixtures of shape `(batch_size, channels, samples)` or `(batch_size, samples, channels)`.\n \"\"\"\n channels = request.param\n audio_input = AudioInput(channels_first, channels)\n test_input = audio_input.get_data()\n test_output = test_input.copy()\n return test_input, test_output, audio_input.sample_rate\n\n\ndef test_sample_rate_error(art_warning):\n try:\n exc_msg = \"Sample rate be must a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n Mp3Compression(sample_rate=0)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_non_temporal_data_error(art_warning, image_batch_small):\n try:\n test_input = image_batch_small\n mp3compression = Mp3Compression(sample_rate=16000)\n\n exc_msg = \"Mp3 compression can only be applied to temporal data across at least one channel.\"\n with pytest.raises(ValueError, match=exc_msg):\n mp3compression(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.skip_framework(\n \"keras\",\n \"pytorch\",\n \"scikitlearn\",\n)\ndef test_mp3_compression(art_warning, audio_batch, channels_first):\n try:\n test_input, test_output, sample_rate = audio_batch\n mp3compression = Mp3Compression(sample_rate=sample_rate, channels_first=channels_first)\n\n assert_array_equal(mp3compression(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.skip_framework(\n \"keras\",\n \"pytorch\",\n \"scikitlearn\",\n)\ndef test_mp3_compression_object(art_warning, audio_batch, channels_first):\n try:\n test_input, test_output, sample_rate = audio_batch\n test_input_object = np.array([x for x in test_input], dtype=object)\n mp3compression = Mp3Compression(sample_rate=sample_rate, channels_first=channels_first)\n\n assert_array_equal(mp3compression(test_input_object)[0], test_output)\n\n grad = mp3compression.estimate_gradient(x=test_input_object, grad=np.ones_like(test_input_object))\n\n assert grad.dtype == object\n assert grad.shape == (2, test_input.shape[1], 44100) if channels_first else (2, 44100, test_input.shape[2])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"keras\",\n \"pytorch\",\n \"scikitlearn\",\n)\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = Mp3Compression(sample_rate=1000, verbose=\"False\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_mp3_compression_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.defences.preprocessor import Mp3CompressionPyTorch\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass AudioInput:\n \"\"\"\n Create audio batch.\n \"\"\"\n\n def __init__(self, channels_first, channels, sample_rate=44100, batch_size=2):\n self.channels_first = channels_first\n self.channels = channels\n self.sample_rate = sample_rate\n self.batch_size = batch_size\n\n def get_data(self):\n if self.channels_first:\n shape = (self.batch_size, self.channels, self.sample_rate)\n else:\n shape = (self.batch_size, self.sample_rate, self.channels)\n return np.zeros(shape, dtype=np.int16)\n\n\n@pytest.fixture(params=[1, 2], ids=[\"mono\", \"stereo\"])\ndef audio_batch(request, channels_first):\n \"\"\"\n Audio fixtures of shape `(batch_size, channels, samples)` or `(batch_size, samples, channels)`.\n \"\"\"\n channels = request.param\n audio_input = AudioInput(channels_first, channels)\n test_input = audio_input.get_data()\n test_output = test_input.copy()\n return test_input, test_output, audio_input.sample_rate\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_sample_rate_error(art_warning):\n try:\n exc_msg = \"Sample rate be must a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n Mp3CompressionPyTorch(sample_rate=0)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_non_temporal_data_error(art_warning, image_batch_small):\n try:\n test_input = image_batch_small\n mp3compression = Mp3CompressionPyTorch(sample_rate=16000)\n\n exc_msg = \"Mp3 compression can only be applied to temporal data across at least one channel.\"\n with pytest.raises(ValueError, match=exc_msg):\n mp3compression(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_mp3_compression(art_warning, audio_batch, channels_first):\n try:\n test_input, test_output, sample_rate = audio_batch\n mp3compression = Mp3CompressionPyTorch(sample_rate=sample_rate, channels_first=channels_first)\n\n assert_array_equal(mp3compression(test_input)[0], test_output)\n\n import torch\n\n test_input_tensor = torch.from_numpy(test_input.astype(float))\n test_input_tensor.requires_grad = True\n loss = mp3compression.forward(x=test_input_tensor, y=test_output)[0].sum()\n loss.backward()\n\n assert test_input_tensor.grad is not None\n if channels_first:\n assert test_input_tensor.grad.detach().cpu().numpy().shape == (2, test_input.shape[1], 44100)\n else:\n assert test_input_tensor.grad.detach().cpu().numpy().shape == (2, 44100, test_input.shape[2])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = Mp3CompressionPyTorch(sample_rate=1000, verbose=\"False\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_preprocessor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nimport pytest\n\nfrom art.defences.preprocessor.preprocessor import PreprocessorPyTorch\nfrom tests.utils import ARTTestException\n\n\nclass DummyPreprocessorPyTorch(PreprocessorPyTorch):\n def forward(self, x, y):\n return x, y\n\n\n@pytest.mark.parametrize(\"is_fitted\", [True, False])\n@pytest.mark.parametrize(\"apply_fit\", [True, False])\n@pytest.mark.parametrize(\"apply_predict\", [True, False])\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_preprocessor_pytorch_init(art_warning, is_fitted, apply_fit, apply_predict):\n try:\n import torch\n\n preprocessor = DummyPreprocessorPyTorch(\n device_type=\"cpu\",\n is_fitted=is_fitted,\n apply_fit=apply_fit,\n apply_predict=apply_predict,\n )\n\n assert preprocessor.device == torch.device(\"cpu\")\n assert preprocessor.is_fitted == is_fitted\n assert preprocessor.apply_fit == apply_fit\n assert preprocessor.apply_predict == apply_predict\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_resample.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\nimport resampy\n\nfrom art.defences.preprocessor import Resample\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 2], ids=[\"one_channel\", \"two_channel\"])\ndef audio_batch(request):\n \"\"\"\n Create audio fixtures of shape (batch_size=2, channels={1,2}, samples).\n \"\"\"\n sample_rate_orig = 16000\n sample_rate_new = 8000\n test_input = np.zeros((2, request.param, sample_rate_orig), dtype=np.int16)\n test_output = np.zeros((2, request.param, sample_rate_new), dtype=np.int16)\n return test_input, test_output, sample_rate_orig, sample_rate_new\n\n\n@pytest.mark.framework_agnostic\ndef test_sample_rate_original_error(art_warning):\n try:\n exc_msg = \"Original sampling rate be must a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n Resample(sr_original=0, sr_new=16000)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_sample_rate_new_error(art_warning):\n try:\n exc_msg = \"New sampling rate be must a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n Resample(sr_original=16000, sr_new=0)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_temporal_data_error(art_warning, image_batch_small):\n try:\n test_input = image_batch_small\n resample = Resample(16000, 16000)\n\n exc_msg = \"Resampling can only be applied to temporal data across at least one channel.\"\n with pytest.raises(ValueError, match=exc_msg):\n resample(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_resample(art_warning, audio_batch, mocker):\n try:\n test_input, test_output, sr_orig, sr_new = audio_batch\n\n mocker.patch(\"resampy.resample\", autospec=True)\n resampy.resample.return_value = test_input[:, :, :sr_new]\n\n resampler = Resample(sr_original=sr_orig, sr_new=sr_new, channels_first=True)\n assert resampler(test_input)[0].shape == test_output.shape\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_spatial_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.defences.preprocessor import SpatialSmoothing\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\ndef test_spatial_smoothing_median_filter_call(art_warning):\n try:\n test_input = np.array([[[[1, 2], [3, 4]]]])\n test_output = np.array([[[[1, 2], [3, 3]]]])\n spatial_smoothing = SpatialSmoothing(channels_first=True, window_size=2)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"window_size\", [1, 2, 10])\n@pytest.mark.framework_agnostic\ndef test_spatial_smoothing_image_data(art_warning, image_batch, channels_first, window_size):\n try:\n test_input, test_output = image_batch\n spatial_smoothing = SpatialSmoothing(channels_first=channels_first, window_size=window_size)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n\n spatial_smoothing = SpatialSmoothing(channels_first=channels_first, window_size=window_size, clip_values=(0, 1))\n\n spatial_smoothing(test_input)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.framework_agnostic\ndef test_spatial_smoothing_video_data(art_warning, video_batch, channels_first):\n try:\n test_input, test_output = video_batch\n spatial_smoothing = SpatialSmoothing(channels_first=channels_first, window_size=2)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_spatial_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n spatial_smoothing = SpatialSmoothing(channels_first=True)\n\n exc_msg = \"Unrecognized input dimension. Spatial smoothing can only be applied to image and video data.\"\n with pytest.raises(ValueError, match=exc_msg):\n spatial_smoothing(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_window_size_error(art_warning):\n try:\n exc_msg = \"Sliding window size must be a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothing(window_size=0)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_triple_clip_values_error(art_warning):\n try:\n exc_msg = \"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothing(clip_values=(0, 1, 2))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_relation_clip_values_error(art_warning):\n try:\n exc_msg = \"Invalid 'clip_values': min >= max.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothing(clip_values=(1, 0))\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_spatial_smoothing_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\n\nfrom art.defences.preprocessor.spatial_smoothing_pytorch import SpatialSmoothingPyTorch\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.xfail(\n reason=\"\"\"a) SciPy's \"reflect\" padding mode is not supported in PyTorch. The \"reflect\" model in PyTorch maps\n to the \"mirror\" mode in SciPy; b) torch.median() takes the smaller value when the window size is even.\"\"\"\n)\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_spatial_smoothing_median_filter_call(art_warning):\n try:\n test_input = np.array([[[[1, 2], [3, 4]]]])\n test_output = np.array([[[[1, 2], [3, 3]]]])\n spatial_smoothing = SpatialSmoothingPyTorch(channels_first=True, window_size=2)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_spatial_smoothing_median_filter_call_expected_behavior(art_warning):\n try:\n test_input = np.array([[[[1, 2], [3, 4]]]])\n test_output = np.array([[[[2, 2], [2, 2]]]])\n spatial_smoothing = SpatialSmoothingPyTorch(channels_first=True, window_size=2)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_spatial_smoothing_estimate_gradient(art_warning):\n try:\n test_input = np.array([[[[1], [2]], [[3], [4]]]]).astype(float)\n test_output = np.array([[[[2], [2]], [[2], [2]]]]).astype(float)\n spatial_smoothing = SpatialSmoothingPyTorch(channels_first=False, window_size=2)\n\n test_gradients = spatial_smoothing.estimate_gradient(x=test_input, grad=np.ones_like(test_output).astype(float))\n\n assert test_gradients.shape == test_input.shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\n \"window_size\",\n [\n 1,\n 2,\n pytest.param(\n 10,\n marks=pytest.mark.xfail(\n reason=\"Window size of 10 fails, because PyTorch requires that Padding size should be less than \"\n \"the corresponding input dimension.\"\n ),\n ),\n ],\n)\ndef test_spatial_smoothing_image_data(art_warning, image_batch, channels_first, window_size):\n try:\n test_input, test_output = image_batch\n spatial_smoothing = SpatialSmoothingPyTorch(channels_first=channels_first, window_size=window_size)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_spatial_smoothing_video_data(art_warning, video_batch, channels_first):\n try:\n test_input, test_output = video_batch\n spatial_smoothing = SpatialSmoothingPyTorch(channels_first=channels_first, window_size=2)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_non_spatial_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n spatial_smoothing = SpatialSmoothingPyTorch(channels_first=True)\n\n exc_msg = \"Unrecognized input dimension. Spatial smoothing can only be applied to image and video data.\"\n with pytest.raises(ValueError, match=exc_msg):\n spatial_smoothing(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_window_size_error(art_warning):\n try:\n exc_msg = \"Sliding window size must be a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothingPyTorch(window_size=0)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_triple_clip_values_error(art_warning):\n try:\n exc_msg = \"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothingPyTorch(clip_values=(0, 1, 2))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_relation_clip_values_error(art_warning):\n try:\n exc_msg = \"Invalid 'clip_values': min >= max.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothingPyTorch(clip_values=(1, 0))\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_spatial_smoothing_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\nimport tensorflow as tf\n\nfrom art.defences.preprocessor.spatial_smoothing_tensorflow import SpatialSmoothingTensorFlowV2, median_filter2d\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.xfail()\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_spatial_smoothing_median_filter_call(art_warning):\n try:\n test_input = np.array([[[[1], [2]], [[3], [4]]]])\n test_output = np.array([[[[1], [2]], [[3], [3]]]])\n spatial_smoothing = SpatialSmoothingTensorFlowV2(channels_first=False, window_size=3)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_spatial_smoothing_median_filter_call_expected_behavior(art_warning):\n try:\n test_input = np.array([[[[1], [2]], [[3], [4]]]])\n test_output = np.array([[[[3], [3]], [[2], [2]]]])\n spatial_smoothing = SpatialSmoothingTensorFlowV2(channels_first=False, window_size=3)\n\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_spatial_smoothing_estimate_gradient(art_warning):\n try:\n test_input = np.array([[[[1], [2]], [[3], [4]]]])\n test_output = np.array([[[[2], [2]], [[2], [2]]]])\n spatial_smoothing = SpatialSmoothingTensorFlowV2(channels_first=False, window_size=3)\n\n test_gradients = spatial_smoothing.estimate_gradient(x=test_input, grad=np.ones_like(test_output))\n\n assert test_gradients.shape == test_input.shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\n \"window_size\",\n [\n 1,\n 3,\n pytest.param(\n 10,\n marks=pytest.mark.xfail(\n reason=\"Window size of 10 fails, because TensorFlow requires that Padding size should be less than \"\n \"the corresponding input dimension.\"\n ),\n ),\n ],\n)\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_spatial_smoothing_image_data(art_warning, image_batch, channels_first, window_size):\n try:\n test_input, test_output = image_batch\n\n if channels_first:\n exc_msg = \"Only channels last input data is supported\"\n with pytest.raises(ValueError, match=exc_msg):\n _ = SpatialSmoothingTensorFlowV2(channels_first=channels_first, window_size=window_size)\n else:\n spatial_smoothing = SpatialSmoothingTensorFlowV2(channels_first=channels_first, window_size=window_size)\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_spatial_smoothing_video_data(art_warning, video_batch, channels_first):\n try:\n test_input, test_output = video_batch\n\n if channels_first:\n exc_msg = \"Only channels last input data is supported\"\n with pytest.raises(ValueError, match=exc_msg):\n _ = SpatialSmoothingTensorFlowV2(channels_first=channels_first, window_size=3)\n else:\n spatial_smoothing = SpatialSmoothingTensorFlowV2(channels_first=channels_first, window_size=3)\n assert_array_equal(spatial_smoothing(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow\")\ndef test_non_spatial_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n spatial_smoothing = SpatialSmoothingTensorFlowV2(channels_first=False)\n\n exc_msg = \"Unrecognized input dimension. Spatial smoothing can only be applied to image\"\n with pytest.raises(ValueError, match=exc_msg):\n spatial_smoothing(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_window_size_error(art_warning):\n try:\n exc_msg = \"Sliding window size must be a positive integer.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothingTensorFlowV2(window_size=0)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_triple_clip_values_error(art_warning):\n try:\n exc_msg = \"'clip_values' should be a tuple of 2 floats or arrays containing the allowed data range.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothingTensorFlowV2(clip_values=(0, 1, 2))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_relation_clip_values_error(art_warning):\n try:\n exc_msg = \"Invalid 'clip_values': min >= max.\"\n with pytest.raises(ValueError, match=exc_msg):\n SpatialSmoothingTensorFlowV2(clip_values=(1, 0))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_median_filter2d(art_warning):\n try:\n # Create a test image: batch of 1, 5x5 grayscale\n x = np.zeros((1, 5, 5, 1), dtype=np.float32)\n x[0, 0, 0, 0] = 1.0\n x[0, 0, 2, 0] = 1.0\n x[0, 0, 4, 0] = 1.0\n x[0, 2, 0, 0] = 1.0\n x[0, 2, 2, 0] = 1.0\n x[0, 2, 4, 0] = 1.0\n x[0, 4, 0, 0] = 1.0\n x[0, 4, 2, 0] = 1.0\n x[0, 4, 4, 0] = 1.0\n\n x_tf = tf.constant(x)\n\n # Apply both filters\n filter_size = 1\n custom_result = median_filter2d(x_tf, filter_size=filter_size, padding=\"REFLECT\")\n\n expected_results = np.array([1.0, 0.0, 1.0, 0.0, 1.0])\n assert np.isclose(custom_result[0, :, 2, 0].numpy(), expected_results).all()\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_video_compression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.defences.preprocessor import VideoCompression\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture\ndef video_batch(channels_first):\n \"\"\"\n Video fixture of shape NFHWC and NCFHW.\n \"\"\"\n test_input = np.stack((np.zeros((3, 25, 4, 6)), np.ones((3, 25, 4, 6))))\n if not channels_first:\n test_input = np.transpose(test_input, (0, 2, 3, 4, 1))\n test_output = test_input.copy()\n return test_input, test_output\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.skip_framework(\n \"keras\",\n \"pytorch\",\n \"scikitlearn\",\n)\ndef test_video_compression(art_warning, video_batch, channels_first):\n try:\n test_input, test_output = video_batch\n video_compression = VideoCompression(video_format=\"mp4\", constant_rate_factor=0, channels_first=channels_first)\n\n assert_array_equal(video_compression(test_input)[0], test_output)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"keras\",\n \"pytorch\",\n \"scikitlearn\",\n)\ndef test_compress_video_call(art_warning):\n try:\n test_input = np.arange(12).reshape((1, 3, 1, 2, 2))\n video_compression = VideoCompression(video_format=\"mp4\", constant_rate_factor=50, channels_first=True)\n\n assert np.any(np.not_equal(video_compression(test_input)[0], test_input))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"constant_rate_factor\", [-1, 52])\ndef test_constant_rate_factor_error(art_warning, constant_rate_factor):\n try:\n exc_msg = r\"Constant rate factor must be an integer in the range \\[0, 51\\].\"\n with pytest.raises(ValueError, match=exc_msg):\n VideoCompression(video_format=\"\", constant_rate_factor=constant_rate_factor)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_non_spatio_temporal_data_error(art_warning, image_batch_small):\n try:\n test_input = image_batch_small\n video_compression = VideoCompression(video_format=\"\")\n\n exc_msg = \"Video compression can only be applied to spatio-temporal data.\"\n with pytest.raises(ValueError, match=exc_msg):\n video_compression(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/test_video_compression_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.defences.preprocessor import VideoCompressionPyTorch\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture\ndef video_batch(channels_first):\n \"\"\"\n Video fixture of shape NFHWC and NCFHW.\n \"\"\"\n test_input = np.stack((np.zeros((3, 25, 4, 6)), np.ones((3, 25, 4, 6))))\n if not channels_first:\n test_input = np.transpose(test_input, (0, 2, 3, 4, 1))\n test_output = test_input.copy()\n return test_input, test_output\n\n\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_video_compression(art_warning, video_batch, channels_first):\n try:\n test_input, test_output = video_batch\n video_compression = VideoCompressionPyTorch(\n video_format=\"mp4\", constant_rate_factor=0, channels_first=channels_first\n )\n\n assert_array_equal(video_compression(test_input)[0], test_output)\n\n import torch\n\n test_input_tensor = torch.from_numpy(test_input)\n test_input_tensor.requires_grad = True\n loss = video_compression.forward(x=test_input_tensor, y=test_output)[0].sum()\n loss.backward()\n\n assert test_input_tensor.grad is not None\n if channels_first:\n assert test_input_tensor.grad.detach().cpu().numpy().shape == (2, 3, 25, 4, 6)\n else:\n assert test_input_tensor.grad.detach().cpu().numpy().shape == (2, 25, 4, 6, 3)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_compress_video_call(art_warning):\n try:\n test_input = np.arange(12).reshape((1, 3, 1, 2, 2))\n video_compression = VideoCompressionPyTorch(video_format=\"mp4\", constant_rate_factor=50, channels_first=True)\n\n assert np.any(np.not_equal(video_compression(test_input)[0], test_input))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.parametrize(\"constant_rate_factor\", [-1, 52])\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_constant_rate_factor_error(art_warning, constant_rate_factor):\n try:\n exc_msg = r\"Constant rate factor must be an integer in the range \\[0, 51\\].\"\n with pytest.raises(ValueError, match=exc_msg):\n VideoCompressionPyTorch(video_format=\"\", constant_rate_factor=constant_rate_factor)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_non_spatio_temporal_data_error(art_warning, image_batch_small):\n try:\n test_input = image_batch_small\n video_compression = VideoCompressionPyTorch(video_format=\"\")\n\n exc_msg = \"Video compression can only be applied to spatio-temporal data.\"\n with pytest.raises(ValueError, match=exc_msg):\n video_compression(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\")\ndef test_check_params(art_warning, image_batch_small):\n try:\n with pytest.raises(ValueError):\n _ = VideoCompressionPyTorch(video_format=\"\", verbose=\"False\")\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/cutmix/test_cutmix.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import CutMix\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request):\n \"\"\"\n Image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request):\n \"\"\"\n Empty image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"alpha\", [1.0, 2.5])\n@pytest.mark.parametrize(\"probability\", [0.5, 1.0])\ndef test_mixup_image_data(art_warning, image_batch, alpha, probability):\n try:\n mixup = CutMix(num_classes=10, alpha=alpha, probability=probability)\n x, y = mixup(image_batch, np.arange(len(image_batch)))\n assert_array_almost_equal(x, image_batch)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(image_batch)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"alpha\", [1.0])\n@pytest.mark.parametrize(\"probability\", [1.0])\ndef test_mixup_empty_data(art_warning, empty_image, alpha, probability):\n try:\n mixup = CutMix(num_classes=10, alpha=alpha, probability=probability)\n x, y = mixup(empty_image, np.arange(len(empty_image)))\n assert_array_equal(x, empty_image)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(empty_image)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_missing_labels_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n mixup = CutMix(num_classes=10)\n\n exc_msg = \"Labels `y` cannot be None.\"\n with pytest.raises(ValueError, match=exc_msg):\n mixup(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = CutMix(num_classes=0)\n\n with pytest.raises(ValueError):\n _ = CutMix(num_classes=10, alpha=0)\n\n with pytest.raises(ValueError):\n _ = CutMix(num_classes=10, alpha=-1)\n\n with pytest.raises(ValueError):\n _ = CutMix(num_classes=10, probability=1.1)\n\n with pytest.raises(ValueError):\n _ = CutMix(num_classes=10, probability=-0.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/cutmix/test_cutmix_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import CutMixPyTorch\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request):\n \"\"\"\n Image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request):\n \"\"\"\n Empty image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"alpha\", [1.0, 2.5])\n@pytest.mark.parametrize(\"probability\", [0.5, 1.0])\ndef test_mixup_image_data(art_warning, image_batch, alpha, probability):\n try:\n mixup = CutMixPyTorch(num_classes=10, alpha=alpha, probability=probability)\n x, y = mixup(image_batch, np.arange(len(image_batch)))\n assert_array_almost_equal(x, image_batch)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(image_batch)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"alpha\", [1.0])\n@pytest.mark.parametrize(\"probability\", [1.0])\ndef test_mixup_empty_data(art_warning, empty_image, alpha, probability):\n try:\n mixup = CutMixPyTorch(num_classes=10, alpha=alpha, probability=probability)\n x, y = mixup(empty_image, np.arange(len(empty_image)))\n assert_array_equal(x, empty_image)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(empty_image)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_missing_labels_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n mixup = CutMixPyTorch(num_classes=10)\n\n exc_msg = \"Labels `y` cannot be None.\"\n with pytest.raises(ValueError, match=exc_msg):\n mixup(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = CutMixPyTorch(num_classes=0)\n\n with pytest.raises(ValueError):\n _ = CutMixPyTorch(num_classes=10, alpha=0)\n\n with pytest.raises(ValueError):\n _ = CutMixPyTorch(num_classes=10, alpha=-1)\n\n with pytest.raises(ValueError):\n _ = CutMixPyTorch(num_classes=10, probability=1.1)\n\n with pytest.raises(ValueError):\n _ = CutMixPyTorch(num_classes=10, probability=-0.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/cutmix/test_cutmix_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import CutMixTensorFlowV2\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request):\n \"\"\"\n Image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request):\n \"\"\"\n Empty image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"alpha\", [1.0, 2.5])\n@pytest.mark.parametrize(\"probability\", [0.5, 1.0])\ndef test_mixup_image_data(art_warning, image_batch, alpha, probability):\n try:\n mixup = CutMixTensorFlowV2(num_classes=10, alpha=alpha, probability=probability)\n x, y = mixup(image_batch, np.arange(len(image_batch)))\n assert_array_almost_equal(x, image_batch)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(image_batch)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"alpha\", [1.0])\n@pytest.mark.parametrize(\"probability\", [1.0])\ndef test_mixup_empty_data(art_warning, empty_image, alpha, probability):\n try:\n mixup = CutMixTensorFlowV2(num_classes=10, alpha=alpha, probability=probability)\n x, y = mixup(empty_image, np.arange(len(empty_image)))\n assert_array_equal(x, empty_image)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(empty_image)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_missing_labels_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n mixup = CutMixTensorFlowV2(num_classes=10)\n\n exc_msg = \"Labels `y` cannot be None.\"\n with pytest.raises(ValueError, match=exc_msg):\n mixup(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = CutMixTensorFlowV2(num_classes=0)\n\n with pytest.raises(ValueError):\n _ = CutMixTensorFlowV2(num_classes=10, alpha=0)\n\n with pytest.raises(ValueError):\n _ = CutMixTensorFlowV2(num_classes=10, alpha=-1)\n\n with pytest.raises(ValueError):\n _ = CutMixTensorFlowV2(num_classes=10, probability=1.1)\n\n with pytest.raises(ValueError):\n _ = CutMixTensorFlowV2(num_classes=10, probability=-0.1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/cutout/test_cutout.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import Cutout\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request, channels_first):\n \"\"\"\n Image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, channels, 12, 8)\n else:\n data_shape = (2, 12, 8, channels)\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef video_batch(request, channels_first):\n \"\"\"\n Video fixtures of shape NFHWC and NCFHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, 2, channels, 12, 8)\n else:\n data_shape = (2, 2, 12, 8, channels)\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request, channels_first):\n \"\"\"\n Empty image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, channels, 12, 8)\n else:\n data_shape = (2, 12, 8, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"length\", [4, 5])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_cutout_image_data(art_warning, image_batch, length, channels_first):\n try:\n cutout = Cutout(length=length, channels_first=channels_first)\n count = np.not_equal(cutout(image_batch)[0], image_batch).sum()\n\n n = image_batch.shape[0]\n if channels_first:\n channels = image_batch.shape[1]\n else:\n channels = image_batch.shape[-1]\n assert count <= n * channels * length * length\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"length\", [4])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_cutout_video_data(art_warning, video_batch, length, channels_first):\n try:\n cutout = Cutout(length=length, channels_first=channels_first)\n count = np.not_equal(cutout(video_batch)[0], video_batch).sum()\n\n n = video_batch.shape[0]\n frames = video_batch.shape[1]\n if channels_first:\n channels = video_batch.shape[2]\n else:\n channels = video_batch.shape[-1]\n assert count <= n * frames * channels * length * length\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"length\", [4])\n@pytest.mark.parametrize(\"channels_first\", [True])\ndef test_cutout_empty_data(art_warning, empty_image, length, channels_first):\n try:\n cutout = Cutout(length=length, channels_first=channels_first)\n assert_array_equal(cutout(empty_image)[0], empty_image)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_non_image_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n cutout = Cutout(length=4, channels_first=True)\n\n exc_msg = \"Unrecognized input dimension. Cutout can only be applied to image and video data.\"\n with pytest.raises(ValueError, match=exc_msg):\n cutout(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = Cutout(length=-1)\n\n with pytest.raises(ValueError):\n _ = Cutout(length=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/cutout/test_cutout_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import CutoutPyTorch\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request, channels_first):\n \"\"\"\n Image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, channels, 12, 8)\n else:\n data_shape = (2, 12, 8, channels)\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef video_batch(request, channels_first):\n \"\"\"\n Video fixtures of shape NFHWC and NCFHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, 2, channels, 12, 8)\n else:\n data_shape = (2, 2, 12, 8, channels)\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request, channels_first):\n \"\"\"\n Empty image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, channels, 12, 8)\n else:\n data_shape = (2, 12, 8, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"length\", [2, 4])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_cutout_image_data(art_warning, image_batch, length, channels_first):\n try:\n cutout = CutoutPyTorch(length=length, channels_first=channels_first)\n count = np.not_equal(cutout(image_batch)[0], image_batch).sum()\n\n n = image_batch.shape[0]\n if channels_first:\n channels = image_batch.shape[1]\n else:\n channels = image_batch.shape[-1]\n assert count <= n * channels * length * length\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"length\", [4])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_cutout_video_data(art_warning, video_batch, length, channels_first):\n try:\n cutout = CutoutPyTorch(length=length, channels_first=channels_first)\n count = np.not_equal(cutout(video_batch)[0], video_batch).sum()\n\n n = video_batch.shape[0]\n frames = video_batch.shape[1]\n if channels_first:\n channels = video_batch.shape[2]\n else:\n channels = video_batch.shape[-1]\n assert count <= n * frames * channels * length * length\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"length\", [4])\n@pytest.mark.parametrize(\"channels_first\", [True])\ndef test_cutout_empty_data(art_warning, empty_image, length, channels_first):\n try:\n cutout = CutoutPyTorch(length=length, channels_first=channels_first)\n assert_array_equal(cutout(empty_image)[0], empty_image)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_non_image_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n cutout = CutoutPyTorch(length=8, channels_first=True)\n\n exc_msg = \"Unrecognized input dimension. Cutout can only be applied to image and video data.\"\n with pytest.raises(ValueError, match=exc_msg):\n cutout(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = CutoutPyTorch(length=-1)\n\n with pytest.raises(ValueError):\n _ = CutoutPyTorch(length=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/cutout/test_cutout_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor.cutout.cutout_tensorflow import CutoutTensorFlowV2, random_cutout\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request, channels_first):\n \"\"\"\n Image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, channels, 12, 8)\n else:\n data_shape = (2, 12, 8, channels)\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef video_batch(request, channels_first):\n \"\"\"\n Video fixtures of shape NFHWC and NCFHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, 2, channels, 12, 8)\n else:\n data_shape = (2, 2, 12, 8, channels)\n return (255 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request, channels_first):\n \"\"\"\n Empty image fixtures of shape NHWC and NCHW.\n \"\"\"\n channels = request.param\n\n if channels_first:\n data_shape = (2, channels, 12, 8)\n else:\n data_shape = (2, 12, 8, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"length\", [2, 4])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_cutout_image_data(art_warning, image_batch, length, channels_first):\n try:\n cutout = CutoutTensorFlowV2(length=length, channels_first=channels_first)\n count = np.not_equal(cutout(image_batch)[0], image_batch).sum()\n\n n = image_batch.shape[0]\n if channels_first:\n channels = image_batch.shape[1]\n else:\n channels = image_batch.shape[-1]\n assert count <= n * channels * length * length\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"length\", [4])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\ndef test_cutout_video_data(art_warning, video_batch, length, channels_first):\n try:\n cutout = CutoutTensorFlowV2(length=length, channels_first=channels_first)\n count = np.not_equal(cutout(video_batch)[0], video_batch).sum()\n\n n = video_batch.shape[0]\n frames = video_batch.shape[1]\n if channels_first:\n channels = video_batch.shape[2]\n else:\n channels = video_batch.shape[-1]\n assert count <= n * frames * channels * length * length\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_random_cutout(art_warning):\n try:\n import tensorflow as tf\n\n x = np.ones((2, 5, 5, 1), dtype=np.float32)\n\n # Fixed seeds\n tf_seed = tf.constant([42, 24], dtype=tf.int32) # Tensor seed for custom function\n\n # Apply both cutout methods\n custom_cutout = random_cutout(tf.constant(x), mask_size=(2, 2), seed=tf_seed)\n\n expected_cutout = np.array(\n [\n [1.0, 1.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0, 1.0, 1.0],\n ]\n )\n assert np.isclose(custom_cutout[0, :, :, 0].numpy(), expected_cutout).all()\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"length\", [4])\n@pytest.mark.parametrize(\"channels_first\", [True])\ndef test_cutout_empty_data(art_warning, empty_image, length, channels_first):\n try:\n cutout = CutoutTensorFlowV2(length=length, channels_first=channels_first)\n assert_array_equal(cutout(empty_image)[0], empty_image)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_non_image_data_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n cutout = CutoutTensorFlowV2(length=8, channels_first=True)\n\n exc_msg = \"Unrecognized input dimension. Cutout can only be applied to image and video data.\"\n with pytest.raises(ValueError, match=exc_msg):\n cutout(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = CutoutTensorFlowV2(length=-1)\n\n with pytest.raises(ValueError):\n _ = CutoutTensorFlowV2(length=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/mixup/test_mixup.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import Mixup\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request):\n \"\"\"\n Image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request):\n \"\"\"\n Empty image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"alpha\", [1.0, 2.5])\n@pytest.mark.parametrize(\"num_mix\", [2, 3])\ndef test_mixup_image_data(art_warning, image_batch, alpha, num_mix):\n try:\n mixup = Mixup(num_classes=10, alpha=alpha, num_mix=num_mix)\n x, y = mixup(image_batch, np.arange(len(image_batch)))\n assert_array_almost_equal(x, image_batch)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(image_batch)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"alpha\", [1.0])\n@pytest.mark.parametrize(\"num_mix\", [2])\ndef test_mixup_empty_data(art_warning, empty_image, alpha, num_mix):\n try:\n mixup = Mixup(num_classes=10, alpha=alpha, num_mix=num_mix)\n x, y = mixup(empty_image, np.arange(len(empty_image)))\n assert_array_equal(x, empty_image)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(empty_image)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_missing_labels_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n mixup = Mixup(num_classes=10)\n\n exc_msg = \"Labels `y` cannot be None.\"\n with pytest.raises(ValueError, match=exc_msg):\n mixup(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = Mixup(num_classes=0)\n\n with pytest.raises(ValueError):\n _ = Mixup(num_classes=10, alpha=0)\n\n with pytest.raises(ValueError):\n _ = Mixup(num_classes=10, alpha=-1)\n\n with pytest.raises(ValueError):\n _ = Mixup(num_classes=10, num_mix=1)\n\n with pytest.raises(ValueError):\n _ = Mixup(num_classes=10, num_mix=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/mixup/test_mixup_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import MixupPyTorch\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request):\n \"\"\"\n Image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request):\n \"\"\"\n Empty image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"alpha\", [1.0, 2.5])\n@pytest.mark.parametrize(\"num_mix\", [2, 3])\ndef test_mixup_image_data(art_warning, image_batch, alpha, num_mix):\n try:\n mixup = MixupPyTorch(num_classes=10, alpha=alpha, num_mix=num_mix)\n x, y = mixup(image_batch, np.arange(len(image_batch)))\n assert_array_almost_equal(x, image_batch)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(image_batch)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"alpha\", [1.0])\n@pytest.mark.parametrize(\"num_mix\", [2])\ndef test_mixup_empty_data(art_warning, empty_image, alpha, num_mix):\n try:\n mixup = MixupPyTorch(num_classes=10, alpha=alpha, num_mix=num_mix)\n x, y = mixup(empty_image, np.arange(len(empty_image)))\n assert_array_equal(x, empty_image)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(empty_image)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_missing_labels_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n mixup = MixupPyTorch(num_classes=10)\n\n exc_msg = \"Labels `y` cannot be None.\"\n with pytest.raises(ValueError, match=exc_msg):\n mixup(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = MixupPyTorch(num_classes=0)\n\n with pytest.raises(ValueError):\n _ = MixupPyTorch(num_classes=10, alpha=0)\n\n with pytest.raises(ValueError):\n _ = MixupPyTorch(num_classes=10, alpha=-1)\n\n with pytest.raises(ValueError):\n _ = MixupPyTorch(num_classes=10, num_mix=1)\n\n with pytest.raises(ValueError):\n _ = MixupPyTorch(num_classes=10, num_mix=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/preprocessor/mixup/test_mixup_tensorflow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.defences.preprocessor import MixupTensorFlowV2\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef image_batch(request):\n \"\"\"\n Image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.fixture(params=[1, 3], ids=[\"grayscale\", \"RGB\"])\ndef empty_image(request):\n \"\"\"\n Empty image fixtures of shape NHWC.\n \"\"\"\n channels = request.param\n data_shape = (4, 8, 12, channels)\n return np.zeros(data_shape).astype(ART_NUMPY_DTYPE)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"alpha\", [1.0, 2.5])\n@pytest.mark.parametrize(\"num_mix\", [2, 3])\ndef test_mixup_image_data(art_warning, image_batch, alpha, num_mix):\n try:\n mixup = MixupTensorFlowV2(num_classes=10, alpha=alpha, num_mix=num_mix)\n x, y = mixup(image_batch, np.arange(len(image_batch)))\n assert_array_almost_equal(x, image_batch)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(image_batch)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"alpha\", [1.0])\n@pytest.mark.parametrize(\"num_mix\", [2])\ndef test_mixup_empty_data(art_warning, empty_image, alpha, num_mix):\n try:\n mixup = MixupTensorFlowV2(num_classes=10, alpha=alpha, num_mix=num_mix)\n x, y = mixup(empty_image, np.arange(len(empty_image)))\n assert_array_equal(x, empty_image)\n assert_array_almost_equal(y.sum(axis=1), np.ones(len(empty_image)))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_missing_labels_error(art_warning, tabular_batch):\n try:\n test_input = tabular_batch\n mixup = MixupTensorFlowV2(num_classes=10)\n\n exc_msg = \"Labels `y` cannot be None.\"\n with pytest.raises(ValueError, match=exc_msg):\n mixup(test_input)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_check_params(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = MixupTensorFlowV2(num_classes=0)\n\n with pytest.raises(ValueError):\n _ = MixupTensorFlowV2(num_classes=10, alpha=0)\n\n with pytest.raises(ValueError):\n _ = MixupTensorFlowV2(num_classes=10, alpha=-1)\n\n with pytest.raises(ValueError):\n _ = MixupTensorFlowV2(num_classes=10, num_mix=1)\n\n with pytest.raises(ValueError):\n _ = MixupTensorFlowV2(num_classes=10, num_mix=-1)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_adversarial_trainer_FBF.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport logging\nimport numpy as np\n\nfrom art.defences.trainer import AdversarialTrainerFBFPyTorch\n\n\n@pytest.fixture()\ndef get_adv_trainer(framework, image_dl_estimator):\n def _get_adv_trainer():\n\n if framework == \"keras\":\n trainer = None\n if framework == \"tensorflow\":\n trainer = None\n if framework in [\"pytorch\", \"huggingface\"]:\n classifier, _ = image_dl_estimator()\n trainer = AdversarialTrainerFBFPyTorch(classifier, eps=0.05)\n if framework == \"scikitlearn\":\n trainer = None\n\n return trainer\n\n return _get_adv_trainer\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 100\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\", \"huggingface\")\ndef test_adversarial_trainer_fbf_pytorch_fit_and_predict(get_adv_trainer, fix_get_mnist_subset):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n trainer = get_adv_trainer()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=20)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new == 0.63\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=20, validation_data=(x_train_mnist, y_train_mnist))\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"scikitlearn\", \"kerastf\", \"huggingface\")\ndef test_adversarial_trainer_fbf_pytorch_fit_generator_and_predict(\n get_adv_trainer, fix_get_mnist_subset, image_data_generator\n):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n generator = image_data_generator()\n\n trainer = get_adv_trainer()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n\n trainer.fit_generator(generator=generator, nb_epochs=20)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.2\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_adversarial_trainer_awp_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport logging\nimport numpy as np\n\nfrom art.defences.trainer import AdversarialTrainerAWPPyTorch\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\n@pytest.fixture()\ndef get_adv_trainer_awppgd(framework, image_dl_estimator):\n def _get_adv_trainer_awppgd():\n\n if framework == \"keras\":\n trainer = None\n if framework == \"tensorflow\":\n trainer = None\n if framework == \"pytorch\":\n classifier, _ = image_dl_estimator(from_logits=True)\n proxy_classifier, _ = image_dl_estimator(from_logits=True)\n attack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=0.2,\n eps_step=0.01,\n max_iter=20,\n targeted=False,\n num_random_init=1,\n batch_size=16,\n verbose=False,\n )\n trainer = AdversarialTrainerAWPPyTorch(\n classifier, proxy_classifier, attack, mode=\"PGD\", gamma=0.01, beta=6.0, warmup=0\n )\n if framework == \"scikitlearn\":\n trainer = None\n\n return trainer\n\n return _get_adv_trainer_awppgd\n\n\n@pytest.fixture()\ndef get_adv_trainer_awptrades(framework, image_dl_estimator):\n def _get_adv_trainer_awptrades():\n\n if framework == \"keras\":\n trainer = None\n if framework == \"tensorflow\":\n trainer = None\n if framework == \"pytorch\":\n classifier, _ = image_dl_estimator(from_logits=True)\n proxy_classifier, _ = image_dl_estimator(from_logits=True)\n attack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=0.1,\n eps_step=0.01,\n max_iter=5,\n targeted=False,\n num_random_init=0,\n batch_size=16,\n verbose=False,\n )\n trainer = AdversarialTrainerAWPPyTorch(\n classifier, proxy_classifier, attack, mode=\"TRADES\", gamma=0.01, beta=6.0, warmup=0\n )\n if framework == \"scikitlearn\":\n trainer = None\n\n return trainer\n\n return _get_adv_trainer_awptrades\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 100\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_awppgd_pytorch_fit_and_predict(get_adv_trainer_awppgd, fix_get_mnist_subset, label_format):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_train_mnist = np.argmax(y_train_mnist, axis=1)\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n trainer = get_adv_trainer_awppgd()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=40)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=5, validation_data=(x_train_mnist, y_train_mnist))\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_awptrades_pytorch_fit_and_predict(\n get_adv_trainer_awptrades, fix_get_mnist_subset, label_format\n):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_train_mnist = np.argmax(y_train_mnist, axis=1)\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n trainer = get_adv_trainer_awptrades()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=5)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=5, validation_data=(x_train_mnist, y_train_mnist))\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_awppgd_pytorch_fit_generator_and_predict(\n get_adv_trainer_awppgd, fix_get_mnist_subset, image_data_generator, label_format\n):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n generator = image_data_generator()\n\n trainer = get_adv_trainer_awppgd()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit_generator(generator=generator, nb_epochs=5)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit_generator(generator=generator, nb_epochs=2, validation_data=(x_train_mnist, y_train_mnist))\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_awptrades_pytorch_fit_generator_and_predict(\n get_adv_trainer_awptrades, fix_get_mnist_subset, image_data_generator, label_format\n):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n generator = image_data_generator()\n\n trainer = get_adv_trainer_awptrades()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit_generator(generator=generator, nb_epochs=5)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit_generator(generator=generator, nb_epochs=2, validation_data=(x_train_mnist, y_train_mnist))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_adversarial_trainer_madry_pgd.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.defences.trainer.adversarial_trainer_madry_pgd import AdversarialTrainerMadryPGD\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 100\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"huggingface\")\ndef test_fit_predict(art_warning, image_dl_estimator, fix_get_mnist_subset):\n classifier, _ = image_dl_estimator()\n\n (x_train, y_train, x_test, y_test) = fix_get_mnist_subset\n x_test_original = x_test.copy()\n\n adv_trainer = AdversarialTrainerMadryPGD(classifier, nb_epochs=1, batch_size=128)\n adv_trainer.fit(x_train, y_train)\n\n predictions_new = np.argmax(adv_trainer.trainer.get_classifier().predict(x_test), axis=1)\n accuracy_new = np.mean(predictions_new == np.argmax(y_test, axis=1))\n\n assert accuracy_new == pytest.approx(0.375, abs=0.05)\n # Check that x_test has not been modified by attack and classifier\n assert np.allclose(x_test_original, x_test)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"huggingface\")\ndef test_get_classifier(art_warning, image_dl_estimator):\n classifier, _ = image_dl_estimator()\n\n adv_trainer = AdversarialTrainerMadryPGD(classifier, nb_epochs=1, batch_size=128)\n _ = adv_trainer.get_classifier()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_adversarial_trainer_oaat_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport logging\nimport numpy as np\n\nfrom art.defences.trainer import AdversarialTrainerOAATPyTorch\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\n@pytest.fixture()\ndef get_adv_trainer_oaat(framework, image_dl_estimator):\n def _get_adv_trainer_oaat():\n\n if framework == \"keras\":\n trainer = None\n if framework == \"tensorflow\":\n trainer = None\n if framework == \"pytorch\":\n classifier, _ = image_dl_estimator(from_logits=True)\n proxy_classifier, _ = image_dl_estimator(from_logits=True)\n lpips_classifier, _ = image_dl_estimator(from_logits=True)\n list_avg_classifiers = [image_dl_estimator(from_logits=True)[0] for _ in range(3)]\n train_params = {\n \"weight_decay\": 0.0,\n \"lr\": 0.1,\n \"momentum\": 0.0,\n \"norm\": np.inf,\n \"i_epsilon\": 0.1,\n \"epsilon\": 0.2,\n \"alpha\": 1.0,\n \"beta\": 1.5,\n \"awp_gamma\": 0.005,\n \"awp_warmup\": 1,\n \"lr_schedule\": \"cosine\",\n \"beta_final\": 3.0,\n \"mixup_alpha\": 0.2,\n \"mixup_epsilon\": 0.25,\n \"lpips_weight\": 1.0,\n \"list_swa_tau\": [0.995, 0.9996, 0.9998],\n \"oaat_warmup\": 0,\n \"alternate_iter_eps\": 0.15,\n \"swa_save_epoch\": 0,\n \"list_swa_epoch\": [0, 15, 15],\n \"max_iter\": 5,\n \"models_path\": None,\n \"load_swa_model_tau\": 0.995,\n \"layer_names_activation\": [\"conv\"],\n }\n\n attack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=0.2,\n eps_step=0.01,\n max_iter=5,\n targeted=False,\n num_random_init=0,\n batch_size=16,\n verbose=False,\n )\n trainer = AdversarialTrainerOAATPyTorch(\n classifier, proxy_classifier, lpips_classifier, list_avg_classifiers, attack, train_params\n )\n if framework == \"scikitlearn\":\n trainer = None\n\n return trainer\n\n return _get_adv_trainer_oaat\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 100\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_oaat_pytorch_fit_and_predict(get_adv_trainer_oaat, fix_get_mnist_subset, label_format):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_train_mnist = np.argmax(y_train_mnist, axis=1)\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n trainer = get_adv_trainer_oaat()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=10, batch_size=16)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit(\n x_train_mnist, y_train_mnist, nb_epochs=2, validation_data=(x_train_mnist, y_train_mnist), batch_size=16\n )\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_oaat_pytorch_fit_generator_and_predict(\n get_adv_trainer_oaat, fix_get_mnist_subset, image_data_generator, label_format\n):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n generator = image_data_generator()\n\n trainer = get_adv_trainer_oaat()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit_generator(generator=generator, nb_epochs=10)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit_generator(generator=generator, nb_epochs=2, validation_data=(x_train_mnist, y_train_mnist))\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_adversarial_trainer_trades_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport logging\nimport numpy as np\n\nfrom art.defences.trainer import AdversarialTrainerTRADESPyTorch\nfrom art.attacks.evasion import ProjectedGradientDescent\n\n\n@pytest.fixture()\ndef get_adv_trainer(framework, image_dl_estimator):\n def _get_adv_trainer():\n\n if framework == \"keras\":\n trainer = None\n if framework == \"tensorflow\":\n trainer = None\n if framework == \"pytorch\":\n classifier, _ = image_dl_estimator(from_logits=True)\n attack = ProjectedGradientDescent(\n classifier,\n norm=np.inf,\n eps=0.3,\n eps_step=0.03,\n max_iter=5,\n targeted=False,\n num_random_init=1,\n batch_size=128,\n verbose=False,\n )\n trainer = AdversarialTrainerTRADESPyTorch(classifier, attack, beta=6.0)\n\n if framework in [\"huggingface\", \"scikitlearn\"]:\n trainer = None\n\n return trainer\n\n return _get_adv_trainer\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 100\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_trades_pytorch_fit_and_predict(get_adv_trainer, fix_get_mnist_subset, label_format):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n y_train_mnist = np.argmax(y_train_mnist, axis=1)\n\n trainer = get_adv_trainer()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=5)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n trainer.fit(x_train_mnist, y_train_mnist, nb_epochs=2, validation_data=(x_train_mnist, y_train_mnist))\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"label_format\", [\"one_hot\", \"numerical\"])\ndef test_adversarial_trainer_trades_pytorch_fit_generator_and_predict(\n get_adv_trainer, fix_get_mnist_subset, image_data_generator, label_format\n):\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n x_test_mnist_original = x_test_mnist.copy()\n\n if label_format == \"one_hot\":\n assert y_train_mnist.shape[-1] == 10\n assert y_test_mnist.shape[-1] == 10\n if label_format == \"numerical\":\n y_test_mnist = np.argmax(y_test_mnist, axis=1)\n\n generator = image_data_generator()\n\n trainer = get_adv_trainer()\n if trainer is None:\n logging.warning(\"Couldn't perform this test because no trainer is defined for this framework configuration\")\n return\n\n predictions = np.argmax(trainer.predict(x_test_mnist), axis=1)\n if label_format == \"one_hot\":\n accuracy = np.sum(predictions == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy = np.sum(predictions == y_test_mnist) / x_test_mnist.shape[0]\n\n trainer.fit_generator(generator=generator, nb_epochs=5)\n predictions_new = np.argmax(trainer.predict(x_test_mnist), axis=1)\n\n if label_format == \"one_hot\":\n accuracy_new = np.sum(predictions_new == np.argmax(y_test_mnist, axis=1)) / x_test_mnist.shape[0]\n else:\n accuracy_new = np.sum(predictions_new == y_test_mnist) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(\n float(np.mean(x_test_mnist_original - x_test_mnist)),\n 0.0,\n decimal=4,\n )\n\n assert accuracy == 0.32\n assert accuracy_new > 0.32\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_certified_adversarial_trainer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\nimport numpy as np\nimport random\nimport torch\n\nfrom art.utils import load_dataset\nfrom art.estimators.certification.deep_z import PytorchDeepZ\nfrom art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\nfrom art.defences.trainer import AdversarialTrainerCertifiedPytorch\n\nfrom tests.utils import ARTTestException\nfrom tests.utils import get_image_classifier_pt, get_cifar10_image_classifier_pt\n\n\n@pytest.fixture()\ndef fix_get_mnist_data():\n \"\"\"\n Get the first 100 samples of the mnist test set with channels first format\n\n :return: First 100 sample/label pairs of the MNIST test dataset.\n \"\"\"\n nb_test = 100\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_test = np.squeeze(x_test)\n x_test = np.expand_dims(x_test, axis=1)\n y_test = np.argmax(y_test, axis=1)\n\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n\n return x_test.astype(np.float32), y_test\n\n\n@pytest.fixture()\ndef fix_get_cifar10_data():\n \"\"\"\n Get the first 10 samples of the cifar10 test set\n\n :return: First 10 sample/label pairs of the cifar10 test dataset.\n \"\"\"\n nb_test = 10\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"cifar10\")\n y_test = np.argmax(y_test, axis=1)\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n return np.moveaxis(x_test, [3], [1]).astype(np.float32), y_test\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\", \"huggingface\")\ndef test_mnist_certified_training(art_warning, fix_get_mnist_data):\n \"\"\"\n Check the following properties for the first 100 samples of the MNIST test set given an l_inf bound\n 1) Check regular loss\n 2) Train the model for 3 epochs using certified training.\n 3) Re-Check regular loss\n \"\"\"\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n import torch.optim as optim\n\n optimizer = optim.Adam(ptc.model.parameters(), lr=1e-4)\n zonotope_model = PytorchDeepZ(\n model=ptc.model.to(device),\n optimizer=optimizer,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n pgd_params = {\"eps\": 0.25, \"eps_step\": 0.05, \"max_iter\": 20, \"num_random_init\": 0, \"batch_size\": 64}\n\n trainer = AdversarialTrainerCertifiedPytorch(zonotope_model, pgd_params=pgd_params, batch_size=10, bound=0.1)\n\n np.random.seed(123)\n random.seed(123)\n torch.manual_seed(123)\n try:\n # Check losses pre-training\n trainer._classifier.model.set_forward_mode(\"concrete\")\n prediction = trainer._classifier.model.forward(fix_get_mnist_data[0])\n loss = trainer._classifier.concrete_loss(prediction, torch.tensor(fix_get_mnist_data[1]).to(device))\n assert round(float(loss.cpu().detach().numpy()), 3) == 0.095\n\n trainer.fit(fix_get_mnist_data[0], fix_get_mnist_data[1], nb_epochs=3)\n\n # Check losses post-training\n prediction = trainer._classifier.model.forward(fix_get_mnist_data[0])\n loss = trainer._classifier.concrete_loss(prediction, torch.tensor(fix_get_mnist_data[1]).to(device))\n assert round(float(loss.cpu().detach().numpy()), 3) == 0.092\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\", \"huggingface\")\ndef test_mnist_certified_loss(art_warning, fix_get_mnist_data):\n \"\"\"\n Check the certified losses with interval_loss_cce, max_logit_loss, and make sure that we give a lower\n bound compared to PGD.\n \"\"\"\n bound = 0.05\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n import torch.optim as optim\n\n optimizer = optim.Adam(ptc.model.parameters(), lr=1e-4)\n zonotope_model = PytorchDeepZ(\n model=ptc.model.to(device),\n optimizer=optimizer,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n pgd_params = {\"eps\": 0.25, \"eps_step\": 0.05, \"max_iter\": 20, \"num_random_init\": 0, \"batch_size\": 64}\n\n trainer = AdversarialTrainerCertifiedPytorch(zonotope_model, pgd_params=pgd_params, batch_size=10, bound=bound)\n\n np.random.seed(123)\n random.seed(123)\n torch.manual_seed(123)\n concrete_correct = 0\n samples_x, samples_eps = trainer.predict_zonotopes(np.copy(fix_get_mnist_data[0]), bound)\n try:\n certified_loss = 0\n for i, (x, y) in enumerate(zip(fix_get_mnist_data[0], fix_get_mnist_data[1])):\n x = x.astype(\"float32\")\n pred_sample = np.copy(x)\n pred_sample = np.expand_dims(pred_sample, axis=0)\n zonotope_model.model.set_forward_mode(\"concrete\")\n prediction = trainer._classifier.model.forward(torch.from_numpy(pred_sample.astype(\"float32\")).to(device))\n if np.argmax(prediction.cpu().detach().numpy()) == y:\n concrete_correct += 1\n\n eps_bound = np.eye(784) * bound\n zonotope_model.model.set_forward_mode(\"abstract\")\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=x, eps=eps_bound)\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n bias, eps_bound = trainer._classifier.model.forward(eps=eps_bound, cent=data_sample_processed)\n bias = torch.unsqueeze(bias, dim=0)\n\n assert np.allclose(samples_x[i], bias.cpu().detach().numpy())\n assert np.allclose(samples_eps[i], eps_bound.cpu().detach().numpy())\n\n certified_loss += trainer._classifier.interval_loss_cce(\n prediction=torch.cat((bias, eps_bound)),\n target=torch.from_numpy(np.expand_dims(y, axis=0)).to(device),\n )\n\n assert round(float(certified_loss.cpu().detach().numpy()), 4) == 39.7759\n\n samples_certified = 0\n\n certified_loss = 0\n for x, y in zip(fix_get_mnist_data[0], fix_get_mnist_data[1]):\n x = x.astype(\"float32\")\n pred_sample = np.copy(x)\n pred_sample = np.expand_dims(pred_sample, axis=0)\n zonotope_model.model.set_forward_mode(\"concrete\")\n prediction = trainer._classifier.model.forward(torch.from_numpy(pred_sample.astype(\"float32\")).to(device))\n if np.argmax(prediction.cpu().detach().numpy()) == y:\n concrete_correct += 1\n\n eps_bound = np.eye(784) * bound\n zonotope_model.model.set_forward_mode(\"abstract\")\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=np.copy(x), eps=eps_bound)\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n bias, eps_bound = trainer._classifier.model.forward(eps=eps_bound, cent=data_sample_processed)\n bias = torch.unsqueeze(bias, dim=0)\n\n sample_loss = trainer._classifier.max_logit_loss(\n prediction=torch.cat((bias, eps_bound)),\n target=torch.from_numpy(np.expand_dims(y, axis=0)).to(device),\n )\n\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=np.copy(x), eps=np.eye(784) * bound)\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n is_certified = zonotope_model.certify(\n eps=eps_bound, cent=data_sample_processed, prediction=np.argmax(prediction.cpu().detach().numpy())\n )\n\n if (\n is_certified and int(np.argmax(prediction.cpu().detach().numpy())) == y\n ): # if it is classified correctly AND is certified\n assert sample_loss <= 0.0 # ...the max_logit_loss gives negatve.\n samples_certified += 1\n\n certified_loss += sample_loss\n\n assert float(certified_loss.cpu().detach().numpy()) == pytest.approx(-309.2724, abs=0.001)\n assert samples_certified == 94\n\n # empirically check that PGD does not give a lower acc\n zonotope_model.model.set_forward_mode(\"concrete\")\n attack = ProjectedGradientDescent(\n estimator=trainer._classifier,\n eps=bound,\n eps_step=bound / 20,\n max_iter=30,\n num_random_init=0,\n )\n i_batch = attack.generate(fix_get_mnist_data[0], y=fix_get_mnist_data[1])\n preds = trainer._classifier.model.forward(i_batch)\n preds = preds.cpu().detach().numpy()\n acc = np.sum(np.argmax(preds, axis=1) == fix_get_mnist_data[1]) / len(fix_get_mnist_data[1])\n assert acc * 100 >= samples_certified\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\", \"huggingface\")\ndef test_cifar_certified_training(art_warning, fix_get_cifar10_data):\n \"\"\"\n Check the following properties for the first 10 samples of the CIFAR test set given an l_inf bound\n 1) Check regular loss\n 2) Train the model for 3 epochs using certified training.\n 3) Re-Check regular loss\n \"\"\"\n\n bound = 0.01\n\n ptc = get_cifar10_image_classifier_pt(from_logits=True)\n\n import torch.optim as optim\n\n optimizer = optim.Adam(ptc.model.parameters(), lr=1e-4)\n zonotope_model = PytorchDeepZ(\n model=ptc.model,\n optimizer=optimizer,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n input_shape=(3, 32, 32),\n nb_classes=10,\n )\n\n pgd_params = {\"eps\": 8 / 255, \"eps_step\": 1 / 255, \"max_iter\": 20, \"num_random_init\": 0, \"batch_size\": 64}\n\n trainer = AdversarialTrainerCertifiedPytorch(zonotope_model, pgd_params=pgd_params, batch_size=10, bound=bound)\n\n np.random.seed(123)\n random.seed(123)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n try:\n trainer._classifier.model.set_forward_mode(\"concrete\")\n prediction = trainer._classifier.model.forward(fix_get_cifar10_data[0])\n loss = trainer._classifier.concrete_loss(prediction, torch.tensor(fix_get_cifar10_data[1]).to(device))\n assert round(float(loss.cpu().detach().numpy()), 4) == 1.0611\n\n trainer.fit(fix_get_cifar10_data[0], fix_get_cifar10_data[1], nb_epochs=3)\n prediction = trainer._classifier.model.forward(fix_get_cifar10_data[0])\n\n loss = trainer._classifier.concrete_loss(prediction, torch.tensor(fix_get_cifar10_data[1]).to(device))\n assert round(float(loss.cpu().detach().numpy()), 4) == 1.0092\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\", \"huggingface\")\ndef test_cifar_certified_loss(art_warning, fix_get_cifar10_data):\n \"\"\"\n Check the certified losses with interval_loss_cce, max_logit_loss, and make sure that we give a lower\n bound compared to PGD.\n \"\"\"\n bound = 2 / 255\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_cifar10_image_classifier_pt(from_logits=True)\n\n import torch.optim as optim\n\n optimizer = optim.Adam(ptc.model.parameters(), lr=1e-4)\n zonotope_model = PytorchDeepZ(\n model=ptc.model,\n optimizer=optimizer,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n input_shape=(3, 32, 32),\n nb_classes=10,\n )\n\n pgd_params = {\"eps\": 8 / 255, \"eps_step\": 1 / 255, \"max_iter\": 20, \"num_random_init\": 0, \"batch_size\": 64}\n\n trainer = AdversarialTrainerCertifiedPytorch(zonotope_model, pgd_params=pgd_params, batch_size=10, bound=bound)\n\n np.random.seed(123)\n random.seed(123)\n torch.manual_seed(123)\n concrete_correct = 0\n samples_x, samples_eps = trainer.predict_zonotopes(np.copy(fix_get_cifar10_data[0]), bound)\n try:\n certified_loss = 0\n for x, y in zip(fix_get_cifar10_data[0], fix_get_cifar10_data[1]):\n x = x.astype(\"float32\")\n pred_sample = np.copy(x)\n pred_sample = np.expand_dims(pred_sample, axis=0)\n zonotope_model.model.set_forward_mode(\"concrete\")\n prediction = trainer._classifier.model.forward(torch.from_numpy(pred_sample.astype(\"float32\")).to(device))\n if np.argmax(prediction.cpu().detach().numpy()) == y:\n concrete_correct += 1\n\n eps_bound = np.eye(3 * 32 * 32) * bound\n zonotope_model.model.set_forward_mode(\"abstract\")\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=x, eps=eps_bound)\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n bias, eps_bound = trainer._classifier.model.forward(eps=eps_bound, cent=data_sample_processed)\n bias = torch.unsqueeze(bias, dim=0)\n\n certified_loss += trainer._classifier.interval_loss_cce(\n prediction=torch.cat((bias, eps_bound)),\n target=torch.from_numpy(np.expand_dims(y, axis=0)).to(device),\n )\n\n certified_loss = certified_loss.cpu().detach().numpy()\n assert round(float(certified_loss), 4) == 16.5492\n\n samples_certified = 0\n\n certified_loss = 0\n for i, (x, y) in enumerate(zip(fix_get_cifar10_data[0], fix_get_cifar10_data[1])):\n x = x.astype(\"float32\")\n pred_sample = np.copy(x)\n pred_sample = np.expand_dims(pred_sample, axis=0)\n zonotope_model.model.set_forward_mode(\"concrete\")\n prediction = trainer._classifier.model.forward(torch.from_numpy(pred_sample.astype(\"float32\")).to(device))\n if np.argmax(prediction.cpu().detach().numpy()) == y:\n concrete_correct += 1\n\n eps_bound = np.eye(3 * 32 * 32) * bound\n zonotope_model.model.set_forward_mode(\"abstract\")\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=np.copy(x), eps=eps_bound)\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n bias, eps_bound = trainer._classifier.model.forward(eps=eps_bound, cent=data_sample_processed)\n bias = torch.unsqueeze(bias, dim=0)\n\n assert np.allclose(samples_x[i], bias.cpu().detach().numpy())\n assert np.allclose(samples_eps[i], eps_bound.cpu().detach().numpy())\n\n sample_loss = trainer._classifier.max_logit_loss(\n prediction=torch.cat((bias, eps_bound)),\n target=torch.from_numpy(np.expand_dims(y, axis=0)).to(device),\n )\n\n data_sample_processed, eps_bound = zonotope_model.pre_process(\n cent=np.copy(x), eps=np.eye(3 * 32 * 32) * bound\n )\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n is_certified = zonotope_model.certify(\n eps=eps_bound, cent=data_sample_processed, prediction=np.argmax(prediction.cpu().detach().numpy())\n )\n\n if (\n is_certified and int(np.argmax(prediction.cpu().detach().numpy())) == y\n ): # if it is classified correctly AND is certified\n assert sample_loss <= 0.0 # ...the max_logit_loss gives negatve.\n samples_certified += 1\n\n certified_loss += sample_loss\n\n assert round(float(certified_loss.cpu().detach().numpy()), 4) == 1.6515\n assert samples_certified == 6\n\n # empirically check that PGD does not give a lower acc\n zonotope_model.model.set_forward_mode(\"concrete\")\n attack = ProjectedGradientDescent(\n estimator=trainer._classifier,\n eps=bound,\n eps_step=bound / 20,\n max_iter=30,\n num_random_init=0,\n )\n i_batch = attack.generate(fix_get_cifar10_data[0], y=fix_get_cifar10_data[1])\n preds = trainer._classifier.model.forward(i_batch)\n preds = preds.cpu().detach().numpy()\n acc = np.sum(np.argmax(preds, axis=1) == fix_get_cifar10_data[1]) / len(fix_get_cifar10_data[1])\n assert acc * 100 >= samples_certified\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/trainer/test_dp_instahide_trainer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\nimport logging\n\nfrom art.defences.preprocessor import Mixup, Cutout\nfrom art.defences.trainer import DPInstaHideTrainer\nfrom art.estimators.classification import PyTorchClassifier, TensorFlowV2Classifier, KerasClassifier\nfrom tests.utils import ARTTestException\nfrom tests.utils import get_image_classifier_hf\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_mnist_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n import torch\n\n model = torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=7),\n torch.nn.ReLU(),\n torch.nn.MaxPool2d(4, 4),\n torch.nn.Flatten(),\n torch.nn.Linear(25, 10),\n )\n criterion = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n classifier = PyTorchClassifier(\n model,\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n elif framework == \"tensorflow2\":\n import tensorflow as tf\n from tensorflow.keras import layers, Sequential\n\n model = Sequential()\n model.add(layers.Conv2D(1, kernel_size=(7, 7), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(layers.MaxPooling2D(pool_size=(4, 4)))\n model.add(layers.Flatten())\n model.add(layers.Dense(10))\n\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)\n\n classifier = TensorFlowV2Classifier(\n model, nb_classes=10, input_shape=(28, 28, 1), loss_object=loss_object, optimizer=optimizer\n )\n\n elif framework in (\"keras\", \"kerastf\"):\n import tensorflow as tf\n from tensorflow.keras import layers, Sequential\n\n model = Sequential()\n model.add(layers.Conv2D(1, kernel_size=(7, 7), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(layers.MaxPooling2D(pool_size=(4, 4)))\n model.add(layers.Flatten())\n model.add(layers.Dense(10))\n model.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\")\n classifier = KerasClassifier(model, clip_values=(0, 1), use_logits=True)\n\n elif framework == \"huggingface\":\n classifier = get_image_classifier_hf(from_logits=True)\n\n else:\n classifier = None\n\n return classifier\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\", \"huggingface\")\n@pytest.mark.parametrize(\"noise\", [\"gaussian\", \"laplacian\", \"exponential\"])\ndef test_dp_instahide_single_aug(\n art_warning, get_mnist_classifier, get_default_mnist_subset, get_default_cifar10_subset, noise, framework\n):\n classifier = get_mnist_classifier()\n\n (x_train, y_train), (_, _) = get_default_mnist_subset\n\n mixup = Mixup(num_classes=10)\n\n try:\n trainer = DPInstaHideTrainer(classifier, augmentations=mixup, noise=noise, loc=0, scale=0.1)\n trainer.fit(x_train, y_train, nb_epochs=1)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\", \"huggingface\")\n@pytest.mark.parametrize(\"noise\", [\"gaussian\", \"laplacian\", \"exponential\"])\ndef test_dp_instahide_multiple_aug(\n art_warning, get_mnist_classifier, get_default_mnist_subset, get_default_cifar10_subset, noise, framework\n):\n classifier = get_mnist_classifier()\n\n (x_train, y_train), (_, _) = get_default_mnist_subset\n\n mixup = Mixup(num_classes=10)\n cutout = Cutout(length=8, channels_first=False)\n\n try:\n trainer = DPInstaHideTrainer(classifier, augmentations=[mixup, cutout], noise=noise, loc=0, scale=0.1)\n trainer.fit(x_train, y_train, nb_epochs=1)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\", \"huggingface\")\n@pytest.mark.parametrize(\"noise\", [\"gaussian\", \"laplacian\", \"exponential\"])\ndef test_dp_instahide_validation_data(\n art_warning, get_mnist_classifier, get_default_mnist_subset, get_default_cifar10_subset, noise, framework\n):\n classifier = get_mnist_classifier()\n\n (x_train, y_train), (x_test, y_test) = get_default_mnist_subset\n mixup = Mixup(num_classes=10)\n\n try:\n trainer = DPInstaHideTrainer(classifier, augmentations=mixup, noise=noise, loc=0, scale=0.1)\n trainer.fit(x_train, y_train, validation_data=(x_test, y_test), nb_epochs=1)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\", \"huggingface\")\n@pytest.mark.parametrize(\"noise\", [\"gaussian\", \"laplacian\", \"exponential\"])\ndef test_dp_instahide_generator(\n art_warning, get_mnist_classifier, get_default_mnist_subset, get_default_cifar10_subset, noise, framework\n):\n from art.data_generators import NumpyDataGenerator\n\n classifier = get_mnist_classifier()\n\n (x_train, y_train), (_, _) = get_default_mnist_subset\n\n mixup = Mixup(num_classes=10)\n generator = NumpyDataGenerator(x_train, y_train, batch_size=len(x_train))\n\n try:\n trainer = DPInstaHideTrainer(classifier, augmentations=mixup, noise=noise, loc=0, scale=0.1)\n trainer.fit_generator(generator, nb_epochs=1)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/defences/transformer/poisoning/test_strip.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\n\nfrom art.defences.transformer.poisoning import STRIP\nfrom art.estimators.classification import TensorFlowV2Classifier\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\ndef test_strip(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator()\n\n classifier.fit(x_train_mnist, y_train_mnist, nb_epochs=1)\n strip = STRIP(classifier)\n defense_cleanse = strip()\n defense_cleanse.mitigate(x_test_mnist)\n defense_cleanse.predict(x_test_mnist)\n stripped_classifier = strip.get_classifier()\n stripped_classifier._check_params()\n assert isinstance(stripped_classifier, TensorFlowV2Classifier)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_deepz.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport json\nimport os\nimport pytest\n\nimport numpy as np\nimport torch\n\nfrom art.utils import load_dataset\nfrom art.estimators.certification.deep_z import PytorchDeepZ\nfrom tests.utils import ARTTestException\nfrom tests.utils import get_image_classifier_pt, get_cifar10_image_classifier_pt\n\n\n@pytest.fixture()\ndef fix_get_mnist_data():\n \"\"\"\n Get the first 100 samples of the mnist test set with channels first format.\n :return: First 100 sample/label pairs of the MNIST test dataset.\n \"\"\"\n nb_test = 100\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_test = np.squeeze(x_test)\n x_test = np.expand_dims(x_test, axis=1)\n y_test = np.argmax(y_test, axis=1)\n\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n\n return x_test, y_test\n\n\n@pytest.fixture()\ndef fix_get_cifar10_data():\n \"\"\"\n Get the first 10 samples of the cifar10 test set\n :return: First 10 sample/label pairs of the cifar10 test dataset.\n \"\"\"\n nb_test = 10\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"cifar10\")\n y_test = np.argmax(y_test, axis=1)\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n return x_test, y_test\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_mnist_certification(art_warning, fix_get_mnist_data):\n \"\"\"\n Check the following properties for the first 100 samples of the MNIST test set given an l_inf bound of 0.05.\n 1) Upper and lower bounds are calculated correctly.\n 2) The correct number of datapoints are certified.\n 3) The standard accuracy is correct.\n \"\"\"\n bound = 0.05\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n\n zonotope_model = PytorchDeepZ(\n model=ptc.model, clip_values=(0, 1), loss=torch.nn.CrossEntropyLoss(), input_shape=(1, 28, 28), nb_classes=10\n )\n\n correct_upper_bounds = np.asarray(\n json.load(\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"certification/output_results/mini_nets/mnist_ub_results_0.05.json\",\n )\n )\n )\n )\n correct_lower_bounds = np.asarray(\n json.load(\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"certification/output_results/mini_nets/mnist_lb_results_0.05.json\",\n )\n )\n )\n )\n\n num_cert = 0\n correct = 0\n try:\n for x, y in zip(fix_get_mnist_data[0], fix_get_mnist_data[1]):\n x = x.astype(\"float32\")\n eps_bound = np.eye(784) * bound\n pred_sample = np.copy(x)\n pred_sample = np.expand_dims(pred_sample, axis=0)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n pred_sample = torch.from_numpy(pred_sample.astype(\"float32\")).to(device)\n zonotope_model.model.set_forward_mode(\"concrete\")\n prediction = zonotope_model.model.forward(pred_sample)\n prediction = np.argmax(prediction.cpu().detach().numpy())\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=x, eps=eps_bound)\n\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n zonotope_model.model.set_forward_mode(\"abstract\")\n\n bias, eps = zonotope_model.model.forward(eps=eps_bound, cent=data_sample_processed)\n\n upper_bounds, lower_bounds = zonotope_model.zonotope_get_bounds(bias, eps)\n if prediction == y:\n for bnds, correct_bds in zip(\n [upper_bounds, lower_bounds], [correct_upper_bounds[correct], correct_lower_bounds[correct]]\n ):\n bnds = torch.stack(bnds)\n bnds = bnds.detach().cpu().numpy()\n assert np.allclose(bnds, correct_bds, rtol=1e-05, atol=1e-05)\n\n correct += 1\n\n bias = bias.detach().cpu().numpy()\n eps = eps.detach().cpu().numpy()\n\n certified = True\n sub_certs = []\n min_bound_on_class = lower_bounds[y]\n\n for k in range(10):\n if k != prediction:\n cert_via_sub = zonotope_model.certify_via_subtraction(\n predicted_class=prediction, class_to_consider=k, cent=bias, eps=eps\n )\n sub_certs.append(cert_via_sub)\n\n if min_bound_on_class <= upper_bounds[k]:\n certified = False\n\n if certified: # if box certified then subtract must also certify\n assert all(sub_certs)\n\n # make sure the certify method gives the same result\n is_certified = zonotope_model.certify(eps=eps_bound, cent=data_sample_processed, prediction=prediction)\n assert is_certified == all(sub_certs)\n\n if all(sub_certs) and int(prediction) == y:\n num_cert += 1\n\n assert num_cert == 94\n assert correct == 99\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_cifar_certification(art_warning, fix_get_cifar10_data):\n \"\"\"\n Check the following properties for the first 100 samples of the CIFAR10 test set given an l_inf bound of 0.004.\n 1) Upper and lower bounds are calculated correctly.\n 2) The correct number of datapoints are certified.\n 3) The standard accuracy is correct.\n \"\"\"\n bound = 0.004\n\n ptc = get_cifar10_image_classifier_pt(from_logits=True)\n zonotope_model = PytorchDeepZ(\n model=ptc.model, clip_values=(0, 1), loss=torch.nn.CrossEntropyLoss(), input_shape=(3, 32, 32), nb_classes=10\n )\n\n correct_upper_bounds = np.asarray(\n json.load(\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"certification/output_results/mini_nets/cifar10_ub_results_0.004.json\",\n )\n )\n )\n )\n correct_lower_bounds = np.asarray(\n json.load(\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"certification/output_results/mini_nets/cifar10_lb_results_0.004.json\",\n )\n )\n )\n )\n\n num_cert = 0\n correct = 0\n try:\n for x, y in zip(fix_get_cifar10_data[0], fix_get_cifar10_data[1]):\n x = x.astype(\"float32\")\n eps_bound = np.eye(3 * 32 * 32) * bound\n x = np.moveaxis(x, [2], [0])\n pred_sample = np.copy(x)\n pred_sample = np.expand_dims(pred_sample, axis=0)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n pred_sample = torch.from_numpy(pred_sample.astype(\"float32\")).to(device)\n zonotope_model.model.set_forward_mode(\"concrete\")\n prediction = zonotope_model.model.forward(pred_sample)\n prediction = np.argmax(prediction.cpu().detach().numpy())\n data_sample_processed, eps_bound = zonotope_model.pre_process(cent=x, eps=eps_bound)\n\n data_sample_processed = np.expand_dims(data_sample_processed, axis=0)\n zonotope_model.model.set_forward_mode(\"abstract\")\n bias, eps_bound = zonotope_model.model.forward(eps=eps_bound, cent=data_sample_processed)\n\n upper_bounds, lower_bounds = zonotope_model.zonotope_get_bounds(bias, eps_bound)\n if prediction == y:\n for bnds, correct_bds in zip(\n [upper_bounds, lower_bounds], [correct_upper_bounds[correct], correct_lower_bounds[correct]]\n ):\n bnds = torch.stack(bnds)\n bnds = bnds.detach().cpu().numpy()\n assert np.allclose(bnds, correct_bds, rtol=1e-05, atol=1e-05)\n correct += 1\n\n bias = bias.detach().cpu().numpy()\n eps_bound = eps_bound.detach().cpu().numpy()\n\n certified = True\n sub_certs = []\n min_bound_on_class = lower_bounds[y]\n\n for k in range(10):\n if k != prediction:\n cert_via_sub = zonotope_model.certify_via_subtraction(\n predicted_class=prediction, class_to_consider=k, cent=bias, eps=eps_bound\n )\n sub_certs.append(cert_via_sub)\n\n if min_bound_on_class <= upper_bounds[k]:\n certified = False\n\n if certified: # if box certified then subtract must also certify\n assert all(sub_certs)\n\n if all(sub_certs) and int(prediction) == y:\n num_cert += 1\n\n assert num_cert == 7\n assert correct == 8\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_derandomized_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport pytest\n\nimport numpy as np\n\nfrom art.utils import load_dataset\nfrom art.estimators.certification.derandomized_smoothing import (\n PyTorchDeRandomizedSmoothing,\n TensorFlowV2DeRandomizedSmoothing,\n)\nfrom tests.utils import ARTTestException\n\n\n@pytest.fixture()\ndef fix_get_mnist_data():\n \"\"\"\n Get the first 128 samples of the mnist test set with channels first format\n\n :return: First 128 sample/label pairs of the MNIST test dataset.\n \"\"\"\n nb_test = 128\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_test = np.squeeze(x_test).astype(np.float32)\n x_test = np.expand_dims(x_test, axis=1)\n y_test = np.argmax(y_test, axis=1)\n\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n return x_test, y_test\n\n\n@pytest.fixture()\ndef fix_get_cifar10_data():\n \"\"\"\n Get the first 128 samples of the cifar10 test set\n\n :return: First 128 sample/label pairs of the cifar10 test dataset.\n \"\"\"\n nb_test = 128\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"cifar10\")\n y_test = np.argmax(y_test, axis=1)\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n x_test = np.transpose(x_test, (0, 3, 1, 2)) # return in channels first format\n return x_test.astype(np.float32), y_test\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_pytorch_training(art_warning, fix_get_mnist_data, fix_get_cifar10_data):\n \"\"\"\n Check that the training loop for pytorch does not result in errors\n \"\"\"\n import torch\n import torch.optim as optim\n import torch.nn as nn\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n class SmallMNISTModel(nn.Module):\n def __init__(self):\n super(SmallMNISTModel, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=2, out_channels=32, kernel_size=(4, 4), dilation=(1, 1), stride=(2, 2))\n self.max_pool = nn.MaxPool2d(2, stride=2)\n self.fc1 = nn.Linear(in_features=1152, out_features=100)\n\n self.fc2 = nn.Linear(in_features=100, out_features=10)\n\n self.relu = nn.ReLU()\n\n def forward(self, x):\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(device)\n x = self.relu(self.conv1(x))\n x = self.max_pool(x)\n x = torch.flatten(x, 1)\n x = self.relu(self.fc1(x))\n return self.fc2(x)\n\n class SmallCIFARModel(nn.Module):\n def __init__(self):\n super(SmallCIFARModel, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=6, out_channels=32, kernel_size=(4, 4), dilation=(1, 1), stride=(2, 2))\n self.max_pool = nn.MaxPool2d(2, stride=2)\n self.fc1 = nn.Linear(in_features=1568, out_features=100)\n\n self.fc2 = nn.Linear(in_features=100, out_features=10)\n\n self.relu = nn.ReLU()\n\n def forward(self, x):\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(device)\n x = self.relu(self.conv1(x))\n x = self.max_pool(x)\n x = torch.flatten(x, 1)\n x = self.relu(self.fc1(x))\n return self.fc2(x)\n\n for dataset, dataset_name in zip([fix_get_mnist_data, fix_get_cifar10_data], [\"mnist\", \"cifar\"]):\n if dataset_name == \"mnist\":\n ptc = SmallMNISTModel().to(device)\n input_shape = (1, 28, 28)\n else:\n ptc = SmallCIFARModel().to(device)\n input_shape = (3, 32, 32)\n\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(ptc.parameters(), lr=0.01, momentum=0.9)\n try:\n for ablation_type in [\"column\", \"row\", \"block\"]:\n classifier = PyTorchDeRandomizedSmoothing(\n model=ptc,\n clip_values=(0, 1),\n loss=criterion,\n optimizer=optimizer,\n input_shape=input_shape,\n nb_classes=10,\n ablation_type=ablation_type,\n ablation_size=5,\n threshold=0.3,\n algorithm=\"levine2020\",\n logits=True,\n )\n classifier.fit(x=dataset[0], y=dataset[1], nb_epochs=1)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"pytorch\")\ndef test_tf2_training(art_warning, fix_get_mnist_data, fix_get_cifar10_data):\n \"\"\"\n Check that the training loop for tensorflow2 does not result in errors\n \"\"\"\n import tensorflow as tf\n\n def build_model(input_shape):\n img_inputs = tf.keras.Input(shape=(input_shape[0], input_shape[1], input_shape[2] * 2))\n x = tf.keras.layers.Conv2D(filters=32, kernel_size=(4, 4), strides=(2, 2), activation=\"relu\")(img_inputs)\n x = tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=2)(x)\n # tensorflow uses channels last, and we are loading weights from an originally trained pytorch model\n x = tf.keras.layers.Permute((3, 1, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n x = tf.keras.layers.Dense(100, activation=\"relu\")(x)\n x = tf.keras.layers.Dense(10)(x)\n return tf.keras.Model(inputs=img_inputs, outputs=x)\n\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)\n\n for dataset, dataset_name in zip([fix_get_mnist_data, fix_get_cifar10_data], [\"mnist\", \"cifar\"]):\n if dataset_name == \"mnist\":\n input_shape = (28, 28, 1)\n else:\n input_shape = (32, 32, 3)\n net = build_model(input_shape=input_shape)\n\n try:\n for ablation_type in [\"column\", \"row\", \"block\"]:\n ablation_size = 5\n classifier = TensorFlowV2DeRandomizedSmoothing(\n model=net,\n clip_values=(0, 1),\n loss_object=loss_object,\n optimizer=optimizer,\n input_shape=input_shape,\n nb_classes=10,\n ablation_type=ablation_type,\n ablation_size=ablation_size,\n threshold=0.3,\n logits=True,\n )\n x = np.transpose(np.copy(dataset[0]), (0, 2, 3, 1)) # put channels last\n classifier.fit(x=x, y=dataset[1], nb_epochs=1)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_pytorch_mnist_certification(art_warning, fix_get_mnist_data):\n \"\"\"\n Assert that the correct number of certifications are given for the MNIST dataset\n \"\"\"\n import torch\n import torch.optim as optim\n import torch.nn as nn\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n class SmallMNISTModel(nn.Module):\n def __init__(self):\n super(SmallMNISTModel, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=2, out_channels=32, kernel_size=(4, 4), dilation=(1, 1), stride=(2, 2))\n self.max_pool = nn.MaxPool2d(2, stride=2)\n self.fc1 = nn.Linear(in_features=1152, out_features=100)\n\n self.fc2 = nn.Linear(in_features=100, out_features=10)\n\n self.relu = nn.ReLU()\n\n def forward(self, x):\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(device)\n x = self.relu(self.conv1(x))\n x = self.max_pool(x)\n x = torch.flatten(x, 1)\n x = self.relu(self.fc1(x))\n return self.fc2(x)\n\n def load_weights(self):\n fpath = os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"../../utils/resources/models/certification/derandomized/\"\n )\n self.conv1.weight = nn.Parameter(torch.from_numpy(np.load(fpath + \"W_CONV2D1_MNIST.npy\")).float())\n self.conv1.bias = nn.Parameter(torch.from_numpy(np.load(fpath + \"B_CONV2D1_MNIST.npy\")).float())\n\n self.fc1.weight = nn.Parameter(torch.from_numpy(np.load(fpath + \"W_DENSE1_MNIST.npy\")).float())\n self.fc1.bias = nn.Parameter(torch.from_numpy(np.load(fpath + \"B_DENSE1_MNIST.npy\")).float())\n\n self.fc2.weight = nn.Parameter(torch.from_numpy(np.load(fpath + \"W_DENSE2_MNIST.npy\")).float())\n self.fc2.bias = nn.Parameter(torch.from_numpy(np.load(fpath + \"B_DENSE2_MNIST.npy\")).float())\n\n ptc = SmallMNISTModel()\n ptc.load_weights()\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(ptc.parameters(), lr=0.01)\n\n try:\n for ablation_type in [\"column\", \"block\"]:\n if ablation_type == \"column\":\n size_to_certify = 5\n ablation_size = 2\n else:\n \"\"\"\n the model was trained on column ablations, so make the block task simpler so that a\n degree of certification is obtained.\n \"\"\"\n size_to_certify = 1\n ablation_size = 5\n\n classifier = PyTorchDeRandomizedSmoothing(\n model=ptc,\n clip_values=(0, 1),\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n ablation_type=ablation_type,\n ablation_size=ablation_size,\n threshold=0.3,\n algorithm=\"levine2020\",\n logits=True,\n )\n\n preds = classifier.predict(np.copy(fix_get_mnist_data[0]))\n cert, cert_and_correct, top_predicted_class_argmax = classifier.ablator.certify(\n preds, label=fix_get_mnist_data[1], size_to_certify=size_to_certify\n )\n if ablation_type == \"column\":\n assert np.sum(cert.cpu().numpy()) == 52\n else:\n assert np.sum(cert.cpu().numpy()) == 22\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"pytorch\")\ndef test_tf2_mnist_certification(art_warning, fix_get_mnist_data):\n \"\"\"\n Assert that the correct number of certifications are given for the MNIST dataset\n \"\"\"\n\n import tensorflow as tf\n\n def build_model(input_shape):\n img_inputs = tf.keras.Input(shape=(input_shape[0], input_shape[1], input_shape[2] * 2))\n x = tf.keras.layers.Conv2D(filters=32, kernel_size=(4, 4), strides=(2, 2), activation=\"relu\")(img_inputs)\n x = tf.keras.layers.MaxPool2D(pool_size=(2, 2), strides=2)(x)\n # tensorflow uses channels last, and we are loading weights from an originally trained pytorch model\n x = tf.keras.layers.Permute((3, 1, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n x = tf.keras.layers.Dense(100, activation=\"relu\")(x)\n x = tf.keras.layers.Dense(10)(x)\n return tf.keras.Model(inputs=img_inputs, outputs=x)\n\n def get_weights():\n fpath = os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"../../utils/resources/models/certification/derandomized/\"\n )\n weight_names = [\n \"W_CONV2D1_MNIST.npy\",\n \"B_CONV2D1_MNIST.npy\",\n \"W_DENSE1_MNIST.npy\",\n \"B_DENSE1_MNIST.npy\",\n \"W_DENSE2_MNIST.npy\",\n \"B_DENSE2_MNIST.npy\",\n ]\n weight_list = []\n for name in weight_names:\n w = np.load(fpath + name)\n if \"W_CONV\" in name:\n w = np.transpose(w, (2, 3, 1, 0))\n if \"W_DENSE\" in name:\n w = np.transpose(w)\n weight_list.append(w)\n return weight_list\n\n net = build_model(input_shape=(28, 28, 1))\n net.set_weights(get_weights())\n\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)\n\n try:\n for ablation_type in [\"column\", \"block\"]:\n if ablation_type == \"column\":\n size_to_certify = 5\n ablation_size = 2\n else:\n \"\"\"\n the model was trained on column ablations, so make the block task simpler so that a\n degree of certification is obtained.\n \"\"\"\n size_to_certify = 1\n ablation_size = 5\n\n classifier = TensorFlowV2DeRandomizedSmoothing(\n model=net,\n clip_values=(0, 1),\n loss_object=loss_object,\n optimizer=optimizer,\n input_shape=(28, 28, 1),\n nb_classes=10,\n ablation_type=ablation_type,\n ablation_size=ablation_size,\n threshold=0.3,\n logits=True,\n )\n\n x = np.copy(fix_get_mnist_data[0])\n x = np.squeeze(x)\n x = np.expand_dims(x, axis=-1)\n preds = classifier.predict(x)\n cert, cert_and_correct, top_predicted_class_argmax = classifier.ablator.certify(\n preds, label=fix_get_mnist_data[1], size_to_certify=size_to_certify\n )\n\n if ablation_type == \"column\":\n assert np.sum(cert) == 52\n else:\n assert np.sum(cert) == 22\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_interval.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\nimport torch\nimport numpy as np\n\nfrom art.estimators.certification.interval import PyTorchIBPClassifier\nfrom art.estimators.certification.interval import PyTorchIntervalConv2D\n\nfrom art.utils import load_dataset\nfrom tests.utils import ARTTestException\nfrom tests.utils import get_image_classifier_pt\n\n\ndef get_synthetic_model():\n \"\"\"\n Get a model with just one convolutional layer to test the convolutional to dense conversion\n \"\"\"\n\n class SyntheticIntervalModel(torch.nn.Module):\n def __init__(\n self, input_shape, output_channels, kernel_size, stride=1, bias=False, padding=0, dilation=1, to_debug=True\n ):\n super().__init__()\n\n self.conv1 = PyTorchIntervalConv2D(\n in_channels=input_shape[1],\n out_channels=output_channels,\n kernel_size=kernel_size,\n input_shape=input_shape,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias,\n to_debug=to_debug,\n device=torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"),\n )\n\n def forward(self, x):\n \"\"\"\n Computes the forward pass though the neural network\n :param x: input data of the form [number of samples, interval, feature]\n :return:\n \"\"\"\n return self.conv1.concrete_forward(x)\n\n return SyntheticIntervalModel\n\n\n@pytest.fixture()\ndef fix_get_mnist_data():\n \"\"\"\n Get the first 100 samples of the mnist test set with channels first format.\n :return: First 100 sample/label pairs of the MNIST test dataset.\n \"\"\"\n nb_test = 100\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_test = np.squeeze(x_test)\n x_test = np.expand_dims(x_test, axis=1)\n y_test = np.argmax(y_test, axis=1)\n\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n\n return x_test, y_test\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_single_channel_in_multi_out(art_warning):\n \"\"\"\n Check that the conversion works for a single input channel.\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 1, 25, 25).to(device)\n model = synth_model(input_shape=synthetic_data.shape, output_channels=4, kernel_size=5)\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n output_from_equivalent = torch.reshape(output_from_equivalent, output_from_conv.shape)\n try:\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_multi_channel_in_single_out():\n \"\"\"\n Check that the conversion works for multiple input channels with single output\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 3, 25, 25).to(device)\n model = synth_model(input_shape=synthetic_data.shape, output_channels=1, kernel_size=5)\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n\n output_from_equivalent = output_from_equivalent.flatten()\n output_from_conv = output_from_conv.flatten()\n\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_multi_channel_in_multi_out():\n \"\"\"\n Check that the conversion works for multiple input channels and multiple output channels.\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 3, 25, 25).to(device)\n model = synth_model(input_shape=synthetic_data.shape, output_channels=12, kernel_size=5)\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_layer_multi_channel_in_multi_out_with_stride():\n \"\"\"\n Check that the conversion works for multiple input/output channels with strided convolution\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 3, 25, 25).to(device)\n model = synth_model(input_shape=synthetic_data.shape, output_channels=12, kernel_size=5, stride=2)\n\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_layer_multi_channel_in_multi_out_with_stride_and_bias():\n \"\"\"\n Check that the conversion works for multiple input/output channels with strided convolution and bias\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 3, 25, 25).to(device)\n model = synth_model(input_shape=synthetic_data.shape, output_channels=12, kernel_size=5, bias=True, stride=2)\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_layer_padding():\n \"\"\"\n Check that the conversion works for multiple input/output channels with strided convolution, bias,\n and padding\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 3, 25, 25).to(device)\n model = synth_model(\n input_shape=synthetic_data.shape, output_channels=12, kernel_size=5, bias=True, padding=2, stride=2\n )\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_layer_dilation():\n \"\"\"\n Check that the conversion works for multiple input/output channels with strided convolution, bias,\n padding, and dilation\n \"\"\"\n synth_model = get_synthetic_model()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n synthetic_data = torch.rand(32, 3, 25, 25).to(device)\n model = synth_model(\n input_shape=synthetic_data.shape, output_channels=12, kernel_size=5, bias=True, padding=2, stride=2, dilation=3\n )\n output_from_equivalent = model.forward(synthetic_data)\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n\n assert torch.allclose(output_from_equivalent, output_from_conv, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_layer_grads():\n \"\"\"\n Checking that the gradients are correctly backpropagated through the convolutional layer\n \"\"\"\n synth_model = get_synthetic_model()\n output_channels = 12\n input_channels = 3\n loss_fn = torch.nn.MSELoss()\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n target = torch.rand(size=(32, 12, 21, 21)).to(device)\n\n synthetic_data = torch.rand(32, input_channels, 25, 25).to(device)\n model = synth_model(\n input_shape=synthetic_data.shape, output_channels=output_channels, kernel_size=5, bias=True, stride=1\n )\n model = model.to(device)\n output_from_equivalent = model.forward(synthetic_data)\n loss = loss_fn(output_from_equivalent, target)\n loss.backward()\n\n equivalent_grads = model.conv1.conv.weight.grad\n equivalent_grads = (\n torch.reshape(equivalent_grads, shape=(output_channels, input_channels, 5, 5)).detach().clone().to(device)\n )\n equivalent_bias = model.conv1.bias_to_grad.grad.data.detach().clone().to(device)\n\n model.zero_grad()\n output_from_conv = model.conv1.conv_debug(synthetic_data)\n loss = loss_fn(output_from_conv, target)\n loss.backward()\n\n assert torch.allclose(equivalent_grads, model.conv1.conv_debug.weight.grad, atol=1e-05)\n assert torch.allclose(equivalent_bias, model.conv1.conv_debug.bias.grad, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_conv_train_loop():\n \"\"\"\n Assert that training the interval conv layer gives the same results as a regular layer\n \"\"\"\n output_channels = 12\n input_channels = 3\n loss_fn = torch.nn.MSELoss()\n synth_model = get_synthetic_model()\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n target = torch.rand(size=(32, 12, 21, 21)).to(device)\n\n synthetic_data = torch.rand(32, input_channels, 25, 25).to(device)\n model = synth_model(\n input_shape=synthetic_data.shape,\n output_channels=output_channels,\n kernel_size=5,\n bias=True,\n stride=1,\n to_debug=False,\n ).to(device)\n\n class TestModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.conv = torch.nn.Conv2d(\n in_channels=3,\n out_channels=12,\n kernel_size=5,\n bias=True,\n stride=1,\n )\n\n def forward(self, x):\n return self.conv(x)\n\n test_model = TestModel()\n # Get the weights we will transfer over\n # Set the weights in the normal model\n test_model.conv.weight = torch.nn.Parameter(\n torch.reshape(\n torch.tensor(model.conv1.conv.weight.data.cpu().detach().numpy()),\n shape=(output_channels, input_channels, 5, 5),\n )\n )\n test_model.conv.bias = torch.nn.Parameter(torch.tensor(model.conv1.bias_to_grad.data.cpu().detach().numpy()))\n test_model.to(device)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\n test_opt = torch.optim.Adam(test_model.parameters(), lr=0.0001)\n\n for _ in range(5):\n model.zero_grad()\n\n # Test model is for ground truth comparison\n test_model.zero_grad()\n output_from_equivalent = model.forward(synthetic_data)\n loss = loss_fn(output_from_equivalent, target)\n loss.backward()\n\n equivalent_grads = model.conv1.conv.weight.grad\n equivalent_grads = (\n torch.reshape(equivalent_grads, shape=(output_channels, input_channels, 5, 5)).detach().clone().to(device)\n )\n equivalent_bias = model.conv1.bias_to_grad.grad.clone().to(device)\n\n output_from_conv = test_model.forward(synthetic_data)\n loss = loss_fn(output_from_conv, target)\n loss.backward()\n\n assert torch.allclose(equivalent_grads, test_model.conv.weight.grad, atol=1e-05)\n assert torch.allclose(equivalent_bias, test_model.conv.bias.grad, atol=1e-05)\n\n optimizer.step()\n test_opt.step()\n\n reshaped_weights = torch.reshape(\n model.conv1.conv.weight.data.clone().detach(), shape=(output_channels, input_channels, 5, 5)\n ).to(device)\n\n assert torch.allclose(reshaped_weights, test_model.conv.weight.data, atol=1e-05)\n\n # function to re-pop the dense layer\n model.conv1.re_convert(device)\n\n # Sanity check! Are the grads still present and the same after the conversion?\n equivalent_grads = model.conv1.conv.weight.grad\n equivalent_grads = (\n torch.reshape(equivalent_grads, shape=(output_channels, input_channels, 5, 5)).detach().clone().to(device)\n )\n equivalent_bias = model.conv1.bias_to_grad.grad\n\n assert torch.allclose(equivalent_grads, test_model.conv.weight.grad, atol=1e-05)\n assert torch.allclose(equivalent_bias, test_model.conv.bias.grad, atol=1e-05)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_mnist_certification(art_warning, fix_get_mnist_data):\n \"\"\"\n Assert the certification performance on sample MNIST data\n \"\"\"\n bound = 0.05\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n\n box_model = PyTorchIBPClassifier(\n model=ptc.model.to(device),\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n mnist_data = fix_get_mnist_data[0]\n mnist_labels = fix_get_mnist_data[1]\n box_model.model.set_forward_mode(\"concrete\")\n preds = box_model.predict(mnist_data.astype(\"float32\"))\n acc = np.sum(np.argmax(preds, axis=1) == mnist_labels)\n assert acc == 99\n\n box_model.model.set_forward_mode(\"abstract\")\n up_bound = np.expand_dims(np.clip(mnist_data + bound, 0, 1), axis=1)\n low_bound = np.expand_dims(np.clip(mnist_data - bound, 0, 1), axis=1)\n interval_x = np.concatenate([low_bound, up_bound], axis=1)\n\n interval_preds = box_model.predict_intervals(interval_x, is_interval=True)\n cert_results = box_model.certify(preds=interval_preds, labels=mnist_labels)\n assert np.sum(cert_results) == 48\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_mnist_certification_conversion(art_warning, fix_get_mnist_data):\n \"\"\"\n Assert that the re-convert method does not throw errors\n \"\"\"\n\n class TestModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.conv1 = torch.nn.Conv2d(\n in_channels=1,\n out_channels=32,\n kernel_size=5,\n bias=True,\n stride=1,\n ).to(self.device)\n\n self.conv2 = torch.nn.Conv2d(\n in_channels=32,\n out_channels=32,\n kernel_size=5,\n bias=True,\n stride=1,\n ).to(self.device)\n\n self.fc1 = torch.nn.Linear(in_features=12800, out_features=100)\n self.fc2 = torch.nn.Linear(in_features=100, out_features=10)\n self.relu = torch.nn.ReLU()\n\n def forward(self, x):\n x = self.relu(self.conv1(x))\n x = self.relu(self.conv2(x))\n x = x.reshape(x.shape[0], -1)\n x = self.relu(self.fc1(x))\n\n return self.fc2(x)\n\n loss_fn = torch.nn.CrossEntropyLoss()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n model = TestModel().to(device)\n\n box_model = PyTorchIBPClassifier(\n model=model, clip_values=(0, 1), loss=torch.nn.CrossEntropyLoss(), input_shape=(1, 28, 28), nb_classes=10\n )\n\n mnist_data = fix_get_mnist_data[0]\n mnist_labels = torch.tensor(fix_get_mnist_data[1]).to(device)\n box_model.model.set_forward_mode(\"concrete\")\n for _ in range(5):\n preds = box_model.model.forward(mnist_data)\n loss = loss_fn(preds, mnist_labels)\n loss.backward()\n box_model.model.zero_grad()\n box_model.model.re_convert()\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_certification_bounds_vs_empirical(art_warning, fix_get_mnist_data):\n \"\"\"\n Create adversarial examples and assert that the lower bounds given by the classifier is higher than\n the empirical attacks and vice versa for the upper bounds\n \"\"\"\n from art.attacks.evasion.projected_gradient_descent.projected_gradient_descent import ProjectedGradientDescent\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n ptc.model.to(device)\n\n optimizer = torch.optim.Adam(ptc.model.parameters(), lr=0.0001)\n\n box_model = PyTorchIBPClassifier(\n model=ptc.model,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n mnist_data = fix_get_mnist_data[0]\n mnist_labels = fix_get_mnist_data[1]\n\n interval_preds = box_model.predict_intervals(x=mnist_data, bounds=0.3, limits=[0.0, 1.0])\n box_model.model.set_forward_mode(\"attack\")\n attack = ProjectedGradientDescent(\n estimator=box_model,\n eps=0.3,\n eps_step=0.001,\n max_iter=20,\n num_random_init=1,\n )\n i_batch = attack.generate(mnist_data.astype(\"float32\"), mnist_labels.astype(\"float32\"))\n adv_preds = box_model.predict(i_batch)\n\n for adv_pred, cert_prd in zip(adv_preds, interval_preds):\n assert np.all(adv_pred > cert_prd[0])\n assert np.all(adv_pred < cert_prd[1])\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_mnist_certification_training(art_warning, fix_get_mnist_data):\n \"\"\"\n Assert that the training loop runs without errors\n \"\"\"\n from art.defences.trainer import AdversarialTrainerCertifiedIBPPyTorch\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n ptc.model.to(device)\n\n optimizer = torch.optim.Adam(ptc.model.parameters(), lr=0.0001)\n\n box_model = PyTorchIBPClassifier(\n model=ptc.model,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n mnist_data = fix_get_mnist_data[0]\n mnist_labels = torch.tensor(fix_get_mnist_data[1])\n\n from torch.optim.lr_scheduler import MultiStepLR\n\n scheduler = MultiStepLR(box_model._optimizer, milestones=[2, 5], gamma=0.1)\n trainer = AdversarialTrainerCertifiedIBPPyTorch(classifier=box_model, bound=0.2)\n trainer.fit(x=mnist_data, y=mnist_labels, scheduler=scheduler, batch_size=32, nb_epochs=2, limits=[0, 1])\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"keras\", \"kerastf\", \"tensorflow2\")\ndef test_mnist_certification_training_with_pgd(art_warning, fix_get_mnist_data):\n \"\"\"\n Assert that the training loop runs without errors when also doing PGD augmentation\n \"\"\"\n from art.defences.trainer import AdversarialTrainerCertifiedIBPPyTorch\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n ptc = get_image_classifier_pt(from_logits=True, use_maxpool=False)\n ptc.model.to(device)\n\n optimizer = torch.optim.Adam(ptc.model.parameters(), lr=0.0001)\n\n box_model = PyTorchIBPClassifier(\n model=ptc.model,\n clip_values=(0, 1),\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n mnist_data = fix_get_mnist_data[0]\n mnist_labels = torch.tensor(fix_get_mnist_data[1])\n\n from torch.optim.lr_scheduler import MultiStepLR\n\n scheduler = MultiStepLR(box_model._optimizer, milestones=[2, 5], gamma=0.1)\n trainer = AdversarialTrainerCertifiedIBPPyTorch(\n classifier=box_model,\n bound=0.2,\n augment_with_pgd=True,\n pgd_params={\"eps\": 0.3, \"eps_step\": 0.05, \"max_iter\": 20, \"batch_size\": 32, \"num_random_init\": 1},\n )\n trainer.fit(x=mnist_data, y=mnist_labels, scheduler=scheduler, batch_size=32, nb_epochs=2, limits=[0, 1])\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_macer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.estimators.certification.randomized_smoothing import PyTorchMACER, TensorFlowV2MACER\nfrom tests.utils import ARTTestException, get_image_classifier_pt, get_image_classifier_tf\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_mnist_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n import torch\n\n classifier = get_image_classifier_pt()\n optimizer = torch.optim.SGD(classifier.model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[200, 400], gamma=0.1)\n rs = PyTorchMACER(\n model=classifier.model,\n loss=classifier._loss,\n input_shape=classifier.input_shape,\n nb_classes=classifier.nb_classes,\n optimizer=optimizer,\n clip_values=classifier.clip_values,\n channels_first=classifier.channels_first,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n beta=16.0,\n gamma=8.0,\n lmbda=12.0,\n gaussian_samples=16,\n )\n\n elif framework == \"tensorflow2\":\n import tensorflow as tf\n\n classifier, _ = get_image_classifier_tf()\n optimizer = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9, name=\"SGD\", decay=5e-4)\n scheduler = tf.keras.optimizers.schedules.PiecewiseConstantDecay([250, 400], [0.01, 0.001, 0.0001])\n rs = TensorFlowV2MACER(\n model=classifier.model,\n nb_classes=classifier.nb_classes,\n input_shape=classifier.input_shape,\n loss_object=classifier.loss_object,\n optimizer=optimizer,\n train_step=None,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n beta=16.0,\n gamma=8.0,\n lmbda=12.0,\n gaussian_samples=16,\n )\n\n else:\n classifier, scheduler, rs = None, None, None\n\n return classifier, scheduler, rs\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_smoothmix_mnist_predict(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n classifier, _, rs = get_mnist_classifier()\n y_test_base = classifier.predict(x=x_test)\n y_test_smooth = rs.predict(x=x_test)\n\n np.testing.assert_array_equal(y_test_smooth.shape, y_test_base.shape)\n np.testing.assert_array_almost_equal(np.sum(y_test_smooth, axis=1), np.ones(len(y_test)))\n np.testing.assert_array_almost_equal(np.argmax(y_test_smooth, axis=1), np.argmax(y_test_base, axis=1))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_smoothmix_mnist_fit(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, scheduler, rs = get_mnist_classifier()\n rs.fit(x=x_test, y=y_test, batch_size=128, nb_epochs=1, scheduler=scheduler)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_smoothmix_mnist_certification(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, _, rs = get_mnist_classifier()\n pred, radius = rs.certify(x=x_test, n=250)\n\n np.testing.assert_array_equal(pred.shape, radius.shape)\n np.testing.assert_array_less(radius, 1)\n np.testing.assert_array_less(pred, y_test.shape[1])\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_randomized_smoothing.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.estimators.certification.randomized_smoothing import (\n NumpyRandomizedSmoothing,\n TensorFlowV2RandomizedSmoothing,\n PyTorchRandomizedSmoothing,\n)\nfrom art.utils import load_dataset, random_targets\n\nfrom tests.utils import (\n get_image_classifier_pt,\n get_image_classifier_tf,\n get_image_classifier_kr,\n get_tabular_classifier_pt,\n ARTTestException,\n)\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_mnist_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n import torch\n\n classifier = get_image_classifier_pt()\n optimizer = torch.optim.Adam(classifier.model.parameters(), lr=0.01)\n rs = PyTorchRandomizedSmoothing(\n model=classifier.model,\n loss=classifier._loss,\n optimizer=optimizer,\n input_shape=classifier.input_shape,\n nb_classes=classifier.nb_classes,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n )\n\n elif framework == \"tensorflow2\":\n classifier, _ = get_image_classifier_tf()\n rs = TensorFlowV2RandomizedSmoothing(\n model=classifier.model,\n nb_classes=classifier.nb_classes,\n input_shape=classifier.input_shape,\n loss_object=classifier.loss_object,\n optimizer=classifier.optimizer,\n train_step=classifier.train_step,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n )\n\n elif framework in (\"keras\", \"kerastf\"):\n classifier = get_image_classifier_kr()\n rs = NumpyRandomizedSmoothing(\n classifier=classifier,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n )\n\n else:\n classifier, rs = None, None\n\n return classifier, rs\n\n return _get_classifier\n\n\n@pytest.fixture()\ndef get_iris_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n classifier = get_tabular_classifier_pt()\n rs = PyTorchRandomizedSmoothing(\n model=classifier.model,\n loss=classifier._loss,\n input_shape=classifier.input_shape,\n nb_classes=classifier.nb_classes,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n )\n\n else:\n classifier, rs = None, None\n\n return classifier, rs\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\")\ndef test_randomized_smoothing_mnist_predict(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n classifier, rs = get_mnist_classifier()\n y_test_base = classifier.predict(x=x_test)\n y_test_smooth = rs.predict(x=x_test)\n\n np.testing.assert_array_equal(y_test_smooth.shape, y_test_base.shape)\n np.testing.assert_array_almost_equal(np.sum(y_test_smooth, axis=1), np.ones(len(y_test)))\n np.testing.assert_array_almost_equal(np.argmax(y_test_smooth, axis=1), np.argmax(y_test_base, axis=1))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\")\ndef test_randomized_smoothing_mnist_fit(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, rs = get_mnist_classifier()\n rs.fit(x=x_test, y=y_test)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\")\ndef test_randomized_smoothing_mnist_certify(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, rs = get_mnist_classifier()\n pred, radius = rs.certify(x=x_test, n=250)\n\n np.testing.assert_array_equal(pred.shape, radius.shape)\n np.testing.assert_array_less(radius, 1)\n np.testing.assert_array_less(pred, y_test.shape[1])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\")\ndef test_randomized_smoothing_mnist_loss_gradient(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, rs = get_mnist_classifier()\n grad = rs.loss_gradient(x=x_test, y=y_test, sampling=True)\n\n np.testing.assert_array_equal(grad.shape, x_test.shape)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\", \"keras\", \"kerastf\")\ndef test_randomized_smoothing_mnist_fgsm(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n classifier, rs = get_mnist_classifier()\n fgsm = FastGradientMethod(estimator=classifier, targeted=True)\n params = {\"y\": random_targets(y_test, classifier.nb_classes)}\n x_test_adv = fgsm.generate(x_test, **params)\n\n fgsm_with_rs = FastGradientMethod(estimator=rs, targeted=True)\n x_test_adv_with_rs = fgsm_with_rs.generate(x_test, **params)\n\n np.testing.assert_array_equal(x_test_adv.shape, x_test_adv_with_rs.shape)\n np.testing.assert_array_less(np.abs(x_test_adv - x_test_adv_with_rs), 0.75)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_randomized_smoothing_iris_predict(art_warning, get_iris_classifier):\n (_, _), (x_test, y_test), _, _ = load_dataset(\"iris\")\n\n try:\n _, rs = get_iris_classifier()\n y_test_smooth = rs.predict(x=x_test)\n\n np.testing.assert_array_equal(y_test_smooth.shape, y_test.shape)\n assert np.all(np.sum(y_test_smooth, axis=1) <= 1)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_randomized_smoothing_iris_certify(art_warning, get_iris_classifier):\n (_, _), (x_test, y_test), _, _ = load_dataset(\"iris\")\n\n try:\n _, rs = get_iris_classifier()\n pred, radius = rs.certify(x=x_test, n=250)\n\n np.testing.assert_array_equal(pred.shape, radius.shape)\n np.testing.assert_array_less(radius, 1)\n np.testing.assert_array_less(pred, y_test.shape[1])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_randomized_smoothing_iris_fgsm(art_warning, get_iris_classifier):\n (_, _), (x_test, y_test), _, _ = load_dataset(\"iris\")\n\n try:\n classifier, rs = get_iris_classifier()\n attack = FastGradientMethod(classifier, eps=0.1)\n x_test_adv = attack.generate(x_test)\n preds_smooth = np.argmax(rs.predict(x_test_adv), axis=1)\n\n assert not np.array_equal(x_test, x_test_adv)\n assert not np.array_equal(np.argmax(y_test, axis=1), preds_smooth)\n assert np.all(x_test_adv <= 1)\n assert np.all(x_test_adv >= 0)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_smooth_adv.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.estimators.certification.randomized_smoothing import PyTorchSmoothAdv, TensorFlowV2SmoothAdv\nfrom tests.utils import ARTTestException, get_image_classifier_pt, get_image_classifier_tf\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_mnist_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n import torch\n\n classifier = get_image_classifier_pt()\n optimizer = torch.optim.SGD(classifier.model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.1)\n rs = PyTorchSmoothAdv(\n model=classifier.model,\n loss=classifier._loss,\n input_shape=classifier.input_shape,\n nb_classes=classifier.nb_classes,\n optimizer=optimizer,\n clip_values=classifier.clip_values,\n channels_first=classifier.channels_first,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n epsilon=1.0,\n num_noise_vec=1,\n num_steps=10,\n warmup=1,\n )\n\n elif framework == \"tensorflow2\":\n import tensorflow as tf\n\n classifier, _ = get_image_classifier_tf()\n optimizer = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9, name=\"SGD\", decay=1e-4)\n scheduler = tf.keras.optimizers.schedules.PiecewiseConstantDecay([50, 100], [0.01, 0.001, 0.0001])\n rs = TensorFlowV2SmoothAdv(\n model=classifier.model,\n nb_classes=classifier.nb_classes,\n input_shape=classifier.input_shape,\n loss_object=classifier.loss_object,\n optimizer=optimizer,\n train_step=None,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n epsilon=1.0,\n num_noise_vec=1,\n num_steps=10,\n warmup=1,\n )\n\n else:\n classifier, scheduler, rs = None, None, None\n\n return classifier, scheduler, rs\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_smoothmix_mnist_predict(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n classifier, _, rs = get_mnist_classifier()\n y_test_base = classifier.predict(x=x_test)\n y_test_smooth = rs.predict(x=x_test)\n\n np.testing.assert_array_equal(y_test_smooth.shape, y_test_base.shape)\n np.testing.assert_array_almost_equal(np.sum(y_test_smooth, axis=1), np.ones(len(y_test)))\n np.testing.assert_array_almost_equal(np.argmax(y_test_smooth, axis=1), np.argmax(y_test_base, axis=1))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_smoothmix_mnist_fit(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, scheduler, rs = get_mnist_classifier()\n rs.fit(x=x_test, y=y_test, batch_size=128, nb_epochs=1, scheduler=scheduler)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\", \"tensorflow2\")\ndef test_smoothmix_mnist_certification(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, _, rs = get_mnist_classifier()\n pred, radius = rs.certify(x=x_test, n=250)\n\n np.testing.assert_array_equal(pred.shape, radius.shape)\n np.testing.assert_array_less(radius, 1)\n np.testing.assert_array_less(pred, y_test.shape[1])\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_smooth_mix.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\n\nfrom art.estimators.certification.randomized_smoothing import PyTorchSmoothMix\nfrom tests.utils import ARTTestException, get_image_classifier_pt, get_cifar10_image_classifier_pt\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_mnist_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n import torch\n\n classifier = get_image_classifier_pt()\n optimizer = torch.optim.SGD(classifier.model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=50, gamma=0.1)\n rs = PyTorchSmoothMix(\n model=classifier.model,\n loss=classifier._loss,\n input_shape=classifier.input_shape,\n nb_classes=classifier.nb_classes,\n optimizer=optimizer,\n clip_values=classifier.clip_values,\n channels_first=classifier.channels_first,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n eta=5.0,\n num_noise_vec=2,\n num_steps=8,\n warmup=10,\n mix_step=0,\n maxnorm_s=None,\n maxnorm=None,\n )\n\n else:\n classifier, scheduler, rs = None, None, None\n\n return classifier, scheduler, rs\n\n return _get_classifier\n\n\n@pytest.fixture()\ndef get_cifar10_classifier(framework):\n def _get_classifier():\n if framework == \"pytorch\":\n import torch\n\n classifier = get_cifar10_image_classifier_pt()\n optimizer = torch.optim.SGD(classifier.model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=50, gamma=0.1)\n rs = PyTorchSmoothMix(\n model=classifier.model,\n loss=classifier._loss,\n input_shape=classifier.input_shape,\n nb_classes=classifier.nb_classes,\n optimizer=optimizer,\n clip_values=classifier.clip_values,\n channels_first=classifier.channels_first,\n sample_size=100,\n scale=0.01,\n alpha=0.001,\n eta=5.0,\n num_noise_vec=2,\n num_steps=8,\n warmup=10,\n mix_step=0,\n maxnorm_s=None,\n maxnorm=None,\n )\n\n else:\n classifier, scheduler, rs = None, None, None\n\n return classifier, scheduler, rs\n\n return _get_classifier\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_smoothmix_mnist_predict(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n classifier, _, rs = get_mnist_classifier()\n y_test_base = classifier.predict(x=x_test)\n y_test_smooth = rs.predict(x=x_test)\n\n np.testing.assert_array_equal(y_test_smooth.shape, y_test_base.shape)\n np.testing.assert_array_almost_equal(np.sum(y_test_smooth, axis=1), np.ones(len(y_test)))\n np.testing.assert_array_almost_equal(np.argmax(y_test_smooth, axis=1), np.argmax(y_test_base, axis=1))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_smoothmix_mnist_fit(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, scheduler, rs = get_mnist_classifier()\n rs.fit(x=x_test, y=y_test, batch_size=128, nb_epochs=1, scheduler=scheduler)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_smoothmix_mnist_certification(art_warning, get_default_mnist_subset, get_mnist_classifier):\n (_, _), (x_test, y_test) = get_default_mnist_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, _, rs = get_mnist_classifier()\n pred, radius = rs.certify(x=x_test, n=250)\n\n np.testing.assert_array_equal(pred.shape, radius.shape)\n np.testing.assert_array_less(radius, 1)\n np.testing.assert_array_less(pred, y_test.shape[1])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_smoothmix_cifar10_predict(art_warning, get_default_cifar10_subset, get_cifar10_classifier):\n (_, _), (x_test, y_test) = get_default_cifar10_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n classifier, _, rs = get_cifar10_classifier()\n y_test_base = classifier.predict(x=x_test)\n y_test_smooth = rs.predict(x=x_test)\n\n np.testing.assert_array_equal(y_test_smooth.shape, y_test_base.shape)\n np.testing.assert_array_almost_equal(np.sum(y_test_smooth, axis=1), np.ones((len(y_test))))\n np.testing.assert_array_almost_equal(np.argmax(y_test_smooth, axis=1), np.argmax(y_test_base, axis=1))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_smoothmix_cifar10_fit(art_warning, get_default_cifar10_subset, get_cifar10_classifier):\n (_, _), (x_test, y_test) = get_default_cifar10_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, scheduler, rs = get_cifar10_classifier()\n rs.fit(x=x_test, y=y_test, batch_size=128, nb_epochs=1, scheduler=scheduler)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_smoothmix_cifar10_certification(art_warning, get_default_cifar10_subset, get_cifar10_classifier):\n (_, _), (x_test, y_test) = get_default_cifar10_subset\n x_test, y_test = x_test[:10], y_test[:10]\n\n try:\n _, _, rs = get_cifar10_classifier()\n pred, radius = rs.certify(x=x_test, n=250)\n\n np.testing.assert_array_equal(pred.shape, radius.shape)\n np.testing.assert_array_less(radius, 1)\n np.testing.assert_array_less(pred, y_test.shape[1])\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/test_vision_transformers.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\nimport os\n\nimport numpy as np\n\nfrom art.utils import load_dataset\nfrom tests.utils import ARTTestException\n\n\n@pytest.fixture()\ndef fix_get_mnist_data():\n \"\"\"\n Get the first 128 samples of the mnist test set with channels first format\n\n :return: First 128 sample/label pairs of the MNIST test dataset.\n \"\"\"\n nb_test = 128\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_test = np.squeeze(x_test).astype(np.float32)\n x_test = np.expand_dims(x_test, axis=1)\n y_test = np.argmax(y_test, axis=1)\n\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n return x_test, y_test\n\n\n@pytest.fixture()\ndef fix_get_cifar10_data():\n \"\"\"\n Get the first 128 samples of the cifar10 test set\n\n :return: First 128 sample/label pairs of the cifar10 test dataset.\n \"\"\"\n nb_test = 128\n\n (_, _), (x_test, y_test), _, _ = load_dataset(\"cifar10\")\n y_test = np.argmax(y_test, axis=1)\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n x_test = np.transpose(x_test, (0, 3, 1, 2)) # return in channels first format\n return x_test.astype(np.float32), y_test\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_ablation(art_warning, fix_get_mnist_data, fix_get_cifar10_data):\n \"\"\"\n Check that the ablation is being performed correctly\n \"\"\"\n import torch\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n from art.estimators.certification.derandomized_smoothing.ablators.pytorch import ColumnAblatorPyTorch\n\n try:\n cifar_data = fix_get_cifar10_data[0]\n\n col_ablator = ColumnAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n to_reshape=False, # do not upsample initially\n mode=\"ViT\",\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n )\n\n cifar_data = torch.from_numpy(cifar_data).to(device)\n # check that the ablation functioned when in the middle of the image\n ablated = col_ablator.forward(cifar_data, column_pos=10)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, :, 0:10]) == 0\n assert torch.sum(ablated[:, :, :, 10:14]) > 0\n assert torch.sum(ablated[:, :, :, 14:]) == 0\n\n # check that the ablation wraps when on the edge of the image\n ablated = col_ablator.forward(cifar_data, column_pos=30)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, :, 30:]) > 0\n assert torch.sum(ablated[:, :, :, 2:30]) == 0\n assert torch.sum(ablated[:, :, :, :2]) > 0\n\n # check that upsampling works as expected\n col_ablator = ColumnAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n to_reshape=True,\n mode=\"ViT\",\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n )\n\n ablated = col_ablator.forward(cifar_data, column_pos=10)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, :, : 10 * 7]) == 0\n assert torch.sum(ablated[:, :, :, 10 * 7 : 14 * 7]) > 0\n assert torch.sum(ablated[:, :, :, 14 * 7 :]) == 0\n\n # check that the ablation wraps when on the edge of the image\n ablated = col_ablator.forward(cifar_data, column_pos=30)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, :, 30 * 7 :]) > 0\n assert torch.sum(ablated[:, :, :, 2 * 7 : 30 * 7]) == 0\n assert torch.sum(ablated[:, :, :, : 2 * 7]) > 0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_ablation_row(art_warning, fix_get_mnist_data, fix_get_cifar10_data):\n \"\"\"\n Check that the ablation is being performed correctly\n \"\"\"\n import torch\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n from art.estimators.certification.derandomized_smoothing.ablators.pytorch import ColumnAblatorPyTorch\n\n try:\n cifar_data = fix_get_cifar10_data[0]\n\n col_ablator = ColumnAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n to_reshape=False, # do not upsample initially\n mode=\"ViT\",\n ablation_mode=\"row\",\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n )\n\n cifar_data = torch.from_numpy(cifar_data).to(device)\n # check that the ablation functioned when in the middle of the image\n ablated = col_ablator.forward(cifar_data, column_pos=10)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, 0:10, :]) == 0\n assert torch.sum(ablated[:, :, 10:14, :]) > 0\n assert torch.sum(ablated[:, :, 14:, :]) == 0\n\n # check that the ablation wraps when on the edge of the image\n ablated = col_ablator.forward(cifar_data, column_pos=30)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, 30:, :]) > 0\n assert torch.sum(ablated[:, :, 2:30, :]) == 0\n assert torch.sum(ablated[:, :, :2, :]) > 0\n\n # check that upsampling works as expected\n col_ablator = ColumnAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n to_reshape=True,\n mode=\"ViT\",\n ablation_mode=\"row\",\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n )\n\n ablated = col_ablator.forward(cifar_data, column_pos=10)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, : 10 * 7, :]) == 0\n assert torch.sum(ablated[:, :, 10 * 7 : 14 * 7, :]) > 0\n assert torch.sum(ablated[:, :, 14 * 7 :, :]) == 0\n\n # check that the ablation wraps when on the edge of the image\n ablated = col_ablator.forward(cifar_data, column_pos=30)\n\n assert ablated.shape[1] == 4\n assert torch.sum(ablated[:, :, 30 * 7 :, :]) > 0\n assert torch.sum(ablated[:, :, 2 * 7 : 30 * 7, :]) == 0\n assert torch.sum(ablated[:, :, : 2 * 7, :]) > 0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_training(art_warning, fix_get_mnist_data, fix_get_cifar10_data):\n \"\"\"\n Check that the training loop for pytorch does not result in errors\n \"\"\"\n import torch\n from art.estimators.certification.derandomized_smoothing import PyTorchDeRandomizedSmoothing\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n try:\n cifar_data = fix_get_cifar10_data[0][:50]\n cifar_labels = fix_get_cifar10_data[1][:50]\n\n art_model = PyTorchDeRandomizedSmoothing(\n model=\"vit_small_patch16_224\",\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=torch.optim.SGD,\n optimizer_params={\"lr\": 0.01},\n input_shape=(3, 32, 32),\n nb_classes=10,\n ablation_size=4,\n load_pretrained=True,\n replace_last_layer=True,\n verbose=False,\n )\n\n scheduler = torch.optim.lr_scheduler.MultiStepLR(art_model.optimizer, milestones=[1], gamma=0.1)\n\n head = {\n \"weight\": torch.tensor(\n np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/head_weight.npy\",\n )\n )\n ).to(device),\n \"bias\": torch.tensor(\n np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/head_bias.npy\",\n )\n )\n ).to(device),\n }\n art_model.model.head.load_state_dict(head)\n\n art_model.fit(cifar_data, cifar_labels, nb_epochs=2, update_batchnorm=True, scheduler=scheduler)\n preds = art_model.predict(cifar_data)\n\n gt_preds = np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/cumulative_predictions.npy\",\n )\n )\n\n np.array_equal(preds, gt_preds)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_certification_function(art_warning, fix_get_mnist_data, fix_get_cifar10_data):\n \"\"\"\n Check that based on a given set of synthetic class predictions the certification gives the expected results.\n \"\"\"\n from art.estimators.certification.derandomized_smoothing.ablators.pytorch import ColumnAblatorPyTorch\n import torch\n\n try:\n col_ablator = ColumnAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n mode=\"ViT\",\n to_reshape=True, # do not upsample initially\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n )\n pred_counts = torch.from_numpy(np.asarray([[20, 5, 1], [10, 5, 1], [1, 16, 1]]))\n cert, cert_and_correct, top_predicted_class = col_ablator.certify(\n pred_counts=pred_counts,\n size_to_certify=4,\n label=0,\n )\n assert torch.equal(cert, torch.tensor([True, False, True]))\n assert torch.equal(cert_and_correct, torch.tensor([True, False, False]))\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"ablation\", [\"block\", \"column\"])\ndef test_end_to_end_equivalence(art_warning, fix_get_mnist_data, fix_get_cifar10_data, ablation):\n \"\"\"\n Assert implementations matches original with a forward pass through the same model architecture.\n There are some differences in architecture between the same model names in timm vs the original implementation.\n We use vit_base_patch16_224 which matches.\n \"\"\"\n import torch\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n from art.estimators.certification.derandomized_smoothing import PyTorchDeRandomizedSmoothing\n\n from art.estimators.certification.derandomized_smoothing.ablators import (\n ColumnAblatorPyTorch,\n BlockAblatorPyTorch,\n )\n\n cifar_data = fix_get_cifar10_data[0][:50]\n torch.manual_seed(1234)\n try:\n art_model = PyTorchDeRandomizedSmoothing(\n model=\"vit_base_patch16_224\",\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=torch.optim.SGD,\n optimizer_params={\"lr\": 0.01},\n input_shape=(3, 32, 32),\n nb_classes=10,\n ablation_size=4,\n load_pretrained=True,\n replace_last_layer=True,\n verbose=False,\n )\n\n if ablation == \"column\":\n ablator = ColumnAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n to_reshape=True,\n mode=\"ViT\",\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n )\n ablated = ablator.forward(cifar_data, column_pos=10)\n madry_preds = torch.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/madry_preds_column.pt\",\n )\n )\n art_preds = art_model.model(ablated)\n assert torch.allclose(madry_preds.to(device), art_preds, rtol=1e-04, atol=1e-04)\n\n elif ablation == \"block\":\n ablator = BlockAblatorPyTorch(\n ablation_size=4,\n channels_first=True,\n to_reshape=True,\n original_shape=(3, 32, 32),\n output_shape=(3, 224, 224),\n mode=\"ViT\",\n )\n ablated = ablator.forward(cifar_data, column_pos=10, row_pos=28)\n madry_preds = torch.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/madry_preds_block.pt\",\n )\n )\n art_preds = art_model.model(ablated)\n assert torch.allclose(madry_preds.to(device), art_preds, rtol=1e-04, atol=1e-04)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"ablation\", [\"block\", \"column\"])\ndef test_certification_equivalence(art_warning, fix_get_mnist_data, fix_get_cifar10_data, ablation):\n \"\"\"\n With the forward pass equivalence asserted, we now confirm that the certification functions in the same\n way by doing a full end to end prediction and certification test over the data.\n \"\"\"\n import torch\n\n from art.estimators.certification.derandomized_smoothing import PyTorchDeRandomizedSmoothing\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n try:\n art_model = PyTorchDeRandomizedSmoothing(\n model=\"vit_small_patch16_224\",\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=torch.optim.SGD,\n optimizer_params={\"lr\": 0.01},\n input_shape=(3, 32, 32),\n nb_classes=10,\n ablation_type=ablation,\n ablation_size=4,\n load_pretrained=True,\n replace_last_layer=True,\n verbose=False,\n )\n\n head = {\n \"weight\": torch.tensor(\n np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/head_weight.npy\",\n )\n )\n ).to(device),\n \"bias\": torch.tensor(\n np.load(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"../../utils/resources/models/certification/smooth_vit/head_bias.npy\",\n )\n )\n ).to(device),\n }\n art_model.model.head.load_state_dict(head)\n\n if torch.cuda.is_available():\n num_to_fetch = 100\n else:\n num_to_fetch = 10\n\n cifar_data = torch.from_numpy(fix_get_cifar10_data[0][:num_to_fetch]).to(device)\n cifar_labels = torch.from_numpy(fix_get_cifar10_data[1][:num_to_fetch]).to(device)\n\n acc, cert_acc = art_model.eval_and_certify(\n x=cifar_data.cpu().numpy(), y=cifar_labels.cpu().numpy(), batch_size=num_to_fetch, size_to_certify=4\n )\n\n upsample = torch.nn.Upsample(scale_factor=224 / 32)\n cifar_data = upsample(cifar_data)\n acc_non_ablation = art_model.model(cifar_data)\n acc_non_ablation = art_model.get_accuracy(acc_non_ablation, cifar_labels)\n\n if torch.cuda.is_available():\n if ablation == \"column\":\n assert np.allclose(cert_acc.cpu().numpy(), 0.29)\n assert np.allclose(acc.cpu().numpy(), 0.57)\n else:\n assert np.allclose(cert_acc.cpu().numpy(), 0.16)\n assert np.allclose(acc.cpu().numpy(), 0.24)\n assert np.allclose(acc_non_ablation, 0.52)\n else:\n if ablation == \"column\":\n assert np.allclose(cert_acc.cpu().numpy(), 0.30)\n assert np.allclose(acc.cpu().numpy(), 0.70)\n else:\n assert np.allclose(cert_acc.cpu().numpy(), 0.20)\n assert np.allclose(acc.cpu().numpy(), 0.20)\n assert np.allclose(acc_non_ablation, 0.60)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_equivalence(art_warning, fix_get_cifar10_data):\n import torch\n from art.estimators.certification.derandomized_smoothing import PyTorchDeRandomizedSmoothing\n from art.estimators.certification.derandomized_smoothing.vision_transformers.pytorch import PyTorchVisionTransformer\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n try:\n\n class MadrylabImplementations:\n \"\"\"\n Code adapted from the implementation in https://github.com/MadryLab/smoothed-vit\n to check against our own functionality.\n\n Original License:\n\n MIT License\n\n Copyright (c) 2021 Madry Lab\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n \"\"\"\n\n def __init__(self):\n pass\n\n @classmethod\n def token_dropper(cls, x, mask):\n \"\"\"\n The implementation of dropping tokens has been done slightly differently in this tool.\n Here we check that it is equivalent to the original implementation\n \"\"\"\n\n class MaskProcessor(torch.nn.Module):\n def __init__(self, patch_size=16):\n super().__init__()\n self.avg_pool = torch.nn.AvgPool2d(patch_size)\n\n def forward(self, ones_mask):\n B = ones_mask.shape[0]\n ones_mask = ones_mask[0].unsqueeze(0) # take the first mask\n ones_mask = self.avg_pool(ones_mask)[0]\n ones_mask = torch.where(ones_mask.view(-1) > 0)[0] + 1\n ones_mask = torch.cat([torch.IntTensor(1).fill_(0).to(device), ones_mask]).unsqueeze(0)\n ones_mask = ones_mask.expand(B, -1)\n return ones_mask\n\n mask_processor = MaskProcessor()\n patch_mask = mask_processor(mask)\n\n # x = self.pos_drop(x) # B, N, C\n if patch_mask is not None:\n # patch_mask is B, K\n B, N, C = x.shape\n if len(patch_mask.shape) == 1: # not a separate one per batch\n x = x[:, patch_mask]\n else:\n patch_mask = patch_mask.unsqueeze(-1).expand(-1, -1, C)\n x = torch.gather(x, 1, patch_mask)\n return x\n\n @classmethod\n def embedder(cls, x, pos_embed, cls_token):\n \"\"\"\n NB, original code used the pos embed from the divit rather than vit\n (which we pull from our model) which we use here.\n\n From timm vit:\n self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * .02)\n\n From timm dvit:\n self.pos_embed = nn.Parameter(torch.zeros(1,\n self.patch_embed.num_patches + self.num_prefix_tokens,\n self.embed_dim))\n\n From repo:\n self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))\n \"\"\"\n x = torch.cat((cls_token.expand(x.shape[0], -1, -1), x), dim=1)\n return x + pos_embed\n\n def forward_features(self, x: torch.Tensor, attn_mask: torch.Tensor | None = None) -> torch.Tensor:\n \"\"\"\n This is a copy of the function in ArtViT.forward_features\n except we also perform an equivalence assertion compared to the implementation\n in https://github.com/MadryLab/smoothed-vit (see MadrylabImplementations class above)\n\n The forward pass of the ViT.\n\n :param x: Input data.\n :param attn_mask: Attention mask.\n :return: The input processed by the ViT backbone\n \"\"\"\n import copy\n\n ablated_input = False\n if x.shape[1] == self.in_chans + 1:\n ablated_input = True\n\n if ablated_input:\n x, ablation_mask = x[:, : self.in_chans], x[:, self.in_chans : self.in_chans + 1]\n\n x = self.patch_embed(x)\n\n madry_embed = MadrylabImplementations.embedder(copy.copy(x), self.pos_embed, self.cls_token)\n x = self._pos_embed(x)\n assert torch.equal(madry_embed, x)\n\n # pass the x into the token dropping code\n madry_dropped = MadrylabImplementations.token_dropper(copy.copy(x), ablation_mask)\n\n if self.to_drop_tokens and ablated_input:\n ones = self.ablation_mask_embedder(ablation_mask)\n to_drop = torch.sum(ones, dim=2)\n indexes = torch.gt(torch.where(to_drop > 1, 1, 0), 0)\n x = self.drop_tokens(x, indexes)\n\n assert torch.equal(madry_dropped, x)\n\n x = self.norm_pre(x)\n x = self.blocks(x)\n\n return self.norm(x)\n\n # Replace the forward_features with the forward_features code with checks.\n PyTorchVisionTransformer.forward_features = forward_features\n\n art_model = PyTorchDeRandomizedSmoothing(\n model=\"vit_small_patch16_224\",\n loss=torch.nn.CrossEntropyLoss(),\n optimizer=torch.optim.SGD,\n optimizer_params={\"lr\": 0.01},\n input_shape=(3, 32, 32),\n nb_classes=10,\n ablation_size=4,\n load_pretrained=False,\n replace_last_layer=True,\n verbose=False,\n )\n\n cifar_data = fix_get_cifar10_data[0][:50]\n cifar_labels = fix_get_cifar10_data[1][:50]\n\n scheduler = torch.optim.lr_scheduler.MultiStepLR(art_model.optimizer, milestones=[1], gamma=0.1)\n art_model.fit(cifar_data, cifar_labels, nb_epochs=1, update_batchnorm=True, scheduler=scheduler, batch_size=128)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/output_results/mini_nets/cifar10_lb_results_0.004.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n[\n [\n -0.8378840533643059,\n -3.4111806331278984,\n 1.1988658974512776,\n 3.066127164416609,\n -0.805094748693834,\n 2.7698398274409164,\n 1.2468335811845932,\n -1.335311449206453,\n -0.5309939484200926,\n -3.6143041074527162\n ],\n [\n 2.9120915599840176,\n 3.9003710047695908,\n -1.858476096786187,\n -2.74796546026404,\n -3.0404790819029897,\n -3.8566253198263425,\n -3.661787489875837,\n -3.0719889344488243,\n 4.382638580951076,\n 4.07090478757098\n ],\n [\n 1.8072242210761438,\n 2.254249720214364,\n -1.0444638234918684,\n -1.436473859665103,\n -2.1334566428435293,\n -2.309417615388703,\n -3.2575312723169807,\n -2.193198462704929,\n 3.226739201988189,\n 2.118494504823108\n ],\n [\n 2.51037583365317,\n 0.740408741474522,\n 0.1624633313749695,\n -1.537597139691121,\n -0.693592315603631,\n -2.5984302095495178,\n -2.6779173611688227,\n -1.5545373152390702,\n 2.3445436571531877,\n 0.3336631238826844\n ],\n [\n -0.9071875889885956,\n -1.685716967791222,\n 0.13981565196724755,\n 1.4728731507604564,\n 0.5281414009082737,\n 0.9531555491332404,\n 2.2728385863463982,\n -0.08401751148617131,\n -3.6516575136987113,\n -1.1578771585385126\n ],\n [\n -0.34836263536167805,\n -1.7466770273361554,\n 1.2748167862083042,\n -0.14878581357916637,\n 1.8486663677859707,\n -1.3099487746948524,\n 2.7505817472415073,\n -1.164764505426145,\n -1.5668224234470602,\n -1.6057697734702532\n ],\n [\n -0.9249663724865473,\n -2.1359408004853417,\n 1.3600869941648848,\n 1.8064595434916262,\n 1.2274913592868173,\n 1.427073579387237,\n 0.15079011569085243,\n 0.055130130603498806,\n -2.294938626968638,\n -2.552381420779743\n ],\n [\n 2.033521772385946,\n 3.1964855350829957,\n -0.5567646504048687,\n -1.5651059861149272,\n -1.323767599380468,\n -2.9121778192472365,\n -2.6437216678184887,\n -2.4809867702655333,\n 2.2220367753309582,\n 1.3309978187359244\n ],\n [\n 1.9416255677923777,\n -1.2133528058103236,\n 0.05015124940764859,\n 0.17060990435314072,\n -0.014258149712089274,\n -0.3810168626393605,\n -1.302928555953648,\n -1.8183941342455139,\n 1.772569430440764,\n -1.879763737856041\n ],\n [\n -1.2661821606766412,\n 2.283708146244275,\n -1.1732931496857195,\n -0.5907158249088457,\n -2.068612647363696,\n -1.217554637834737,\n -1.056857988961175,\n -0.3959567474611303,\n -0.3382719239836649,\n 3.7058576856274303\n ],\n [\n 0.2775790682496706,\n 2.770446443404798,\n -0.558526888457626,\n -1.465963923931069,\n -2.058416777676977,\n -2.7033324844160647,\n -2.168679508229442,\n -0.803997845630287,\n 0.8753926011067013,\n 3.3891602683243356\n ],\n [\n 0.6989965635738364,\n -0.7397352448164785,\n -0.34087454181670784,\n -0.3869806251989978,\n 0.018703365698370833,\n -0.4988275297572839,\n -0.47424356773441856,\n -0.7725508707560571,\n 0.8109732735964149,\n -1.1256081351310434\n ],\n [\n -1.797980378101153,\n -0.9903077459194204,\n -0.013364508270405251,\n 1.7300641366857354,\n -0.9251708875212539,\n 2.0301832248862652,\n 0.8002876018140511,\n 0.13471972933666576,\n -1.649275665471706,\n -1.737510213094514\n ],\n [\n 2.193340350918032,\n 1.3075007805344376,\n -1.4750282170531488,\n -2.100655948587544,\n -2.1269091040458448,\n -3.3133526880520106,\n -2.2834147104803146,\n -2.2977732858670894,\n 5.074414845793342,\n 2.3128317542083123\n ],\n [\n -1.9779058754483363,\n -2.7377208382565192,\n 0.42544084216563793,\n 1.1887621212389359,\n 1.466268172404895,\n 1.0607356171499007,\n 3.0685541872260913,\n 1.00914010587266,\n -3.972049568896458,\n -1.680759983797968\n ],\n [\n -1.1102740688748736,\n 0.0725280138014135,\n 0.24504723537007211,\n -0.12376032190392394,\n 0.5238428930066727,\n 0.4173551430254807,\n -1.1854266127399877,\n 2.4387817239818816,\n -3.5215319266024747,\n -0.06690891120612097\n ],\n [\n 4.254503313455536,\n -2.8259106031808625,\n 2.9807353500666913,\n -0.14497515148523538,\n 1.0071850750104923,\n 0.669664965893366,\n -4.687711542528266,\n 0.9112943544868906,\n -0.5528918399483027,\n -3.3720362945744897\n ],\n [\n -1.6101657412828123,\n 4.071537874513082,\n -2.7972580925535455,\n -0.8639453339306573,\n -1.3524370282038118,\n -1.2924358893493841,\n -0.44538211178440257,\n 0.4102517839712969,\n -2.413841374409774,\n 4.552173088652679\n ],\n [\n -1.0719471244494472,\n 2.5711889522823244,\n -1.1587044560269772,\n 0.38717234063994,\n -1.108709513745635,\n -1.4271467390477923,\n -2.028538374714095,\n -0.04289150842175171,\n -2.3260547076060165,\n 3.564190082083976\n ],\n [\n -1.59093813036771,\n -1.2027616833661428,\n 0.5483125147035635,\n 0.11516076138738303,\n 1.2770923878693967,\n 0.241527822522682,\n 1.476482759060556,\n 0.5225022082773478,\n -2.54457427179263,\n -0.6805157181732338\n ],\n [\n -1.354526479128328,\n -0.6808371103001095,\n 0.4592505000664051,\n 1.1759815492627896,\n 0.635890789520219,\n 0.255363637803498,\n 1.801716387400944,\n 0.28719583461206577,\n -3.4186666885318293,\n -0.9807148667398237\n ],\n [\n 0.4366927401677967,\n -0.7226016917949523,\n -0.45806525618484795,\n -0.4067463137356264,\n -1.2929025745838714,\n -1.1066925814833122,\n -2.3950181675994675,\n 0.7340550146450977,\n 0.00893790483538015,\n 2.622342980478969\n ],\n [\n -1.0076724979710938,\n 1.8355083286959264,\n -1.4390455252676908,\n -0.04968391698227109,\n -1.3075901385270097,\n -0.4649381043077656,\n -0.720142536870644,\n -0.3693737992304369,\n -1.4174533014893747,\n 2.4062339756673934\n ],\n [\n -1.1383597201469366,\n -1.9613648117423617,\n 1.3019957877004171,\n 0.1394544029840669,\n 1.8064517771079138,\n -0.5094948136149203,\n 2.4172557786241695,\n -0.9320966449690475,\n -1.727160929274533,\n -1.705109082475819\n ],\n [\n -1.9201520762486326,\n -1.470949396640675,\n 0.6996054679110022,\n 1.17485974973676,\n 1.3912810836043326,\n 0.334005832552698,\n 2.3266103266588325,\n -0.40689879941896545,\n -2.919830779384014,\n -1.3884486794057929\n ],\n [\n 4.865899677265439,\n 2.7819002001759237,\n 0.9497689630784103,\n -5.672562737959405,\n 1.5060176644503498,\n -7.138176763742012,\n -6.997592705110206,\n -0.7665852075366099,\n 4.256128250291817,\n 2.6544376595635146\n ],\n [\n 1.7178375142037816,\n 0.8612101944947048,\n -1.3215841301450224,\n -0.9164180102261144,\n -1.7541245641091132,\n -1.2649570711507057,\n -3.1028193121013574,\n -0.2305934951325027,\n 0.5876034255512169,\n 2.800648852921559\n ],\n [\n -3.109932333069674,\n -3.6390360832695476,\n 0.8649113544162076,\n 2.4546963136932325,\n 1.1595955376052585,\n 2.2263457504763227,\n 2.415470743659163,\n 0.47170274165864035,\n -3.1187500960775925,\n -1.4235415651822982\n ],\n [\n -0.6062402083669006,\n -1.3015839198910373,\n -0.706145394876377,\n 0.6742495304654039,\n -0.9149782356350133,\n 0.057273403920680144,\n -1.770496283551711,\n 0.8865309669161536,\n 0.16226373892570473,\n 1.5145172573651493\n ],\n [\n -1.1072554101509784,\n -2.0777437967550223,\n 2.488336386153227,\n -0.030411146716234516,\n 2.380670859243212,\n -0.2845315574534183,\n 2.6789060176173947,\n -0.5609926441958957,\n -3.3772302291190925,\n -2.0924986005659596\n ],\n [\n -0.07408069996289662,\n 0.9947806047365955,\n -0.3357127131527069,\n -1.0141003039253222,\n -1.294953166223793,\n -1.8835816062248714,\n -2.8535867703007973,\n -0.13042182599629637,\n 0.38660531787378677,\n 3.0413218631623335\n ],\n [\n 0.6183472057356971,\n -0.44730960102978035,\n 0.19051512934482218,\n -1.2532549920799407,\n 0.23848614312130123,\n -1.88960755081434,\n -0.6810033351416882,\n 0.0017588353452440142,\n 0.6384563692328009,\n 0.05332522861141675\n ],\n [\n -3.068306001764154,\n -2.060943257262007,\n 0.32415327921345993,\n 1.8844198075179848,\n 0.21187546290828774,\n 1.7034949553039076,\n 1.1572663968869152,\n 0.6793557054651742,\n -3.339541793139369,\n 0.11244425371127043\n ],\n [\n 4.162506368481393,\n 3.4337583519947295,\n -1.9561695090306785,\n -3.091295436280342,\n -2.5776191755150712,\n -4.109282112826818,\n -3.705861744939016,\n -3.9420068933398413,\n 7.094274805136392,\n 2.5532876442963364\n ],\n [\n 1.5096474356312508,\n -0.9200655127453835,\n 0.5134807289131937,\n -0.5565494702717568,\n -0.13637176122713113,\n -1.604804573923664,\n -0.948143159557171,\n -2.2029853388399223,\n 2.3016301847950422,\n -0.36007379638130277\n ],\n [\n -1.141341124062837,\n -5.0088609085295435,\n 2.3793067117784696,\n 0.7733762086029394,\n 2.91052330666514,\n 1.5191019038190472,\n 2.508426882288615,\n 3.6602441801502925,\n -6.068606215457936,\n -4.027923476422912\n ],\n [\n -1.0991573027861248,\n 0.11910701381940625,\n -0.19636756481853235,\n -0.18238798816421337,\n 0.8560859399380136,\n -0.2565710045048871,\n 1.3741940907306025,\n 0.8383542741401253,\n -1.2912257124484157,\n -1.8948915254369463\n ],\n [\n -1.1082974863335862,\n -0.8305646325834413,\n 0.611610179940278,\n 0.8500742495730872,\n 0.5848365973033134,\n -0.10463716784320232,\n 1.2192154664736905,\n 0.18857309939656197,\n -2.6080867681350854,\n -0.9974443058981239\n ],\n [\n 1.058165994905858,\n 3.178314226894435,\n -1.7079211227472677,\n -2.35147675726804,\n -0.9358227246646456,\n -3.202968277870373,\n -1.0131826598732454,\n -0.5982283596178143,\n 1.139896460314427,\n 2.017610950641115\n ],\n [\n -3.1034840600767244,\n -2.9591908379543663,\n 0.7362979681606223,\n 2.0523042471044293,\n 0.7799959145365506,\n 1.9484308337376945,\n 0.8711416335595407,\n 1.1652990490486217,\n -3.152051566707566,\n -0.04003670983112051\n ],\n [\n -2.1110313095472004,\n -2.0001116534102135,\n 0.30719769910236805,\n 0.8564667804217784,\n 1.0031259889141984,\n 1.2196422397406987,\n 1.8362369554588454,\n 1.2298612924029424,\n -3.7861283689432597,\n -1.041021439929495\n ],\n [\n 1.5380671239966057,\n -1.1337905077553563,\n 0.5874756450958143,\n -0.5926404232878383,\n -0.09895649274281015,\n -1.6159694055924776,\n -0.32901643215090726,\n -1.84203238910028,\n 1.5434894787943736,\n -0.5466562119819173\n ],\n [\n 1.9472974252069757,\n 0.8081389970336073,\n -0.14635277710715933,\n -1.505993353909863,\n -0.9388795256525939,\n -2.664108654073769,\n -2.743392052642351,\n -2.637435441164126,\n 4.318778253119695,\n 0.9962414122197165\n ],\n [\n -1.447584822026252,\n -2.253415195342601,\n 2.616577510898666,\n 0.27762712063388395,\n 2.2893943370633854,\n 0.30944754741157476,\n 0.9518567445389852,\n 0.38083414021970086,\n -2.8855316018269845,\n -2.4085413553623716\n ],\n [\n -0.699851499316624,\n -0.5363609942233057,\n -0.20775569499510538,\n 0.10556449596183856,\n -0.5371142811745124,\n -0.22278685284083288,\n -0.5491028451206086,\n 0.40121047585726277,\n -1.1100439023048192,\n 1.0990818163489982\n ],\n [\n -1.2515808603834058,\n -0.6009040017694878,\n -0.681274645754709,\n 1.386562618549144,\n -0.7823053674083651,\n 1.122564843343234,\n -0.15641863607370077,\n -0.7645832782776212,\n 0.08691857705769104,\n -0.29527183553141656\n ],\n [\n -1.9007177684828784,\n -1.9936133966453404,\n 0.3721305839581066,\n 2.2227677175920033,\n 0.028999263924257335,\n 1.92403930658377,\n 0.8757445063602993,\n 0.16716273418541627,\n -2.5123152518367715,\n -0.9180882546145135\n ],\n [\n 2.1052463250590154,\n 2.46305909633127,\n -1.715207682612272,\n -1.388493394502307,\n -1.9807581293029206,\n -3.4273548978641393,\n -1.4481554734864122,\n -2.5998849384172,\n 3.2873246807409777,\n 2.040769976261203\n ],\n [\n 2.498023641411805,\n 0.38108765693055124,\n -0.042755960506039026,\n -1.045676185332348,\n -1.5325895705771506,\n -1.5646603371459604,\n -2.833999838389154,\n -1.5383643237707572,\n 3.1131813093552205,\n 0.3896647550775896\n ],\n [\n -0.1177815144160233,\n 2.0937471786384463,\n 1.8197484884760102,\n -1.2026223398936373,\n 0.19175926560503576,\n -2.0243933096717663,\n 0.5641281257905713,\n -3.9075284782259008,\n -0.9514415052118894,\n 1.4325540836683022\n ],\n [\n 1.0450514492843925,\n -2.358758551754183,\n 1.9796146478101742,\n 0.9993424860678348,\n 0.08242419650654509,\n 0.9829989126575513,\n -2.131531972638082,\n -0.007301046117133669,\n -1.6781802544725724,\n -0.8224390245511436\n ],\n [\n 0.1623418459663486,\n -1.3855616423540553,\n 2.4199888887357814,\n 0.21513426537655225,\n -0.02196998528700611,\n 0.9989354351953585,\n -2.8492100482170875,\n 0.45331496618166867,\n -1.4967488064437526,\n -0.09638604273392981\n ],\n [\n 0.6630195337952347,\n -1.9398292774929615,\n 0.21193622710552606,\n 0.11601230064086082,\n -0.732041440546014,\n -0.9330114482029505,\n -0.570014161205606,\n -1.3321325709627951,\n 2.0178545567203723,\n 0.4768480754002158\n ],\n [\n 0.40229735054219795,\n 1.4242041664550222,\n -1.4077006616901424,\n -1.0698869489146734,\n -0.9312093811987525,\n -1.6671089610920684,\n -1.7998355841336604,\n -0.37293676937527476,\n 0.7600126877999976,\n 2.322552840628881\n ],\n [\n 4.1432921563194105,\n 2.433873990780054,\n -0.9342851432976729,\n -3.032955397659082,\n -1.1605410784424048,\n -4.03265203172831,\n -3.7381062849954416,\n -2.188781390082129,\n 3.8447203282441866,\n 2.8896212159249828\n ],\n [\n 1.5462914642991867,\n 0.5945946958447763,\n 0.42979226097165235,\n -0.885181234099133,\n -1.1534068696296065,\n -1.99794455995016,\n -3.7985333379474975,\n -3.5469942207363685,\n 4.6702800064366645,\n 0.893683488665272\n ],\n [\n -0.504943891815169,\n -0.0896636872694514,\n 0.7445741111136618,\n -0.4081095594040498,\n 0.36138570357913924,\n -1.1504068038222715,\n 1.9065894056609711,\n -1.1421627818635864,\n -1.891195295138735,\n -0.24482144781046933\n ],\n [\n -0.7371187274833517,\n -2.07599936987843,\n 1.2240733810971285,\n 0.41115667113913223,\n 1.5688425139729338,\n 0.0731250801285197,\n 0.8620302460230792,\n 0.5046627698200583,\n -2.103761278188405,\n -2.195404347045992\n ],\n [\n -2.497570098325261,\n -3.2819513264665034,\n 0.34007431613740136,\n 1.964410537811936,\n 0.7989253278231546,\n 1.727002682011776,\n 2.193974915121892,\n 1.7246169526059627,\n -3.7025266289969934,\n -1.0700391438769992\n ],\n [\n -2.067607524182885,\n -0.7500853476402596,\n 0.37628706350524166,\n 0.6321938919809443,\n 1.7040957000616703,\n 0.03840885494808144,\n 2.015879599074129,\n 0.7476625884020136,\n -3.506034598215903,\n -1.603829578728059\n ],\n [\n -0.8717268419906444,\n -2.3314478138830204,\n 0.7280314213477105,\n 1.0748085549067876,\n 0.48410546236155816,\n 0.26131282922620835,\n 0.10668823915793069,\n 1.533415687556086,\n -3.7570742804365693,\n 0.7386975154305748\n ]\n]\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/output_results/mini_nets/cifar10_ub_results_0.004.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n[\n [\n -0.3694920950594116,\n -2.82297402792517,\n 1.5032832773362848,\n 3.438119526378345,\n -0.499213462703187,\n 3.2113777194420283,\n 1.6174257090764492,\n -0.9362230353614139,\n -0.021559673118867695,\n -3.1694013584938907\n ],\n [\n 3.2856284648860234,\n 4.427760002926155,\n -1.5186747779007952,\n -2.4086189390206885,\n -2.774355041635183,\n -3.4279438794140926,\n -3.351430375946289,\n -2.653830842893208,\n 4.884523802106837,\n 4.501718291171672\n ],\n [\n 2.222294970861238,\n 2.8150544767839194,\n -0.7039814330974761,\n -1.0440328125062028,\n -1.8718478696520195,\n -1.8711054142589363,\n -2.8669623665676776,\n -1.7909979827186966,\n 3.7883743621082036,\n 2.5584235203217887\n ],\n [\n 2.8984564956936656,\n 1.2977631586694311,\n 0.4791717161523321,\n -1.1770724507717478,\n -0.3789922944833397,\n -2.1833124298049653,\n -2.313316510117715,\n -1.1044660974284208,\n 2.892837920390435,\n 0.7612142375255688\n ],\n [\n -0.46443936167894945,\n -0.99511148186393,\n 0.48411951338382286,\n 1.8667769316985103,\n 0.8174139040493977,\n 1.3786516852848063,\n 2.5998922303780723,\n 0.30917011810321005,\n -3.0387239922620335,\n -0.684501283177437\n ],\n [\n 0.040235250376206566,\n -1.2153022562160056,\n 1.5870424362109536,\n 0.21257576432041625,\n 2.1096532486794253,\n -0.8584762145994395,\n 3.0672675529084406,\n -0.6470901470227365,\n -0.9980478607436836,\n -1.1593287969657966\n ],\n [\n -0.49298750054063545,\n -1.5902305497446703,\n 1.6490516161072013,\n 2.1378803067957524,\n 1.5246407614920472,\n 1.797925018246457,\n 0.5118676065940275,\n 0.48315936804052106,\n -1.712462022550679,\n -2.1721336549336385\n ],\n [\n 2.439172187645151,\n 3.7220110486196694,\n -0.2404954976984579,\n -1.1896047407197374,\n -1.0398485156101476,\n -2.465078766576061,\n -2.3181996572845196,\n -2.075759169674202,\n 2.71872297425802,\n 1.7410948646296922\n ],\n [\n 2.338526624062262,\n -0.6346941464566629,\n 0.33932662965302474,\n 0.5742827042353056,\n 0.3075919859285605,\n 0.06781440209171552,\n -0.8948391848978661,\n -1.418352141160644,\n 2.237393393293405,\n -1.3886663013476128\n ],\n [\n -0.8313546135063005,\n 2.8143399934063176,\n -0.8993005155452649,\n -0.26478724322380465,\n -1.8020858559693798,\n -0.8507292806232447,\n -0.7119224539257432,\n -0.014753078614925141,\n 0.22496914036387902,\n 4.062164777075975\n ],\n [\n 0.6570624274302554,\n 3.3210463927367266,\n -0.2375519434026434,\n -1.126889067040501,\n -1.7697291427984951,\n -2.261273554829592,\n -1.8146901066777232,\n -0.41407380058246024,\n 1.366950551399717,\n 3.8316399436356168\n ],\n [\n 1.1309342256117108,\n -0.15488378914698797,\n -0.023797666980097,\n -0.018305315657143384,\n 0.36121909405391617,\n -0.054709390720483864,\n -0.06966385016365484,\n -0.2181106093610108,\n 1.405469045420103,\n -0.662866299252373\n ],\n [\n -1.4111404167781834,\n -0.4648446269948886,\n 0.25937685454644455,\n 2.0593122848209426,\n -0.6454797655733682,\n 2.3692799931146826,\n 1.152036294753174,\n 0.4809121560404068,\n -1.1457152050883044,\n -1.3622589528022688\n ],\n [\n 2.5167436567660086,\n 1.7935276688230775,\n -1.2108537110171769,\n -1.794585755080723,\n -1.8367178148259926,\n -2.97196030843826,\n -1.9088786374320268,\n -1.91990071976295,\n 5.5779446823524905,\n 2.7028728256552297\n ],\n [\n -1.6354911620542754,\n -2.1966623766566418,\n 0.7688168216501043,\n 1.5158138516072677,\n 1.7547373158534312,\n 1.4467630976937076,\n 3.4007356521909466,\n 1.5756044838717114,\n -3.419849869333906,\n -1.224198984574422\n ],\n [\n -0.6868396010122583,\n 0.5963567027939884,\n 0.5518497743692226,\n 0.21013559858939346,\n 0.8187656802544221,\n 0.7959044609109132,\n -0.8392248882171645,\n 2.9046939046871674,\n -2.9474317422118053,\n 0.3558157630947587\n ],\n [\n 4.526324966455808,\n -2.4207327143558754,\n 3.210181476221829,\n 0.09440054199683912,\n 1.2237557678612823,\n 0.9548152777666885,\n -4.423667584118382,\n 1.267264696916346,\n -0.10624117468875077,\n -3.062562395756912\n ],\n [\n -1.2477183048158544,\n 4.679298105224816,\n -2.4610777668589217,\n -0.5432389118446161,\n -1.0787705065435467,\n -0.9092838554001533,\n -0.13078282647105977,\n 0.8552861448003442,\n -1.8408733151260686,\n 5.00623238408999\n ],\n [\n -0.6996964624077815,\n 3.093246766051792,\n -0.866672675004545,\n 0.7019909056263614,\n -0.8419722945223325,\n -1.0673600026683823,\n -1.6894653463417453,\n 0.3531776079648261,\n -1.810534426553652,\n 3.941304321456772\n ],\n [\n -1.1900935950589375,\n -0.6010268992819322,\n 0.9028026347274984,\n 0.4431807404983612,\n 1.5404774214969177,\n 0.6003938984150241,\n 1.8006538871961795,\n 0.8922362185160368,\n -1.9745421421860918,\n -0.23960817913240406\n ],\n [\n -0.9392559138639188,\n -0.08793815235576041,\n 0.8045887530534235,\n 1.5556549724988464,\n 0.9467156341710272,\n 0.6909697778696615,\n 2.100952284903773,\n 0.7802319945048406,\n -2.88230831009549,\n -0.48998360783511885\n ],\n [\n 0.7994316613758379,\n -0.1673085128085885,\n -0.16216325222009886,\n -0.05207430567595728,\n -1.0228813106819894,\n -0.732359451197344,\n -1.9823586883882003,\n 1.135695427012379,\n 0.5504715889164097,\n 3.0177140406104783\n ],\n [\n -0.6011463311189723,\n 2.450651899232015,\n -1.1113817127263572,\n 0.30279808901389094,\n -1.0463632977888913,\n -0.0638685906060873,\n -0.3421587715447605,\n 0.07173086138623619,\n -0.827134712610194,\n 2.852998869002919\n ],\n [\n -0.748522254283003,\n -1.4070186374196127,\n 1.6526546655655363,\n 0.48743242630564354,\n 2.0934494355788194,\n -0.07596224950600639,\n 2.71211328321147,\n -0.4411413743407019,\n -1.2249171158614696,\n -1.2468838715214776\n ],\n [\n -1.5057486732246286,\n -0.9313952339394588,\n 0.9898311905461764,\n 1.5323777339147109,\n 1.6508255195988406,\n 0.7121485734613875,\n 2.6557558629824425,\n -0.05254403002767116,\n -2.3456950150979834,\n -1.0311758151050228\n ],\n [\n 5.2397377036706905,\n 3.353087735162841,\n 1.257285411024096,\n -5.276631873455348,\n 1.8637519442272528,\n -6.692580717945743,\n -6.611851440964056,\n -0.28380081042660243,\n 4.766068517191299,\n 3.119978787132032\n ],\n [\n 2.1041170668635765,\n 1.3963634249026549,\n -1.0601443044361698,\n -0.5570533201137663,\n -1.500433535880393,\n -0.8838023341741023,\n -2.720853721111885,\n 0.17228910951671006,\n 1.1388843614128745,\n 3.17368751022025\n ],\n [\n -2.756261768250733,\n -3.065095684988486,\n 1.2076511285427327,\n 2.7916542058226894,\n 1.4439214898867145,\n 2.615184073724901,\n 2.758560774265803,\n 0.9699392459513851,\n -2.5640904551586465,\n -1.005840925113131\n ],\n [\n -0.20865796693109723,\n -0.7350994643548328,\n -0.4228161965159849,\n 1.0313690472459986,\n -0.6303095464725397,\n 0.46255335191626634,\n -1.3632335919581262,\n 1.276201558956561,\n 0.7021803683108298,\n 1.937704904937608\n ],\n [\n -0.7205793953242827,\n -1.5422221841006383,\n 2.7841804087844793,\n 0.3096289802166895,\n 2.6433806631088856,\n 0.15044735900432693,\n 2.957054054841854,\n -0.09022832321262031,\n -2.9159660374131344,\n -1.6330340746980203\n ],\n [\n 0.3052719671351126,\n 1.5272731061089058,\n -0.0643536327126899,\n -0.6577637061477613,\n -1.0311600240673449,\n -1.5313927353319658,\n -2.450022904176157,\n 0.2554357002800578,\n 0.8935301005963662,\n 3.410031728373964\n ],\n [\n 1.031925672732753,\n 0.11727221281804445,\n 0.5012787004092036,\n -0.8952456844242715,\n 0.5336484310415139,\n -1.4890395852732556,\n -0.26522329641431397,\n 0.4499537134443303,\n 1.1761701709433892,\n 0.4982564425109408\n ],\n [\n -2.6587305252335973,\n -1.4722330941785027,\n 0.6560188941216255,\n 2.213968412397792,\n 0.4919953927007614,\n 2.061500946426033,\n 1.5008995049143325,\n 1.1045957917965303,\n -2.77245813697127,\n 0.5209745536460497\n ],\n [\n 4.531031629128636,\n 3.931024897794776,\n -1.6587684251502126,\n -2.7216835569999556,\n -2.2894247403901047,\n -3.6868221199049707,\n -3.339266204528286,\n -3.5637573849904327,\n 7.51239675827874,\n 2.9653934146374183\n ],\n [\n 1.8390691191472213,\n -0.4244909746096549,\n 0.7637577449605241,\n -0.28709023050663274,\n 0.1527184852448633,\n -1.2867194175373566,\n -0.6226836389737471,\n -1.8137679378221896,\n 2.802527770521195,\n 0.03124957531071937\n ],\n [\n -0.7371289937930249,\n -4.425340742611278,\n 2.7339316426546976,\n 1.129994784386588,\n 3.2328173386791685,\n 1.962543842296788,\n 2.8189482488060875,\n 4.233738383896127,\n -5.465939653396594,\n -3.554967349123594\n ],\n [\n -0.7167087405883108,\n 0.6639465736089276,\n 0.12002861833666634,\n 0.13956848902251803,\n 1.1639297171721443,\n 0.14246347425480743,\n 1.7043051350679481,\n 1.288322111613482,\n -0.8379463215979357,\n -1.4703032993535372\n ],\n [\n -0.6562695185378141,\n -0.24541846379191024,\n 0.9495447118525215,\n 1.2209136347401734,\n 0.8801829329538319,\n 0.317921954147367,\n 1.5876629701726617,\n 0.7016285756484928,\n -2.0429199920359236,\n -0.5729565245893711\n ],\n [\n 1.4469882197722632,\n 3.6862854833556673,\n -1.3928512037898404,\n -2.0564067863997586,\n -0.6194564927714112,\n -2.851716761469572,\n -0.6897022780682116,\n -0.17204399529336234,\n 1.6753410778266573,\n 2.4445062330537684\n ],\n [\n -2.7734775145727,\n -2.4481694785642616,\n 1.0090210222994265,\n 2.3570690693383223,\n 1.0003790278522284,\n 2.298104781538136,\n 1.1613894770673168,\n 1.5667008869575318,\n -2.6382475427830347,\n 0.3237448054977199\n ],\n [\n -1.6538141811888973,\n -1.3324439965408708,\n 0.6572676022896399,\n 1.229240343028187,\n 1.3149961715886278,\n 1.6388359184894772,\n 2.2010146293524144,\n 1.6737224172003065,\n -3.162904459040498,\n -0.5888070671338114\n ],\n [\n 1.8747691851190518,\n -0.6074978871411499,\n 0.8284193747150747,\n -0.28493789901992017,\n 0.15084163952656438,\n -1.2577272192368831,\n 0.018262235051647258,\n -1.4664371881387621,\n 2.097187535934339,\n -0.1954346608527331\n ],\n [\n 2.3704585301478724,\n 1.387154430678792,\n 0.16494355073787537,\n -1.1333489799919378,\n -0.6295020364139994,\n -2.240910497151611,\n -2.3719279998823786,\n -2.2296390379710522,\n 4.815438811356803,\n 1.3997309006301193\n ],\n [\n -1.1258789258159811,\n -1.7710343639376158,\n 2.8989972912590267,\n 0.5737789276038872,\n 2.57801996583507,\n 0.7056137400062419,\n 1.291474987597842,\n 0.9098927461535704,\n -2.361712431895244,\n -1.9963318684951812\n ],\n [\n -0.32723084973880023,\n 0.012099452323155013,\n 0.07672757930396612,\n 0.4445561268020133,\n -0.25091031315472034,\n 0.1760226876280846,\n -0.13627701027256656,\n 0.9017511959364894,\n -0.5656444399501016,\n 1.5032711575084017\n ],\n [\n -0.8360866353969051,\n -0.015783411993397056,\n -0.3709748454030397,\n 1.7022371481475247,\n -0.5161326272167504,\n 1.4624803634102035,\n 0.18411362675577103,\n -0.36748572168601046,\n 0.6083305862679305,\n 0.10144424756359349\n ],\n [\n -1.5171875929810543,\n -1.4602670946302494,\n 0.6540138725020764,\n 2.547733111683097,\n 0.3090465713520971,\n 2.297941081717211,\n 1.193443659615034,\n 0.6224007119776571,\n -2.030196775754159,\n -0.5125539919414481\n ],\n [\n 2.3763546945634793,\n 2.9081045893221162,\n -1.4778191627117736,\n -1.1464936089801074,\n -1.7526022790985687,\n -3.130311997501897,\n -1.1524427331732512,\n -2.2847464071808075,\n 3.6847368494064265,\n 2.348927008617456\n ],\n [\n 2.869889882313979,\n 0.9144665594104484,\n 0.2028367110111804,\n -0.7080021036227736,\n -1.2339458145314763,\n -1.1869560105376993,\n -2.464937628010283,\n -1.1430293938058458,\n 3.6761358297651046,\n 0.8067014617695341\n ],\n [\n 0.2246407397567557,\n 2.6194773233313673,\n 2.1713999405579716,\n -0.8862223245440612,\n 0.4671792935358323,\n -1.6172400517813914,\n 0.9004720471234594,\n -3.420064274805487,\n -0.46364610405631157,\n 1.8459999661213766\n ],\n [\n 1.3925205247488273,\n -1.8695406976484623,\n 2.2086631060202704,\n 1.2797214666906167,\n 0.33615461044932426,\n 1.306600064653347,\n -1.8009998409482226,\n 0.32503659953034925,\n -1.179714938287768,\n -0.49065093928435166\n ],\n [\n 0.5288751317086804,\n -0.8289254055552376,\n 2.738219337578573,\n 0.5910555330747984,\n 0.24911479364908784,\n 1.388717734717242,\n -2.479369231620057,\n 0.8105135138855046,\n -1.0154668519104066,\n 0.3289646558386301\n ],\n [\n 0.9885259176673691,\n -1.4329606893449478,\n 0.46934721723642747,\n 0.40959306170153026,\n -0.4705444414793747,\n -0.5885088345911784,\n -0.2590008827043955,\n -0.9870721872754241,\n 2.5658843266325815,\n 0.8327455944792268\n ],\n [\n 0.7905192586910723,\n 1.9977872342853948,\n -1.0998270983668035,\n -0.7327501434655481,\n -0.6346887230745697,\n -1.2824683522677789,\n -1.394982053566161,\n 0.09294473926540503,\n 1.36638975911214,\n 2.7556640749526\n ],\n [\n 4.517479792172791,\n 2.9713675753851647,\n -0.6307148798311188,\n -2.6790561209696286,\n -0.862904856034362,\n -3.6279623454879815,\n -3.3515064981935723,\n -1.755894902642897,\n 4.376913457473097,\n 3.3005077528489046\n ],\n [\n 1.8824798215014948,\n 1.1270908281284033,\n 0.7224641469260635,\n -0.520360517815348,\n -0.8616148741838856,\n -1.6075155352945676,\n -3.420000561345727,\n -3.126208483709655,\n 5.1960509700232,\n 1.2973319371236682\n ],\n [\n -0.10563935384356654,\n 0.44598410813692446,\n 1.0716674392630445,\n -0.04589514409154111,\n 0.6624194465019368,\n -0.6924114548366398,\n 2.2153154144735137,\n -0.5863136617474104,\n -1.2941842883369261,\n 0.23418511307998102\n ],\n [\n -0.32660488787875824,\n -1.502326406067377,\n 1.5243150910549836,\n 0.756104118262369,\n 1.8923801966626244,\n 0.5145751795271227,\n 1.226543645633887,\n 0.9920367897770643,\n -1.508501777665488,\n -1.7524927393663468\n ],\n [\n -2.087012117082094,\n -2.6578063408447297,\n 0.7012776234076402,\n 2.3307872370585563,\n 1.085464053610602,\n 2.131132852815129,\n 2.5457161337677214,\n 2.1778771706016524,\n -3.076401583915081,\n -0.6381233816817958\n ],\n [\n -1.6015133851895094,\n -0.12145265198348953,\n 0.7458210401797111,\n 0.9865948911078644,\n 2.0008206716540804,\n 0.4532257486602902,\n 2.3550736306152196,\n 1.239157922802352,\n -2.9081184048958018,\n -1.1687137735588569\n ],\n [\n -0.5058340767426799,\n -1.7417372588900795,\n 1.027025075784352,\n 1.4202138772431943,\n 0.7540804782985004,\n 0.6274275257588553,\n 0.4289407538136467,\n 1.9216308177644175,\n -3.211273261517303,\n 1.1866933548467853\n ]\n]\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/output_results/mini_nets/mnist_lb_results_0.05.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n[\n [\n -5.739041410180254,\n -13.489921103636819,\n -5.391637409621392,\n -0.6668617798228719,\n -6.358164257978781,\n -3.5359849508462764,\n -14.797269647311706,\n 5.406469074085281,\n -4.900504951501633,\n -0.4847123227386557\n ],\n [\n -1.6999071889390038,\n -7.551370949168961,\n 4.340454487420221,\n -2.0111126481747434,\n -15.972478933322817,\n -3.753529260203317,\n -0.1184708911585991,\n -23.774418641337686,\n -4.124559581147418,\n -17.78417786266268\n ],\n [\n -7.827782099760742,\n 3.952382829572655,\n -1.4722414278975668,\n -3.066330562298918,\n -1.9247116641489415,\n -4.362957184223783,\n -3.107493581593339,\n -2.2127316391427474,\n -2.8210074580253424,\n -4.259013691829756\n ],\n [\n 3.9241387708064157,\n -18.58459006447502,\n -4.3187138864776236,\n -7.075355514936785,\n -9.489369220931598,\n -3.9959090741348033,\n -3.365049325797384,\n -5.09361465300258,\n -5.059405010244529,\n -5.889578862399114\n ],\n [\n -4.51242358753631,\n -11.215260392391892,\n -3.806408064474631,\n -7.792324070912637,\n 2.8743686569145894,\n -5.802317453418741,\n -3.9777123827490577,\n -1.5688794050186454,\n -4.229577211517941,\n -0.5720250856518209\n ],\n [\n -9.637840110256402,\n 3.9791907730381877,\n -2.1220224407183084,\n -3.748071301994508,\n -2.3348266582369774,\n -6.013559514620253,\n -5.001355212616135,\n -1.201161329622604,\n -2.304638197531707,\n -3.534510818074425\n ],\n [\n -9.342505237159907,\n -8.028640255199962,\n -7.307083339758329,\n -4.648443505433024,\n 2.267989890411252,\n -3.957443936632095,\n -7.295392031432559,\n -2.7418727819890156,\n -2.153862415271541,\n -2.502427623132524\n ],\n [\n -12.715978943545311,\n -6.724477197628045,\n -4.881394397302798,\n -4.078355384716535,\n -0.9710117469539645,\n -2.7609016515400784,\n -7.273642922322769,\n -5.1982107577678,\n -3.4005679193527727,\n 0.8075303973354212\n ],\n [\n -9.665513912799971,\n -16.485911462750213,\n -9.477216700643746,\n -7.369935214084349,\n -2.5078005099169642,\n -6.643652584264652,\n -13.544494469224038,\n -0.7149460635763014,\n -2.9539097772257668,\n 2.4393782290436303\n ],\n [\n 3.463577385211841,\n -17.05651196081425,\n -3.0739874567692924,\n -5.081963470351714,\n -9.852999033977486,\n -3.236441599976211,\n -5.285499452882112,\n -9.635246823137011,\n -3.710972834088019,\n -8.287837755655291\n ],\n [\n -6.098846976430872,\n -11.494354500835941,\n -3.7371607301715044,\n -6.427637178356297,\n -7.142718909109326,\n -6.228770962178707,\n 1.7680523240434698,\n -12.114802030813708,\n -3.9778435164785564,\n -9.902238780000697\n ],\n [\n -9.273851207709546,\n -12.124368356931342,\n -7.6700307692404035,\n -4.778947648018846,\n -0.4672778565526706,\n -5.256039593358759,\n -9.957547965365446,\n -1.443422546638132,\n -2.7359324160479264,\n 2.8527532363683448\n ],\n [\n 4.420290410054627,\n -17.123108858738714,\n -5.59149279632167,\n -7.734947961402138,\n -8.063133092801559,\n -4.172322189081314,\n -6.6392090057923685,\n -5.190921949546287,\n -2.8744232904398914,\n -3.732510863983823\n ],\n [\n -10.652122660989004,\n 4.325237987724612,\n -2.1902285440419944,\n -1.1652737278785508,\n -4.2276043878686,\n -4.041263125786388,\n -3.7191877602623906,\n -4.714008507957449,\n -2.2180801821579106,\n -3.537210276727144\n ],\n [\n -6.024591309201172,\n -8.794506491304217,\n -4.818073307094211,\n -1.0698575603416156,\n -6.506880633561024,\n 1.8633862305330577,\n -5.576033292230156,\n -9.892268095165681,\n -2.2381113326126596,\n -9.404456527712345\n ],\n [\n -5.933008640828387,\n -14.160233482855618,\n -5.121356354224595,\n -6.722152633882806,\n -1.0054943805824863,\n -6.78243314516547,\n -8.057191514140174,\n -0.2443239234877665,\n -3.342004702996101,\n 2.4712739881954757\n ],\n [\n -4.650387411788153,\n -17.87819488231845,\n -4.741483690777442,\n 1.0081947535465572,\n -7.778733011263284,\n -3.4633672531315067,\n -14.656640066600756,\n 6.040500888084519,\n -5.54173445395643,\n -1.8252511083156635\n ],\n [\n -10.139487910699978,\n -14.48458264560521,\n -3.074637421021967,\n -1.320718739046286,\n -8.436155119956618,\n -3.047784642892062,\n -5.868736030849743,\n -12.575266453085376,\n -3.4149118203936877,\n -10.583422688868483\n ],\n [\n -7.018094315177488,\n -9.620653411332395,\n -4.934670597073159,\n -4.810787892756673,\n 3.8565059922316007,\n -4.939003352736314,\n -5.034272688843999,\n -3.352494012296462,\n -3.389760113746425,\n -0.21769769496884206\n ],\n [\n -6.778969734508099,\n -9.086095037680003,\n -9.018052501637229,\n -3.0527150097914437,\n -2.120414017442738,\n -4.6449387856775015,\n -14.818763411853501,\n -1.4647045521702282,\n -3.204483278776956,\n 2.353366198431329\n ],\n [\n -5.416962569585719,\n -11.9189219507129,\n -3.805422678588128,\n -5.493172964011174,\n -4.1613087350950435,\n -1.224393449105907,\n 3.160745657292899,\n -13.99171847156464,\n -2.6547789509226734,\n -7.504249736276326\n ],\n [\n -8.737151385494936,\n -8.844609855676566,\n -4.61115071728743,\n -8.14548284736561,\n -1.8680087679064314,\n -7.938585764453503,\n 1.5068192659922093,\n -4.303970667940605,\n -5.337614445194425,\n -5.14596727560263\n ],\n [\n -6.2035220849611346,\n -9.483511919302986,\n -5.359958785923341,\n -2.533321444838293,\n -3.745692642303293,\n 2.387480766484744,\n -3.5670697273429988,\n -8.975017640503008,\n -1.9092777653273467,\n -5.317025182588788\n ],\n [\n -6.3036050864634925,\n -6.121099915099243,\n -4.03960067346118,\n -4.478181984454759,\n 1.8259604656410804,\n -2.712005423468153,\n -4.042784618209722,\n -0.8252790361336237,\n -4.757825710682888,\n -0.5122162378244708\n ],\n [\n 4.109415442795427,\n -29.531473617869196,\n -6.395972063887287,\n -13.536258981582277,\n -8.42009065131485,\n -6.069441287926837,\n -2.8198537878154024,\n -11.069279056437002,\n -5.146373490721101,\n -9.285972197098518\n ],\n [\n -5.04162877791791,\n -10.887318332165131,\n -4.175154825402548,\n -1.8997665950794749,\n -4.6395907066566755,\n -3.4835497103588042,\n -10.933348926155002,\n 4.198729199321783,\n -5.1281274165078745,\n 0.8784610983165815\n ],\n [\n -7.576974842441992,\n -12.724208653484139,\n -5.527932121153686,\n -6.321117546206244,\n 3.679448461967158,\n -4.841491025130358,\n -5.053153729515385,\n -4.886161312359567,\n -3.6264437635849194,\n -0.20225058684232977\n ],\n [\n 4.758965279547732,\n -16.773795548160557,\n -3.376214203761754,\n -3.5478224212922806,\n -11.068651308829745,\n -4.16937979175664,\n -7.782109801833843,\n -6.3238719552463705,\n -2.986185404268124,\n -6.196522760433062\n ],\n [\n -9.186376715353155,\n 3.4127832428403018,\n -3.4364053257199325,\n -2.271742553675114,\n -2.8157369170109465,\n -1.3854204274288746,\n -3.010857253603481,\n -4.407942978558633,\n -2.2519222908045706,\n -3.4516572249620454\n ],\n [\n -8.705812724560317,\n -12.227248531247573,\n -7.049602188673286,\n 4.199892791483271,\n -7.789637411135691,\n -1.0636748383136803,\n -12.852279536568869,\n -2.504122918918905,\n -3.4503100111315184,\n -1.9027045496093509\n ],\n [\n -9.253724618307372,\n 3.530890036054349,\n -2.7320924445265082,\n -1.2755926080717597,\n -2.121757488018762,\n -2.057717826505843,\n -4.199431645683737,\n -1.0309117837626478,\n -3.2614951989238308,\n -2.225081097160545\n ],\n [\n -7.938903124086021,\n -12.510165275157929,\n -5.908454784866423,\n 3.866481104747077,\n -5.958423430681047,\n 0.2326880981877131,\n -10.917936335689404,\n -9.46270299422179,\n -1.4994400005457365,\n -4.856887591833989\n ],\n [\n -1.6860724817978654,\n -18.385601505285667,\n -5.691503491433684,\n -13.971086405758864,\n 0.3047258471706728,\n -3.473280490593168,\n -1.7948614853869154,\n -7.720931076388515,\n -6.099422886184837,\n -7.484172215401726\n ],\n [\n -8.04114964438501,\n -8.48501181228692,\n -2.5048254976903612,\n -2.7821840548638828,\n -5.624720516003457,\n -8.535083468317975,\n -16.70774854508461,\n 3.467600737168041,\n -3.4698728524344102,\n -1.3340287067783259\n ],\n [\n -4.3111387403585395,\n -9.71015008453802,\n 4.39041979198578,\n -1.6829613768987166,\n -10.520787570681797,\n -6.09906453535686,\n -8.801440920458385,\n -13.9958091471917,\n -3.477003338007882,\n -13.021809313838245\n ],\n [\n -5.667024709909426,\n -8.698426084756127,\n -2.383155080805302,\n -1.6373259735334482,\n -5.7185207683843995,\n -6.7770261751958465,\n -10.885210430979638,\n 3.9866517230956737,\n -4.043505693410018,\n -1.0878027850438363\n ],\n [\n -11.05645524339405,\n 4.34406517026969,\n -3.559131815850391,\n -2.3116924650698643,\n -2.973258069341991,\n -2.791360057856636,\n -5.0123595849082925,\n -2.140114469121564,\n -2.3103301519239583,\n -2.6484009185946484\n ],\n [\n -2.8771156321847142,\n -2.7899406310422563,\n 1.243150774642056,\n -1.1350216221590208,\n -10.512771849742423,\n -3.189993204913157,\n -3.1711033619917854,\n -7.429169938368218,\n -2.072732169987452,\n -8.24962404927857\n ],\n [\n -9.033660858825064,\n 3.7365620648682834,\n -2.908550204084503,\n -2.003081494384287,\n -4.79253805941056,\n -4.372064438247558,\n -2.265532622912218,\n -6.986582780503687,\n -0.5934869652545601,\n -4.790163036506937\n ],\n [\n -6.30936924051858,\n 3.896073165547115,\n -1.5386428701746708,\n -1.9491761846008413,\n -2.4385558481712803,\n -1.5121305192627699,\n -2.2577308343444242,\n -0.959483087900078,\n -3.219377518740381,\n -2.3852483384267966\n ],\n [\n -6.387747269953656,\n -7.317552000631561,\n -2.059082025355382,\n -1.8544759087650065,\n -4.525831966311079,\n -4.808207459075481,\n -8.848902583830972,\n 3.172407630818587,\n -4.891838683150219,\n 0.04774537322597921\n ],\n [\n -13.029897014880165,\n -7.823399835436758,\n -8.471434202840156,\n -6.043227372160082,\n 3.9617456664177184,\n -7.443690717849231,\n -8.698169502109709,\n -2.391478186734941,\n -2.893054350562802,\n -0.5672259865673136\n ],\n [\n -6.0880157653205575,\n -2.3727227982355656,\n 0.9524982537192911,\n -2.98393143713832,\n -4.608096198000232,\n -3.5662323168994337,\n -3.546511110553921,\n -8.570518863731062,\n -2.7562246050517785,\n -8.089346025054853\n ],\n [\n -8.328022363130412,\n -5.757406132357643,\n -3.1157080657336635,\n 0.9424966418109769,\n -5.113055833093626,\n -0.8352860861811855,\n -3.1262795855759107,\n -6.788805707034086,\n -2.961073374664752,\n -4.476592292176468\n ],\n [\n -3.6737955612421205,\n -12.054848992744732,\n -6.341081593283634,\n -1.191841717965024,\n -6.3121762542555615,\n 2.132247009633691,\n -5.153960554288475,\n -8.064369311443974,\n -0.9692988595016155,\n -3.5786434350436953\n ],\n [\n -12.536417959391022,\n 1.7749857295917162,\n -2.3829514756851364,\n -0.9391575574412261,\n -2.9378769868608514,\n -2.1784859089754596,\n -5.126422547298851,\n -4.219085489144391,\n -2.634013823777452,\n -4.104279189324114\n ],\n [\n -7.55603876144435,\n -4.840469875249788,\n 2.9599420221321044,\n -2.283114704222573,\n -7.297184738228846,\n -6.064423877469445,\n -2.6814339292394402,\n -10.442800120107893,\n -5.704707928490945,\n -9.629417844367772\n ],\n [\n -12.114023389226249,\n -16.54283231911138,\n -10.078707806810485,\n -6.440180207602838,\n 4.329340089527039,\n -6.563108379378051,\n -11.712899626202734,\n -6.171936701094317,\n -2.1073504230698283,\n 1.2908350290471657\n ],\n [\n -6.478211633180821,\n -13.811517821586174,\n -4.475410710695743,\n -7.918962401874359,\n 3.7580442470666964,\n -7.630392621041,\n -4.83148733683002,\n -2.4433870517627256,\n -4.085376543036049,\n -1.1113417420494718\n ],\n [\n -2.088598213746363,\n -11.968778124859114,\n -3.5652836374860057,\n -3.345865137939947,\n -4.573080021528986,\n -1.6610048183284318,\n 4.119902449656644,\n -11.216823829816676,\n -3.4217868340288082,\n -7.415879640067485\n ],\n [\n -6.74861525992107,\n -16.446964410845794,\n -2.8639490454731487,\n 2.58166790898603,\n -11.684133922648572,\n -3.134472306341342,\n -6.946699027748149,\n -9.710068784742187,\n -3.7619246723641893,\n -9.05328295846884\n ],\n [\n -6.127949477373676,\n -12.266522825558125,\n -7.839178281833323,\n -4.296479036212941,\n -3.0083041450841495,\n 2.2048241240534967,\n -5.365637580729996,\n -6.8697778631671325,\n -2.9387135352960865,\n -3.3591063930654688\n ],\n [\n -6.286605565317822,\n -8.628664765248688,\n -5.32991176133253,\n -0.174591698951086,\n -5.379874838780349,\n 1.4031160224031092,\n -4.280371494411112,\n -7.473111717753334,\n -3.072335944385583,\n -4.666872585918678\n ],\n [\n -8.928231749084963,\n -16.05807299728325,\n -4.50038064970109,\n -10.505566034822825,\n -8.909367144562326,\n -8.30446071669314,\n 3.702209242101107,\n -14.385265378769656,\n -4.341242271517439,\n -16.521377671498534\n ],\n [\n 4.072015081162871,\n -15.03755013215672,\n -4.062536975180043,\n -5.059920071319336,\n -6.968772281919088,\n -3.291329920045567,\n -5.664750189040719,\n -8.092734712025727,\n -0.16415092477946608,\n -5.241098698957419\n ],\n [\n -9.04177602063436,\n -19.623174874026393,\n -6.461526292717023,\n -7.96190817786061,\n 4.628108043893345,\n -6.224268785476329,\n -5.4696331678664,\n -5.565570981385855,\n -3.5202207027532966,\n -2.6171796950790536\n ],\n [\n -8.063306030128114,\n 3.635017786923056,\n -2.116561742766116,\n -2.6729991163619125,\n -2.359070148543411,\n -4.704405501782069,\n -4.96964880153147,\n -1.082348195675092,\n -2.7502523494099185,\n -2.8402126289858534\n ],\n [\n -10.125015153321728,\n -16.842463083241654,\n -7.621207671497696,\n -5.777808674713026,\n -1.8219643679360344,\n -4.413415906410686,\n -10.79002739281621,\n -0.8231482617939034,\n -3.7935924223433464,\n 3.0338403610231333\n ],\n [\n -3.1495220935437827,\n -3.724741937720689,\n -6.785224477825897,\n -5.115729792121762,\n -2.1824131970846268,\n 0.7626080463515962,\n -7.573874253401498,\n -1.6027218970398125,\n -3.5669242373382644,\n -3.719232591973688\n ],\n [\n -10.87849000538773,\n -14.681017009672424,\n -4.6645563710458235,\n 1.1433256323841932,\n -6.525265164571842,\n -5.268318365759996,\n -14.95798883620007,\n 5.913743417685296,\n -5.657900113698658,\n -3.695461263078331\n ],\n [\n -7.06824682949268,\n -16.832336825862306,\n -1.7722407717058397,\n -6.110207301450279,\n -8.900196872584324,\n -4.223775760743008,\n -5.279936287026133,\n -10.431008988286518,\n 0.4594702559059047,\n -3.7815915501299777\n ],\n [\n -6.727030558009833,\n -7.480889031112938,\n -3.687079816665549,\n -4.928027836933339,\n -2.298408629366841,\n -0.7883743286084859,\n -3.925099050594414,\n -1.5743836595273488,\n -2.12601551706016,\n 0.31888209166169285\n ],\n [\n -7.757590362281623,\n -6.475651071251881,\n 0.6585343461300748,\n 1.3629970368435282,\n -8.27156949984422,\n -4.618155640356794,\n -7.630748385811376,\n -10.280487758097346,\n -2.4017603250809914,\n -4.631405001317533\n ],\n [\n -12.506921457529197,\n -19.038096418691016,\n -4.949182984764483,\n -1.684351343063019,\n -5.886111544713403,\n -6.81657895697437,\n -16.210118325398426,\n 2.3184287127032737,\n -5.381983111235751,\n -2.4036376830091712\n ],\n [\n -6.023622682378005,\n -3.4505825655167977,\n -4.789872621217483,\n -1.9521411924290013,\n 1.5688145697863207,\n -2.326593634878334,\n -3.1397083156718955,\n -4.280350299063732,\n -2.589478093442848,\n -1.0876288983699813\n ],\n [\n -5.504085091723479,\n -10.465016644717863,\n -2.6591746030208836,\n -5.944607115082631,\n -4.874700954945726,\n -7.972446844942297,\n -2.1443266089484507,\n -4.795278676613273,\n -5.840261807522633,\n -7.15638566856568\n ],\n [\n -6.358376953232942,\n -9.24628154289088,\n -5.216909386683965,\n -8.358054539527465,\n 3.5418461150866114,\n -8.113803456921463,\n -5.325586971311065,\n -2.585517243554269,\n -4.704112112048466,\n -1.650341773326483\n ],\n [\n -9.405809406537895,\n -12.904784427112618,\n -4.257971419173858,\n 4.202258734154726,\n -8.51656023555442,\n -2.196956275123628,\n -12.11437316893145,\n -7.831771215137778,\n -0.8545073610808817,\n -3.56002906500227\n ],\n [\n 4.600189694915761,\n -17.006168900011023,\n -4.560350932839821,\n -8.857618524236837,\n -12.676041325513651,\n -2.3442662017918683,\n -2.214752977489813,\n -7.121244342912603,\n -6.599578324082183,\n -9.733708686851148\n ],\n [\n -4.384465690260855,\n -16.591764227900967,\n -4.0392639485221355,\n -0.025365531276088024,\n -7.447965965242684,\n -6.107761653690256,\n -14.187749069343045,\n 6.463218192901054,\n -6.006286883673829,\n -3.0040941630894515\n ],\n [\n 5.734175536564301,\n -22.619812868666124,\n -3.6072549466807957,\n -9.07457294295478,\n -13.160953266811312,\n -4.955084720227756,\n -4.021924610426497,\n -13.56946944282849,\n -3.6166515341849186,\n -9.948399997681708\n ],\n [\n -1.734422415651456,\n -13.971287156351847,\n 2.8927375661317503,\n 0.2339538258742979,\n -9.408450305704132,\n -4.888816860309703,\n -8.099794577348874,\n -12.05754225521911,\n -3.167183058464264,\n -12.207630430782066\n ],\n [\n -11.077489359508828,\n -4.473167402919609,\n -6.366630544713796,\n -4.325050286593944,\n -6.317827905507596,\n -7.560005348178872,\n -15.521991814660037,\n -0.40029670553460506,\n -1.2209193240416722,\n 0.10775996217516204\n ],\n [\n -10.291558060185197,\n 3.5476022376086114,\n -3.7364216708863056,\n -2.329824952931869,\n -3.3893304293981954,\n -2.5066663631933377,\n -4.5825495256729,\n -3.2596166773900044,\n -1.4474675332315359,\n -2.3490191484602847\n ],\n [\n -13.693353452399078,\n -7.240153255520626,\n -4.467145533998059,\n -2.9560377156284923,\n -3.838295226756692,\n -5.084429505878569,\n -11.876103644620992,\n 2.9446966270003503,\n -3.095567642139351,\n -1.6901613670062605\n ],\n [\n -6.403005188199651,\n -5.068627448753278,\n -4.112464278679524,\n 3.2808026350757182,\n -5.417093673854331,\n -0.039315775854428664,\n -6.117826351078394,\n -9.327095058006988,\n -2.0100202075228473,\n -4.849998110885772\n ],\n [\n -5.070049560947079,\n -4.917869049694856,\n 0.6505824072731577,\n -6.032162453559916,\n -5.521774207837508,\n -5.687314403050027,\n -6.131198279786867,\n -1.685429920411965,\n -4.450177889142675,\n -2.0983265334597716\n ],\n [\n -9.316389940923152,\n -4.929299492028762,\n -6.74957119414944,\n -2.7359568565583188,\n -2.890743523338586,\n -4.956078982236754,\n -11.32169917532862,\n -3.3624013997227022,\n -0.6235002307530829,\n 0.059493624470213904\n ],\n [\n -9.332247190014815,\n -16.20323077068271,\n -8.174672075045265,\n -6.084774136302174,\n -8.288929229991936,\n -6.058616167456106,\n -19.6073002851879,\n 5.875815590744661,\n -3.691537983682023,\n -0.731135954926579\n ],\n [\n -7.315871331023113,\n -13.159498764681924,\n -6.8032832368836536,\n -4.175974016267117,\n -2.549769786711973,\n -2.284217953646098,\n -9.911531439681616,\n 2.143249013214214,\n -4.614933565402334,\n 1.5050763251028407\n ],\n [\n -3.812803452021398,\n -12.725620328515872,\n -3.1680281315187457,\n -7.512263847123626,\n -5.047346189805691,\n -1.8920900541364316,\n 3.124529036874621,\n -9.468240241214957,\n -4.1031081027252645,\n -5.615535433119006\n ],\n [\n -6.3409852388588295,\n -10.79866710395644,\n 6.334077086386199,\n -4.115512219927054,\n -8.82788064889368,\n -9.287938524397289,\n -7.13605459810464,\n -16.08088570631066,\n -3.4431793606670436,\n -11.140769848880817\n ],\n [\n -5.249065275917307,\n -10.5559256699859,\n -5.111412266479181,\n -2.9931257092070855,\n -3.199172022727483,\n -4.612506372827503,\n -12.060900207824345,\n 4.694441897427887,\n -4.460478906724106,\n 1.2416280179827308\n ],\n [\n -8.561750904783732,\n -6.730132035535648,\n -5.395131879261276,\n -6.596141345475365,\n -3.5533695099842775,\n -4.590490375071431,\n -7.379924630830779,\n -8.423681141462108,\n 0.37767212352071045,\n -4.459131607141997\n ],\n [\n -10.348891654866605,\n -16.98119968113828,\n -9.501568870122378,\n -7.378430554487015,\n 4.976281094391466,\n -6.324148202326815,\n -7.579018075819559,\n -7.458802602813262,\n -2.3153527224981074,\n -0.8727029228467849\n ],\n [\n -11.844465203347674,\n -7.525097734764531,\n -4.429456740055663,\n -3.318471499653419,\n -7.002127959795516,\n -6.25557920790122,\n -15.480454022153053,\n 5.347250511219018,\n -3.6432427584893063,\n -0.3108484667434547\n ],\n [\n -8.098014788515188,\n -12.389433130499766,\n -7.374997302562261,\n 0.5525308141211631,\n -4.028022797353835,\n -0.6525728483707207,\n -8.21509676142421,\n -3.1775626428472896,\n -4.425403449351496,\n -5.192944333601767\n ],\n [\n -6.072918569000379,\n -15.382397417230413,\n -3.7041829222107396,\n -9.957146989581611,\n -4.167217423782958,\n -6.471434720252308,\n 4.5562961310131165,\n -10.203557387584748,\n -6.143775458561184,\n -9.902148420807695\n ],\n [\n -10.135714032174555,\n 3.7752985627512428,\n -1.9628792843849954,\n -3.774931587156314,\n -2.6682822556651793,\n -5.478354129594544,\n -3.2575333114540306,\n -5.348104510407598,\n -1.704602306408391,\n -5.645027697717877\n ],\n [\n -5.304791624889797,\n -10.917849275174271,\n -5.165567668599966,\n 4.311995036568354,\n -9.66184835524632,\n -1.0183862217001638,\n -14.143586622912714,\n -6.733673268885219,\n -1.3858080353194127,\n -3.8207824931142653\n ],\n [\n -8.211814534803795,\n -8.38903788249547,\n -3.187721441802301,\n -6.2549381199302045,\n -4.113945594996295,\n -2.5334917490765494,\n 4.363650439097854,\n -12.357289158035966,\n -3.866718906080286,\n -7.302235334280572\n ],\n [\n -8.72540797902859,\n -4.027731800153347,\n -3.4433738772330655,\n -3.6403664663390476,\n -1.679310311640678,\n -3.736481759199833,\n -6.1622751606154615,\n -2.025755126239558,\n -2.1048000040120995,\n -0.6224464501914021\n ],\n [\n -6.534666059195752,\n -10.547268494168943,\n -6.089770284368306,\n 3.021860859392828,\n -9.29451102601503,\n -1.1714117552710888,\n -14.603582886275028,\n -4.861538148910319,\n -2.6464910962252026,\n -3.060408132073173\n ],\n [\n -13.229522708500799,\n 3.384183317214765,\n -3.4385230842679175,\n -2.997065338508051,\n -4.064904119667549,\n -3.477993702471325,\n -3.3627631475852198,\n -7.104617097581389,\n -0.31885089439236053,\n -4.704459393173988\n ],\n [\n -9.829083331988372,\n -13.858735319590563,\n -7.863887021399755,\n -12.684343808745238,\n 1.3938234870827682,\n -8.518271425705427,\n -3.9311253327665994,\n -6.4963669837704625,\n -3.7206406763941624,\n -2.275612304645775\n ],\n [\n -9.77079341623652,\n 2.754138351170811,\n -3.1762604588323167,\n -1.5853952385728278,\n -1.5717467541277341,\n -1.1270009413608941,\n -4.572536507979869,\n -1.0119631119077608,\n -2.6742928088117464,\n -2.545746351116324\n ],\n [\n -12.051959950656157,\n -9.303638415275403,\n -3.7842029633154515,\n -3.382419600019866,\n -5.6279664586174265,\n -6.674429102538675,\n -8.875341596046162,\n -1.6962493198016655,\n -2.9230308287969957,\n -5.111844599871766\n ],\n [\n -1.0308795287626331,\n -9.028604092534614,\n -2.850334162165262,\n -7.367063270970033,\n -5.677988687475094,\n -0.08114347014088275,\n 3.1433246903637095,\n -14.73826888811566,\n -4.047792011479305,\n -10.498227482249789\n ],\n [\n -11.847989188187311,\n -16.027911488152732,\n -4.922231243496306,\n -5.96699861120173,\n -2.6090926737238727,\n -7.0069571516290035,\n -10.684792633795285,\n -1.4807241148190562,\n -3.3339538196274643,\n 3.2887713206514717\n ]\n]\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/certification/output_results/mini_nets/mnist_ub_results_0.05.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n[\n [\n -3.762958698725387,\n -10.064938981407087,\n -3.4903230035913366,\n 0.9313086480873003,\n -4.006931027561974,\n -1.4028419225519657,\n -11.599756762859675,\n 7.129302166503048,\n -3.504124962002839,\n 1.2101338846206113\n ],\n [\n 0.5222816131548449,\n -4.684133538440309,\n 6.706156807409307,\n 0.24499643260777168,\n -12.633028414676764,\n -1.8613755916182986,\n 2.178771874715849,\n -19.673214215337197,\n -2.2778988150970116,\n -14.561878556273848\n ],\n [\n -5.72626261039089,\n 5.206297263439835,\n -0.28290099079153996,\n -1.591979457177451,\n -0.38193250285562014,\n -2.7507465748145714,\n -1.3503240396065528,\n -0.3300982369366758,\n -1.6317040623579944,\n -2.6528712787994664\n ],\n [\n 5.466055311017486,\n -15.060836200455183,\n -2.1845079434941495,\n -4.678696328131449,\n -6.904203298761205,\n -1.7279607564805404,\n -1.0390133123266294,\n -2.663132652218254,\n -3.443511615948811,\n -3.984523577378716\n ],\n [\n -2.3378973556363034,\n -7.9152215370624575,\n -1.7007048826325981,\n -5.3420677747602054,\n 4.749337188979979,\n -3.6396700538566864,\n -1.4803028329803094,\n 0.22630177389383252,\n -2.703843298974846,\n 1.1987438635490708\n ],\n [\n -7.505629792066499,\n 5.326930752612063,\n -0.7976736729039249,\n -2.2089471839981907,\n -0.7401845817216869,\n -4.366001632031117,\n -2.884343834859336,\n 0.3445384853686439,\n -1.2081272757800854,\n -2.043688201881729\n ],\n [\n -6.810612849652462,\n -4.964168813315966,\n -4.904300890053906,\n -2.380838089147696,\n 4.260217944330126,\n -1.7577590513481838,\n -4.669993297303721,\n -0.5926833193631238,\n -0.6921626988715404,\n -0.5260631263617139\n ],\n [\n -9.946402409473254,\n -3.7237112354949375,\n -2.875293169764187,\n -2.2043149247272487,\n 0.9189113699108707,\n -1.039622978756894,\n -4.861934625459521,\n -2.893912146657854,\n -2.005239965346632,\n 2.4063405630787975\n ],\n [\n -6.810875339435716,\n -12.45992284812381,\n -6.799578942255206,\n -4.594644620963779,\n 0.002033912245148612,\n -3.8368631074295654,\n -10.059552629571153,\n 1.6970432611813082,\n -1.3382470233770132,\n 4.087988021468665\n ],\n [\n 5.027905880798777,\n -13.30541506948178,\n -0.9350111579709838,\n -2.794768067559198,\n -6.820181862532352,\n -0.9955211348531654,\n -2.6883606754851397,\n -6.618108156679065,\n -1.8258683057266132,\n -5.660608084499768\n ],\n [\n -3.219663093000625,\n -7.589412913652537,\n -1.2506584662970417,\n -3.363889662302244,\n -3.8572584314288854,\n -3.1591167306736914,\n 3.985164816006882,\n -8.877123190474553,\n -1.9754001272812725,\n -6.727853316055034\n ],\n [\n -6.471961293570405,\n -9.026472644265995,\n -5.643668264025809,\n -2.8978582472535206,\n 1.7224625428991225,\n -3.0292542275349312,\n -6.8650567522879715,\n 0.5141660048920672,\n -1.349535725990911,\n 4.2961696671007985\n ],\n [\n 6.2212911657000305,\n -13.647682873297732,\n -3.33491865735841,\n -5.42269650309377,\n -5.482436361559951,\n -1.7344300055177286,\n -3.686865105003533,\n -2.6197479910620816,\n -1.2146543453091367,\n -1.6831863877192506\n ],\n [\n -8.993099191803465,\n 5.326560398893588,\n -1.1000821394342304,\n 0.04910435923875721,\n -2.8559824997629932,\n -2.8594641434108254,\n -2.268443354002082,\n -3.088803155787143,\n -1.2460737038198626,\n -2.352732673322274\n ],\n [\n -3.8447592627895864,\n -5.347096019160217,\n -2.121462744964103,\n 1.1177083083636081,\n -3.610092031392231,\n 3.751303372974698,\n -3.147237470089651,\n -6.317030947116134,\n -0.42669936161486965,\n -6.575983789828881\n ],\n [\n -3.3674830104595683,\n -10.617518767916732,\n -3.0040289607428172,\n -4.409260770771405,\n 1.2260559664090356,\n -4.496062141892435,\n -5.1615632466787735,\n 1.6578212029668276,\n -1.8598196403301217,\n 3.989396697513974\n ],\n [\n -2.6547424308059777,\n -14.340432784866623,\n -2.785306577605215,\n 2.6302871106090406,\n -5.529815081458446,\n -1.3242905969581975,\n -11.475380072761416,\n 7.781100705441441,\n -4.122482933972681,\n -0.05996459922568499\n ],\n [\n -7.328529682379517,\n -10.939942451810818,\n -0.2893536442277967,\n 1.464475246946249,\n -5.533249324558786,\n -0.6201113598299125,\n -3.1765860496810747,\n -9.142942071537092,\n -1.5940781744950123,\n -7.443644137214727\n ],\n [\n -4.769273857394734,\n -6.595143652406207,\n -3.140117381313758,\n -2.965173830845783,\n 5.4458499820861475,\n -3.0907535291266894,\n -2.647994930600224,\n -1.4435654163268943,\n -2.085452188731849,\n 1.3877370557452715\n ],\n [\n -4.235506410235463,\n -5.858270161242545,\n -6.664530833041437,\n -1.0153835098639792,\n -0.02808826724158951,\n -2.325112911273693,\n -11.546824216236555,\n 0.6029562753060063,\n -1.7503378469142041,\n 3.90733456825841\n ],\n [\n -3.064065063238966,\n -8.772274411734305,\n -1.6967233933038661,\n -3.1879027840342737,\n -1.6326623020536777,\n 0.3296747413490425,\n 4.825428245931019,\n -10.794041967128004,\n -1.0731274662496484,\n -5.040491001209592\n ],\n [\n -6.05177356875277,\n -5.313105109405972,\n -2.352377332788808,\n -5.762352131638367,\n 0.49956104638438814,\n -5.431455770810321,\n 3.626072239191469,\n -2.1143260482161113,\n -3.430503390974689,\n -2.8467338191082114\n ],\n [\n -3.904192127272723,\n -6.512184304665964,\n -3.1260858668359752,\n -0.5915265802887895,\n -1.3900855308923608,\n 4.11060110607425,\n -0.7791142273886618,\n -6.35018766702927,\n -0.6457934084343036,\n -2.995805744107523\n ],\n [\n -3.6021953831593607,\n -2.837194117607148,\n -1.8245928941286587,\n -2.266196957952326,\n 3.870063679040515,\n -0.6807362896674993,\n -1.4950775550951136,\n 1.085395199721922,\n -3.1837977691085944,\n 1.137046795625445\n ],\n [\n 6.22635202576358,\n -25.13408908095468,\n -3.973450031305037,\n -10.585858700631324,\n -5.31575210164513,\n -3.1686538897439944,\n -0.07422591423182168,\n -7.604428413639801,\n -3.1145882281622463,\n -6.274153976909932\n ],\n [\n -3.2187619450607516,\n -7.94814512285086,\n -2.067033756086499,\n -0.14995249250826934,\n -2.5141105126267984,\n -1.7720167246833598,\n -8.2469863863098,\n 5.981237610252146,\n -3.6694486320033706,\n 2.5498945279114777\n ],\n [\n -5.338979854315685,\n -9.594283649423973,\n -3.484054171489975,\n -4.300728517544342,\n 5.496464201513135,\n -2.8397306807262166,\n -2.566399371081656,\n -2.9729688658986397,\n -2.3099823324522917,\n 1.2892853211683402\n ],\n [\n 6.393966127848848,\n -13.236937769081596,\n -1.005465816985154,\n -1.2944466387795244,\n -8.308398575638591,\n -1.9369585383706487,\n -4.728214090494104,\n -3.7278534881976846,\n -1.336867940526569,\n -4.157984706401858\n ],\n [\n -7.2724839537834685,\n 4.8879720150401,\n -1.9217365304770164,\n -0.919970655764408,\n -1.2571992875470859,\n -0.21825309701664963,\n -1.5938271482336164,\n -2.7322564351527565,\n -1.008091223916364,\n -2.0509942568160318\n ],\n [\n -6.583181077598625,\n -8.81596544146185,\n -4.882086407850092,\n 5.776168156318077,\n -5.609233986109309,\n 0.6266390543208834,\n -9.981946315196867,\n -0.5117152240265852,\n -1.9265110221786446,\n -0.30583205812530717\n ],\n [\n -7.3362254621591685,\n 4.882905056875019,\n -1.55127826154796,\n -0.1883750843169085,\n -0.8847496565847268,\n -0.8632197731843629,\n -2.5380340526200365,\n 0.27214928638868496,\n -2.151976364329761,\n -1.1651602730565587\n ],\n [\n -5.5126230844115955,\n -8.805369870160023,\n -3.480685887138574,\n 5.691778792168419,\n -3.5023423893312375,\n 1.942590982211729,\n -7.4743996228440865,\n -6.87029930349767,\n -0.16809073693432489,\n -2.860525027693846\n ],\n [\n 0.39776455761053636,\n -13.992336247475986,\n -2.8708172214565715,\n -10.558832361772764,\n 2.8352899866254293,\n -0.7301056996013587,\n 0.6053820271495908,\n -4.947912394097961,\n -3.8625112883170916,\n -4.666851244836726\n ],\n [\n -5.645319287152823,\n -5.435229263990997,\n -0.39199987830672806,\n -0.6394668322421113,\n -3.2475310461934908,\n -6.099768948005513,\n -13.372290285939501,\n 5.343523835170087,\n -1.8437150851385788,\n 0.5747364311521149\n ],\n [\n -2.194192317705064,\n -6.249407719945075,\n 6.359734460446515,\n 0.5180906557412372,\n -7.506671436323899,\n -3.517578506221104,\n -5.869046689514994,\n -10.371729256941448,\n -1.6232751100255585,\n -9.966146647915568\n ],\n [\n -3.4363156600876565,\n -5.836474654669538,\n -0.34571993519952776,\n 0.2251304617404477,\n -3.4112658618823386,\n -4.478484717928862,\n -7.892042055596799,\n 5.919609387852294,\n -2.5796474888439143,\n 0.7780110649552399\n ],\n [\n -8.902870443636097,\n 5.65941420760415,\n -2.0907807425829925,\n -0.9753191390776701,\n -1.5242625830725605,\n -1.3792578925917967,\n -3.0931458340635616,\n -0.6718738582247399,\n -1.1110983295229069,\n -1.4044064791038517\n ],\n [\n -0.9800916838047284,\n -0.2484150798162637,\n 2.921117184792496,\n 0.7768484037293824,\n -7.9856406094634576,\n -1.4107238417681036,\n -1.0087418296669555,\n -4.631964078201514,\n -0.551561194175167,\n -6.011474849215453\n ],\n [\n -6.8669307682052,\n 4.968456626193216,\n -1.482104794507861,\n -0.44914019864973836,\n -3.0528250493430646,\n -2.935135038400655,\n -0.43369293681722376,\n -4.98242508582052,\n 0.5282372260202791,\n -3.205279306397741\n ],\n [\n -4.370455889045643,\n 5.239586705942016,\n -0.2978079591217331,\n -0.6497717898716567,\n -0.9613351554247362,\n -0.13531903219048244,\n -0.740604191619413,\n 0.40805281837743174,\n -2.02238275849015,\n -1.2348569629319803\n ],\n [\n -4.200464261301348,\n -4.566974140671186,\n -0.12232133173406706,\n -0.0053180146514621735,\n -2.4502009675705585,\n -2.7731301257280743,\n -6.009499709753054,\n 4.867042456481401,\n -3.466160599629163,\n 1.4097208474639231\n ],\n [\n -10.391516751061726,\n -4.720321420277673,\n -6.4623350423479975,\n -4.02585242200853,\n 5.737829287119137,\n -5.504171592502196,\n -6.1101931765841995,\n -0.5137141632659775,\n -1.4092978379079084,\n 1.0372330608237237\n ],\n [\n -3.8190771543498294,\n 0.4075886385497101,\n 2.4940033634779795,\n -1.0774160214747366,\n -2.1214155529325605,\n -1.54518414202684,\n -1.525578256285909,\n -5.721691431410593,\n -1.1562936001480095,\n -5.436423365162148\n ],\n [\n -6.266943761843787,\n -2.9891769662309255,\n -1.4286725323967138,\n 2.432032872306629,\n -2.9767276074676645,\n 0.6659515779378019,\n -1.3134034337456504,\n -4.515018325164933,\n -1.6357727748452544,\n -2.670326497733016\n ],\n [\n -1.343905112224308,\n -8.950989236777477,\n -4.155584509613149,\n 0.8098999356719744,\n -3.682038331618554,\n 4.035958650067658,\n -2.2067591266319044,\n -5.4508228303681365,\n 0.4229044259736996,\n -1.4359013116298007\n ],\n [\n -10.31520656973317,\n 3.68198808515902,\n -0.6818440423271713,\n 0.4853798903432517,\n -1.252561755408179,\n -0.7556592168092183,\n -3.3717134058700298,\n -2.3336151294512133,\n -1.3210382859189198,\n -2.5240002227391494\n ],\n [\n -4.701313840333068,\n -1.9005940582086203,\n 5.124972971471435,\n 0.12945917631894943,\n -3.6262356653743564,\n -3.40074181928992,\n 0.09464327839610241,\n -6.372347700628153,\n -3.5715115678995506,\n -6.059000776753858\n ],\n [\n -9.457432589074935,\n -13.01037763516546,\n -7.8845902546116164,\n -4.332403105950795,\n 6.289665336311115,\n -4.360651591265923,\n -8.933949337534575,\n -4.038041136684779,\n -0.618761801781615,\n 2.863088641769402\n ],\n [\n -3.94583821786602,\n -10.438542998695288,\n -2.544962480947071,\n -5.454358739414041,\n 5.486777383444877,\n -5.431834248909705,\n -2.2802493351290987,\n -0.5573629568275179,\n -2.6406853557325087,\n 0.676387404693953\n ],\n [\n 0.07677414492440743,\n -9.220577834037657,\n -1.8238446398947905,\n -1.646643341735473,\n -2.28181258635403,\n -0.043174509753567014,\n 5.841224304829648,\n -8.09776198129464,\n -1.8538225644251454,\n -5.058905796211296\n ],\n [\n -4.313129170061074,\n -12.679733941114893,\n -0.3624202809998157,\n 4.837222136717092,\n -8.641122205453774,\n -0.8885036099672028,\n -4.357032527869311,\n -6.798799034977807,\n -2.0346078741992706,\n -6.312887535892419\n ],\n [\n -3.6095605771946193,\n -8.856708256726913,\n -5.379383253503527,\n -1.972947698308252,\n -0.7168758076662383,\n 4.1334057213818225,\n -2.544317210648593,\n -4.360724086796603,\n -1.5509842341852442,\n -1.2855029830219231\n ],\n [\n -4.049374294905033,\n -5.122645769223824,\n -2.8236425739306865,\n 1.9669993639149848,\n -2.679820981387829,\n 3.19787516487623,\n -2.0094622983240575,\n -4.212643382992114,\n -1.136705736157358,\n -2.207655239601335\n ],\n [\n -5.8349930483822074,\n -11.923738141876505,\n -1.7074131906502796,\n -7.410562494657108,\n -5.65704636921926,\n -5.455871719538208,\n 5.931007605735036,\n -10.840004736892869,\n -1.9491393426722292,\n -12.768969517949987\n ],\n [\n 5.770689386227954,\n -11.805715804558341,\n -2.118468234515105,\n -3.1069090375063015,\n -4.4751614995273465,\n -1.0854285782541209,\n -2.5668420009100354,\n -5.597650966612045,\n 1.1854343571800474,\n -3.293378682633557\n ],\n [\n -6.517603621952119,\n -15.60853402164931,\n -4.183412120037374,\n -5.669294199911528,\n 6.580736847263589,\n -3.8059748144212766,\n -3.0638316451466205,\n -3.415724828630147,\n -2.000219863142147,\n -0.557979707000082\n ],\n [\n -6.067438113518825,\n 4.890052958155947,\n -0.8097250955249141,\n -1.2092496761228977,\n -0.9626661409934262,\n -3.2228514865332967,\n -2.9127565048325703,\n 0.35254719880661745,\n -1.6047650247322502,\n -1.5490142429547735\n ],\n [\n -7.23824107002671,\n -13.23105297887399,\n -5.233320856607795,\n -3.4836456598237757,\n 0.5516218348208833,\n -2.2076693497300197,\n -7.705517591808708,\n 1.3738992320232368,\n -2.2996771672271956,\n 4.562117647379068\n ],\n [\n -1.2006100735943381,\n -0.9573651586567367,\n -4.4613725195685205,\n -2.8564924300438097,\n -0.08490530468069629,\n 2.6787415578801523,\n -4.609850120067013,\n 0.38183810017695774,\n -2.1834459100062147,\n -1.6559297255987984\n ],\n [\n -8.590705483652384,\n -11.806863867467714,\n -2.93109127177208,\n 2.419848735291596,\n -4.617183880732086,\n -3.3327106357294825,\n -12.330470067979112,\n 7.781894845990831,\n -4.279954031497704,\n -1.7713997002945296\n ],\n [\n -4.52371252664437,\n -13.046460700013927,\n 0.33136856948843146,\n -3.5456266374268988,\n -5.993800812047437,\n -1.325366378692646,\n -2.6923156083321587,\n -7.503318403356543,\n 2.135120158044691,\n -1.5964374025254597\n ],\n [\n -4.090454975480301,\n -4.578588782110576,\n -1.6811017330979374,\n -2.975877076611484,\n -0.09975160160622275,\n 1.0590668781789792,\n -1.4815336273512225,\n 0.2784374049688381,\n -0.6932377539006667,\n 1.9409736254259415\n ],\n [\n -5.496812410117724,\n -3.966113835966945,\n 2.101727474094456,\n 3.069557211788801,\n -5.300407476053109,\n -2.477336125082898,\n -5.413392666890513,\n -7.1749777683464995,\n -0.9144206434754092,\n -2.4385371348905474\n ],\n [\n -9.675754312265056,\n -14.905306808893211,\n -2.65185770513902,\n 0.66562453561239,\n -3.407475936661898,\n -3.952333477321714,\n -12.590978593426877,\n 4.777164770344321,\n -3.6938961615658887,\n 0.05191256792187347\n ],\n [\n -3.6542402613274585,\n -1.3580974607976817,\n -3.145230203433526,\n -0.6711178616580702,\n 3.237971824947457,\n -0.6449806791886008,\n -1.0615872759786593,\n -2.2603756218203106,\n -1.319863874780433,\n 0.46051751267136776\n ],\n [\n -2.813278224734649,\n -6.5314562501556885,\n -0.4417039425824656,\n -3.243640932670902,\n -1.8201511150741532,\n -4.925964631338527,\n 0.2757891383234981,\n -2.020184214462186,\n -3.7548571208717347,\n -4.322353168422524\n ],\n [\n -3.6997178210383552,\n -5.794840943679826,\n -2.8101387278092145,\n -5.766090816871408,\n 5.676896903909972,\n -5.571777943064305,\n -2.548214279259011,\n -0.4537916188859563,\n -3.1066996120849217,\n 0.6196842036809181\n ],\n [\n -7.303037359154904,\n -9.956301462069245,\n -2.4642670056953473,\n 5.60864573796251,\n -6.457896213668013,\n -0.29568175863929325,\n -9.478585209745322,\n -5.7197708018412134,\n 0.3139082484188128,\n -1.8940551745350127\n ],\n [\n 6.422747937317637,\n -13.030740769407752,\n -2.2825074375347594,\n -6.175917481849069,\n -9.535872440085388,\n 0.06697586120517224,\n 0.16619067744604246,\n -4.3464683532500015,\n -4.533161181371606,\n -6.7991043112292875\n ],\n [\n -2.475351204025315,\n -13.164200723912222,\n -2.1367777983028438,\n 1.6838056768009406,\n -5.182333616616006,\n -3.5735273584854803,\n -11.029903789966292,\n 8.3421194439246,\n -4.5235717008233856,\n -1.1394269566550108\n ],\n [\n 7.553029109257166,\n -18.5533183879268,\n -1.161940172877235,\n -6.314693749004276,\n -10.092342247666652,\n -2.359029560077611,\n -1.243549501806236,\n -10.187605105972517,\n -1.5107327404568478,\n -7.124112933368715\n ],\n [\n 0.28442053772771336,\n -10.41349259385076,\n 4.767897754250019,\n 2.4547096836914557,\n -6.556890453602522,\n -2.201497158462537,\n -5.179948180021219,\n -8.88213233304664,\n -1.4715095526666597,\n -9.145054462833244\n ],\n [\n -8.776782359621446,\n -1.9865497456087802,\n -4.35262678762113,\n -2.4978834188970396,\n -4.171954655075284,\n -5.297851629105245,\n -12.482804177077753,\n 1.5794681163335602,\n 0.27145803246424416,\n 1.6865133696929457\n ],\n [\n -8.201678996238542,\n 4.9373385813924475,\n -2.048027092363967,\n -0.8296165862232385,\n -1.6645763094982429,\n -1.0111653233450577,\n -2.3380406628507573,\n -1.2766093709586852,\n -0.15707623135502569,\n -0.9219981753224132\n ],\n [\n -10.966519219521311,\n -4.165950637767883,\n -2.4202383987064002,\n -1.1214232934188342,\n -1.6396568806763703,\n -3.0268677274383657,\n -9.036239351655128,\n 4.8477951164977755,\n -1.661670972546306,\n 0.20247381463784753\n ],\n [\n -4.345506287016068,\n -2.102705574708426,\n -2.3542089928281738,\n 4.7585238611942975,\n -2.9393153604638833,\n 1.5994478483449264,\n -3.8030623944187028,\n -6.747015765406685,\n -0.5742052376872601,\n -2.925859809359842\n ],\n [\n -3.063210279074678,\n -2.3916915185813563,\n 2.9100497925301436,\n -3.6198448650617445,\n -2.9689192767452655,\n -3.4685335052115827,\n -3.6358704112928906,\n 0.6286183211599037,\n -2.9502925977370795,\n -0.17316116703352283\n ],\n [\n -6.85121697125966,\n -2.542609604707623,\n -4.787508305817679,\n -0.9727966169433846,\n -0.7464072909304141,\n -2.8239831420355315,\n -8.512922121720544,\n -1.2961455050126505,\n 0.6726154931697501,\n 1.5939998962581816\n ],\n [\n -6.576393289024345,\n -12.35316140107808,\n -5.48706189420423,\n -3.6502087304144757,\n -5.6282188429061355,\n -3.6337878405759723,\n -15.957060569135804,\n 7.846331720802462,\n -1.865204494115141,\n 1.1557500256402908\n ],\n [\n -5.19210652504867,\n -10.01616185872926,\n -5.029959767153927,\n -2.577170970636148,\n -0.4964536868529564,\n -0.6880667146987698,\n -7.309845690204416,\n 3.9279947999804894,\n -3.286999674996312,\n 2.863242788990446\n ],\n [\n -1.6774871711387473,\n -9.694505402285515,\n -1.4128194601528683,\n -5.442554048684996,\n -2.742714213950036,\n -0.3340463250902806,\n 4.719751688195224,\n -6.694603424778095,\n -2.5361813621584353,\n -3.502577617323087\n ],\n [\n -3.996813236110702,\n -7.832284604284163,\n 8.101103057570953,\n -2.077791743044495,\n -5.940261601732222,\n -7.066483436165437,\n -4.525914058907056,\n -12.421689787117804,\n -1.7188698520699033,\n -8.210507719528026\n ],\n [\n -3.3760747055809754,\n -7.637175324937644,\n -3.037226014330463,\n -1.2691645337744155,\n -1.0900748048671365,\n -2.9953276706707044,\n -9.54860585376261,\n 6.209078622154066,\n -3.080350168372041,\n 2.670855492155256\n ],\n [\n -5.706904121999689,\n -3.7511906170166647,\n -2.971490973349341,\n -3.9878707806748994,\n -0.9455854401024236,\n -2.1105472514666803,\n -4.211605593317808,\n -5.520533754447385,\n 1.8340866524407293,\n -2.1792542882205694\n ],\n [\n -7.74180058823765,\n -13.053739507819383,\n -7.2138694250733355,\n -5.142694579536675,\n 6.976641976147153,\n -4.068398473423963,\n -4.900906021195478,\n -5.124683484676152,\n -0.7815541169663316,\n 1.1703592689664513\n ],\n [\n -9.416774003891812,\n -4.716052546040793,\n -2.602040211861344,\n -1.6248014511877336,\n -4.925196730340936,\n -4.22110070370593,\n -12.533797977605206,\n 6.976643349655342,\n -2.2431442000845943,\n 1.2646767279924591\n ],\n [\n -5.580086864824349,\n -8.784550922320559,\n -4.973490832011282,\n 2.5402072867856407,\n -1.752539604493132,\n 1.2967205429030186,\n -5.467517388269132,\n -0.8224370078585697,\n -2.590532537206316,\n -2.867970360928669\n ],\n [\n -3.6937514389895805,\n -11.852020685032793,\n -1.4837631733822985,\n -7.565738547744463,\n -1.5410627494828324,\n -4.043965429093653,\n 6.448107871534838,\n -7.236097795110034,\n -4.26040868491694,\n -7.027443380588594\n ],\n [\n -8.07996804863203,\n 5.132238183773745,\n -0.6603915943660417,\n -2.197323343606787,\n -0.8314628442949418,\n -3.72478607438905,\n -1.3895211434032926,\n -3.256058545584961,\n -0.47206697023386457,\n -3.9085667840697704\n ],\n [\n -3.2292440549968,\n -7.401935240513051,\n -2.8951210691000506,\n 6.0977729198905335,\n -6.7791534796934005,\n 1.2128365456759613,\n -10.550322573088723,\n -3.915793146451857,\n 0.12640551606383854,\n -1.760400246586213\n ],\n [\n -5.6882575380256295,\n -5.318049766928563,\n -1.2064803760438225,\n -4.265093962744851,\n -1.3776606904959707,\n -0.7188261932627427,\n 6.110956313631728,\n -9.166630949391655,\n -2.178746722147867,\n -4.691133832504731\n ],\n [\n -5.962523823010809,\n -1.5688631678552496,\n -1.4143067157323552,\n -1.8392475343780381,\n 0.4905734654324488,\n -1.4790470867428769,\n -3.1288371789910245,\n -0.06902760496997719,\n -0.9282083219059251,\n 1.1887503604785679\n ],\n [\n -4.320752199863908,\n -7.430305281475364,\n -4.128302863958127,\n 4.758717375009701,\n -6.724345361494206,\n 0.6821660284519374,\n -11.406668818936737,\n -2.3200219779324556,\n -1.1491046426063516,\n -1.1695084274738683\n ],\n [\n -11.00881578336663,\n 4.784118921281837,\n -1.7469308464258226,\n -1.4623180605867498,\n -2.3529563580019506,\n -2.0323038295467306,\n -1.5018810812771786,\n -5.02788753745241,\n 0.8841876937597006,\n -3.1516857768615467\n ],\n [\n -7.052179557696842,\n -10.081108566709435,\n -5.310531179319887,\n -9.904922159393417,\n 3.730468056429601,\n -5.87311435467093,\n -0.9864213826636647,\n -3.845737434967773,\n -2.0414310919964116,\n -0.18848817055650482\n ],\n [\n -7.6485628937347405,\n 4.334265898408461,\n -1.642061723992373,\n -0.2773596223817614,\n -0.12917511412160146,\n 0.13089083063194382,\n -2.8555967139420524,\n 0.5732572628957784,\n -1.4032405279192353,\n -1.2540689578684419\n ],\n [\n -9.388941651460817,\n -5.959670442651902,\n -1.8161989639660288,\n -1.1334576172751534,\n -3.293871740937896,\n -4.407464923038745,\n -5.93620529211181,\n 0.5579750925408218,\n -1.444331072242069,\n -2.8043371154447136\n ],\n [\n 0.7304048013409243,\n -6.186154425940321,\n -0.9398104329276924,\n -5.204456655837724,\n -3.0713761328452662,\n 1.4685353236623917,\n 4.9342891469387675,\n -11.352777617995642,\n -2.3780122587804016,\n -7.7270509830608765\n ],\n [\n -8.97022786816846,\n -12.538915261369036,\n -2.6767856103197882,\n -3.473152204919008,\n -0.48183821051219816,\n -4.837543495263658,\n -7.659187685450903,\n 0.6547345889031397,\n -1.9539529683406904,\n 4.826536132911242\n ]\n]\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_GPy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport GPy\n\nfrom art.estimators.classification.GPy import GPyGaussianProcessClassifier\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestGPyGaussianProcessClassifier(TestBase):\n \"\"\"\n This class tests the GPy Gaussian Process classifier.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n # change iris to binary problem, so it is learnable for GPC\n cls.y_train_iris_binary = cls.y_train_iris[:, 1]\n cls.y_test_iris_binary = cls.y_test_iris[:, 1]\n\n # set up GPclassifier\n gpkern = GPy.kern.RBF(np.shape(cls.x_train_iris)[1])\n m = GPy.models.GPClassification(cls.x_train_iris, cls.y_train_iris_binary.reshape(-1, 1), kernel=gpkern)\n m.inference_method = GPy.inference.latent_function_inference.laplace.Laplace()\n m.optimize(messages=True, optimizer=\"lbfgs\")\n\n # get ART classifier + clean accuracy\n cls.classifier = GPyGaussianProcessClassifier(m)\n\n def setUp(self):\n master_seed(seed=1234)\n super().setUp()\n\n def test_predict(self):\n # predictions should be correct\n self.assertTrue(\n np.mean((self.classifier.predict(self.x_test_iris[:3])[:, 0] > 0.5) == self.y_test_iris_binary[:3]) > 0.6\n )\n outlier = np.ones(np.shape(self.x_test_iris[:3])) * 10.0\n # output for random points should be 0.5 (as classifier is uncertain)\n self.assertTrue(np.sum(self.classifier.predict(outlier).flatten() == 0.5) == 6.0)\n\n def test_predict_unc(self):\n outlier = np.ones(np.shape(self.x_test_iris[:3])) * (np.max(self.x_test_iris.flatten()) * 10.0)\n # uncertainty should increase as we go deeper into data\n self.assertTrue(\n np.mean(\n self.classifier.predict_uncertainty(outlier) > self.classifier.predict_uncertainty(self.x_test_iris[:3])\n )\n == 1.0\n )\n\n def test_loss_gradient(self):\n grads = self.classifier.loss_gradient(self.x_test_iris[0:1], self.y_test_iris_binary[0:1])\n # grads with given seed should be [[-2.25244234e-11 -5.63282695e-11 1.74214328e-11 -1.21877914e-11]]\n # we test roughly: amount of positive/negative and largest gradient\n self.assertTrue(np.sum(grads < 0.0) == 3.0)\n self.assertTrue(np.sum(grads > 0.0) == 1.0)\n self.assertTrue(np.argmax(grads) == 2)\n\n def test_class_gradient(self):\n grads = self.classifier.class_gradient(self.x_test_iris[0:1], int(self.y_test_iris_binary[0:1]))\n # grads with given seed should be [[[2.25244234e-11 5.63282695e-11 -1.74214328e-11 1.21877914e-11]]]\n # we test roughly: amount of positive/negative and largest gradient\n self.assertTrue(np.sum(grads < 0.0) == 1.0)\n self.assertTrue(np.sum(grads > 0.0) == 3.0)\n self.assertTrue(np.argmax(grads) == 1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_blackbox.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport tempfile\nimport unittest\n\nimport numpy as np\n\nfrom art.defences.preprocessor import FeatureSqueezing, JpegCompression, SpatialSmoothing\n\nfrom tests.utils import TestBase, get_classifier_bb, get_classifier_bb_nn\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestBlackBoxClassifier(TestBase):\n \"\"\"\n This class tests the BlackBox classifier.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.test_dir = tempfile.mkdtemp()\n\n def test_fit(self):\n classifier = get_classifier_bb()\n self.assertRaises(\n NotImplementedError,\n lambda: classifier.fit(self.x_train_mnist, self.y_train_mnist, batch_size=self.batch_size, nb_epochs=2),\n )\n\n def test_shapes(self):\n classifier = get_classifier_bb()\n predictions = classifier.predict(self.x_test_mnist)\n self.assertEqual(predictions.shape, self.y_test_mnist.shape)\n self.assertEqual(classifier.nb_classes, 10)\n self.assertEqual(predictions.shape, self.y_test_mnist.shape)\n\n def test_defences_predict(self):\n clip_values = (0, 1)\n fs = FeatureSqueezing(clip_values=clip_values, bit_depth=2)\n jpeg = JpegCompression(clip_values=clip_values, apply_predict=True)\n smooth = SpatialSmoothing()\n classifier = get_classifier_bb(defences=[fs, jpeg, smooth])\n self.assertEqual(len(classifier.preprocessing_defences), 3)\n\n predictions_classifier = classifier.predict(self.x_test_mnist)\n\n # Apply the same defences by hand\n x_test_defense = self.x_test_mnist\n x_test_defense, _ = fs(x_test_defense, self.y_test_mnist)\n x_test_defense, _ = jpeg(x_test_defense, self.y_test_mnist)\n x_test_defense, _ = smooth(x_test_defense, self.y_test_mnist)\n classifier = get_classifier_bb()\n predictions_check = classifier.predict(x_test_defense)\n\n # Check that the prediction results match\n np.testing.assert_array_almost_equal(predictions_classifier, predictions_check, decimal=4)\n\n def test_save(self):\n path = \"tmp\"\n filename = \"model.h5\"\n\n classifier = get_classifier_bb()\n\n self.assertRaises(NotImplementedError, lambda: classifier.save(filename, path=path))\n\n def test_repr(self):\n classifier = get_classifier_bb()\n repr_ = repr(classifier)\n\n self.assertIn(\"BlackBoxClassifier\", repr_)\n self.assertIn(\"clip_values=[ 0. 255.]\", repr_)\n self.assertIn(\"defences=None\", repr_)\n self.assertIn(\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\", repr_\n )\n\n\nclass TestBlackBoxClassifierNeuralNetwork(TestBase):\n \"\"\"\n This class tests the BlackBox Neural Network classifier.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.test_dir = tempfile.mkdtemp()\n\n def test_fit(self):\n classifier = get_classifier_bb_nn()\n self.assertRaises(\n NotImplementedError,\n lambda: classifier.fit(self.x_train_mnist, self.y_train_mnist, batch_size=self.batch_size, nb_epochs=2),\n )\n\n def test_shapes(self):\n classifier = get_classifier_bb_nn()\n predictions = classifier.predict(self.x_test_mnist)\n self.assertEqual(predictions.shape, self.y_test_mnist.shape)\n self.assertEqual(classifier.nb_classes, 10)\n self.assertEqual(predictions.shape, self.y_test_mnist.shape)\n\n def test_defences_predict(self):\n clip_values = (0, 1)\n fs = FeatureSqueezing(clip_values=clip_values, bit_depth=2)\n jpeg = JpegCompression(clip_values=clip_values, apply_predict=True)\n smooth = SpatialSmoothing()\n classifier = get_classifier_bb_nn(defences=[fs, jpeg, smooth])\n self.assertEqual(len(classifier.preprocessing_defences), 3)\n\n predictions_classifier = classifier.predict(self.x_test_mnist)\n\n # Apply the same defences by hand\n x_test_defense = self.x_test_mnist\n x_test_defense, _ = fs(x_test_defense, self.y_test_mnist)\n x_test_defense, _ = jpeg(x_test_defense, self.y_test_mnist)\n x_test_defense, _ = smooth(x_test_defense, self.y_test_mnist)\n classifier = get_classifier_bb_nn()\n predictions_check = classifier.predict(x_test_defense)\n\n # Check that the prediction results match\n np.testing.assert_array_almost_equal(predictions_classifier, predictions_check, decimal=4)\n\n def test_repr(self):\n classifier = get_classifier_bb_nn()\n repr_ = repr(classifier)\n\n self.assertIn(\"BlackBoxClassifier\", repr_)\n self.assertIn(\"clip_values=[ 0. 255.]\", repr_)\n self.assertIn(\"defences=None\", repr_)\n self.assertIn(\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\", repr_\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_blackbox_existing_predictions.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\nimport numpy as np\n\nfrom art.estimators.classification.blackbox import BlackBoxClassifierNeuralNetwork, BlackBoxClassifier\nfrom tests.utils import ARTTestException\n\n\ndef test_blackbox_existing_predictions(art_warning, get_mnist_dataset):\n try:\n _, (x_test, y_test) = get_mnist_dataset\n\n limited_x_test = x_test[:500]\n limited_y_test = y_test[:500]\n\n bb = BlackBoxClassifier((limited_x_test, limited_y_test), (28, 28, 1), 10, clip_values=(0, 255))\n assert np.array_equal(bb.predict(limited_x_test), limited_y_test)\n\n with pytest.raises(ValueError):\n bb.predict(x_test[:600])\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_existing_predictions_fuzzy(art_warning):\n try:\n x = np.array([0, 3])\n fuzzy_x = np.array([0, 3.00001])\n y = np.array([[1, 0], [0, 1]])\n bb = BlackBoxClassifier((x, y), (1,), 2, fuzzy_float_compare=True)\n assert np.array_equal(bb.predict(fuzzy_x), y)\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_nn_existing_predictions(art_warning, get_mnist_dataset):\n try:\n _, (x_test, y_test) = get_mnist_dataset\n\n limited_x_test = x_test[:500]\n limited_y_test = y_test[:500]\n\n bb = BlackBoxClassifierNeuralNetwork((limited_x_test, limited_y_test), (28, 28, 1), 10, clip_values=(0, 255))\n assert np.array_equal(bb.predict(limited_x_test), limited_y_test)\n\n with pytest.raises(ValueError):\n bb.predict(x_test[:600])\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_nn_existing_predictions_fuzzy(art_warning):\n try:\n x = np.array([0, 3])\n fuzzy_x = np.array([0, 3.00001])\n y = np.array([[1, 0], [0, 1]])\n bb = BlackBoxClassifierNeuralNetwork((x, y), (1,), 2, fuzzy_float_compare=True)\n assert np.array_equal(bb.predict(fuzzy_x), y)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_catboost.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nfrom catboost import CatBoostClassifier\nimport numpy as np\n\nfrom art.estimators.classification.catboost import CatBoostARTClassifier\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestCatBoostClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.y_train_iris_index = np.argmax(cls.y_train_iris, axis=1)\n cls.y_test_iris_index = np.argmax(cls.y_test_iris, axis=1)\n\n model = CatBoostClassifier(custom_loss=[\"Accuracy\"], random_seed=42, logging_level=\"Silent\")\n cls.classifier = CatBoostARTClassifier(model=model)\n cls.classifier.fit(cls.x_train_iris, cls.y_train_iris_index, cat_features=[], eval_set=[])\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.00106307, 0.00118028, 0.99775665]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"catboost_1\")\n self.classifier.save(filename=\"catboost_2\", path=\".\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_classifier.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.estimators.classification.classifier import ClassGradientsMixin, ClassifierMixin\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin, NeuralNetworkMixin\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass ClassifierInstance(ClassifierMixin, BaseEstimator):\n estimator_params = BaseEstimator.estimator_params + ClassifierMixin.estimator_params\n\n def __init__(self, clip_values=None, channels_first=True):\n super(ClassifierInstance, self).__init__(model=None, clip_values=clip_values)\n\n def fit(self, x, y, **kwargs):\n pass\n\n def predict(self, x, **kwargs):\n pass\n\n def nb_classes(self):\n pass\n\n def save(self, filename, path=None):\n pass\n\n def input_shape(self):\n pass\n\n\nclass ClassifierNeuralNetworkInstance(\n ClassGradientsMixin, ClassifierMixin, NeuralNetworkMixin, LossGradientsMixin, BaseEstimator\n):\n estimator_params = (\n BaseEstimator.estimator_params + NeuralNetworkMixin.estimator_params + ClassifierMixin.estimator_params\n )\n\n def __init__(self, clip_values, channels_first=True):\n super(ClassifierNeuralNetworkInstance, self).__init__(\n model=None, clip_values=clip_values, channels_first=channels_first\n )\n\n def class_gradient(self, x, label=None, **kwargs):\n pass\n\n def fit(self, x, y, batch_size=128, nb_epochs=20, **kwargs):\n pass\n\n def get_activations(self, x, layer, batch_size):\n pass\n\n def compute_loss(self, x, y, **kwargs):\n pass\n\n def loss_gradient(self, x, y, **kwargs):\n pass\n\n def predict(self, x, batch_size=128, **kwargs):\n pass\n\n def nb_classes(self):\n pass\n\n def save(self, filename, path=None):\n pass\n\n def layer_names(self):\n pass\n\n def input_shape(self):\n pass\n\n\nclass TestClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n def setUp(self):\n master_seed(seed=1234)\n super().setUp()\n\n def test_preprocessing_normalisation(self):\n classifier = ClassifierInstance()\n\n x = np.random.rand(2, 3)\n x_new, _ = classifier._apply_preprocessing(x=x, y=None, fit=False)\n x_new_expected = np.asarray([[0.19151945, 0.62210877, 0.43772774], [0.78535858, 0.77997581, 0.27259261]])\n np.testing.assert_array_almost_equal(x_new, x_new_expected)\n\n def test_repr(self):\n classifier = ClassifierInstance()\n\n repr_ = repr(classifier)\n self.assertIn(\"ClassifierInstance\", repr_)\n self.assertIn(\"clip_values=None\", repr_)\n self.assertIn(\"defences=None\", repr_)\n self.assertIn(\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\", repr_\n )\n\n\nclass TestClassifierNeuralNetwork(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n def setUp(self):\n master_seed(seed=1234)\n super().setUp()\n\n def test_preprocessing_normalisation(self):\n classifier = ClassifierNeuralNetworkInstance((0, 1))\n x = np.random.rand(2, 3)\n x_new_expected = np.asarray([[0.19151945, 0.62210877, 0.43772774], [0.78535858, 0.77997581, 0.27259261]])\n x_new, _ = classifier._apply_preprocessing(x, y=None, fit=False)\n np.testing.assert_array_almost_equal(x_new, x_new_expected, decimal=4)\n\n def test_repr(self):\n classifier = ClassifierNeuralNetworkInstance((0, 1))\n repr_ = repr(classifier)\n self.assertIn(\"ClassifierNeuralNetworkInstance\", repr_)\n self.assertIn(\"channels_first=True\", repr_)\n self.assertIn(\"clip_values=[0. 1.]\", repr_)\n self.assertIn(\"defences=None\", repr_)\n self.assertIn(\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\", repr_\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_deep_partition_ensemble.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport os\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow.keras.losses import categorical_crossentropy\nfrom tensorflow.keras.optimizers import Adam\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom art.utils import load_dataset\nfrom art.estimators.classification.deep_partition_ensemble import DeepPartitionEnsemble\nfrom art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier, KerasClassifier\n\nfrom tests.utils import master_seed\n\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"True\"\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 100\nNB_TRAIN = 1000\nNB_TEST = 10\nENSEMBLE_SIZE = 5\n\n\nclass TestDeepPartitionEnsemble(unittest.TestCase):\n \"\"\"\n This class tests the deep partition ensemble classifier.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Get MNIST\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n x_test, y_test = x_test[:NB_TEST], y_test[:NB_TEST]\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_1_tf(self):\n \"\"\"\n Test with a TensorFlow Classifier.\n :return:\n \"\"\"\n # Get MNIST\n (x_train, y_train), (x_test, y_test) = self.mnist\n\n # Create a model from scratch\n from tensorflow.keras import Model\n from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Input\n\n def build_tensorflow_functional_model():\n inputs = Input(shape=(28, 28, 1))\n\n x = Conv2D(filters=4, kernel_size=5, activation=\"relu\")(inputs)\n x = MaxPool2D(pool_size=(2, 2), strides=(2, 2))(x)\n x = Conv2D(filters=10, kernel_size=5, activation=\"relu\")(x)\n x = MaxPool2D(pool_size=(2, 2), strides=(2, 2))(x)\n x = Flatten()(x)\n x = Dense(100, activation=\"relu\")(x)\n outputs = Dense(10, activation=\"linear\")(x)\n\n return Model(inputs=inputs, outputs=outputs, name=\"TensorFlowModel\")\n\n model = build_tensorflow_functional_model()\n loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\n optimizer = Adam(learning_rate=0.01)\n model.compile(loss=loss_object, optimizer=optimizer)\n\n classifier = TensorFlowV2Classifier(\n model=model,\n loss_object=loss_object,\n optimizer=optimizer,\n nb_classes=10,\n input_shape=(28, 28, 1),\n clip_values=(0, 1),\n )\n\n # Initialize DPA Classifier\n dpa = DeepPartitionEnsemble(\n classifiers=classifier,\n ensemble_size=ENSEMBLE_SIZE,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n )\n\n # Check basic functionality of DPA Classifier\n # check predict\n y_test_dpa = dpa.predict(x=x_test)\n self.assertEqual(y_test_dpa.shape, y_test.shape)\n self.assertTrue((np.sum(y_test_dpa, axis=1) <= ENSEMBLE_SIZE * np.ones((NB_TEST,))).all())\n\n # loss gradient\n grad = dpa.loss_gradient(x=x_test, y=y_test, sampling=True)\n assert grad.shape == (10, 28, 28, 1)\n\n # fit\n dpa.fit(x=x_train, y=y_train)\n\n def test_2_pt(self):\n \"\"\"\n Test with a PyTorch Classifier.\n :return:\n \"\"\"\n\n # Get MNIST\n (x_train, y_train), (x_test, y_test) = self.mnist\n\n x_train = np.transpose(x_train, (0, 3, 1, 2)).astype(np.float32)\n x_test = np.transpose(x_test, (0, 3, 1, 2)).astype(np.float32)\n\n # Create a model from scratch\n class PyTorchModel(nn.Module):\n def __init__(self):\n super(PyTorchModel, self).__init__()\n self.conv_1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=5, stride=1)\n self.conv_2 = nn.Conv2d(in_channels=4, out_channels=10, kernel_size=5, stride=1)\n self.fc_1 = nn.Linear(in_features=4 * 4 * 10, out_features=100)\n self.fc_2 = nn.Linear(in_features=100, out_features=10)\n\n def forward(self, x):\n x = F.relu(self.conv_1(x))\n x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.conv_2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4 * 4 * 10)\n x = F.relu(self.fc_1(x))\n x = self.fc_2(x)\n return x\n\n # Step 2a: Define the loss function and the optimizer\n model = PyTorchModel()\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n\n # Step 3: Create the ART classifier\n\n classifier = PyTorchClassifier(\n model=model,\n clip_values=(0, 1),\n loss=criterion,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n\n # Initialize DPA Classifier\n dpa = DeepPartitionEnsemble(\n classifiers=classifier,\n ensemble_size=ENSEMBLE_SIZE,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n )\n\n # Check basic functionality of DPA Classifier\n # check predict\n y_test_dpa = dpa.predict(x=x_test)\n self.assertEqual(y_test_dpa.shape, y_test.shape)\n self.assertTrue((np.sum(y_test_dpa, axis=1) <= ENSEMBLE_SIZE * np.ones((NB_TEST,))).all())\n\n # loss gradient\n grad = dpa.loss_gradient(x=x_test, y=y_test, sampling=True)\n assert grad.shape == (10, 1, 28, 28)\n\n # fit\n dpa.fit(x=x_train, y=y_train)\n\n def test_3_kr(self):\n \"\"\"\n Test with a Keras Classifier.\n :return:\n \"\"\"\n # Get MNIST\n (x_train, y_train), (x_test, y_test) = self.mnist\n\n # Create a model from scratch\n model = Sequential()\n model.add(Conv2D(filters=4, kernel_size=(5, 5), strides=1, activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(filters=10, kernel_size=(5, 5), strides=1, activation=\"relu\", input_shape=(23, 23, 4)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n model.add(Dense(100, activation=\"relu\"))\n model.add(Dense(10, activation=\"softmax\"))\n\n model.compile(loss=categorical_crossentropy, optimizer=Adam(learning_rate=0.01), metrics=[\"accuracy\"])\n\n classifier = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)\n\n # Initialize DPA Classifier\n dpa = DeepPartitionEnsemble(\n classifiers=classifier,\n ensemble_size=ENSEMBLE_SIZE,\n channels_first=classifier.channels_first,\n clip_values=classifier.clip_values,\n preprocessing_defences=classifier.preprocessing_defences,\n postprocessing_defences=classifier.postprocessing_defences,\n preprocessing=classifier.preprocessing,\n )\n\n # Check basic functionality of DPA Classifier\n # check predict\n y_test_dpa = dpa.predict(x=x_test)\n self.assertEqual(y_test_dpa.shape, y_test.shape)\n self.assertTrue((np.sum(y_test_dpa, axis=1) <= ENSEMBLE_SIZE * np.ones((NB_TEST,))).all())\n\n # loss gradient\n grad = dpa.loss_gradient(x=x_test, y=y_test, sampling=True)\n assert grad.shape == (10, 28, 28, 1)\n\n # fit\n dpa.fit(x=x_train, y=y_train)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_deeplearning_common.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_class_gradient\": [\n [\n [\n -0.03347399,\n -0.03195872,\n -0.02650188,\n 0.04111874,\n 0.08676253,\n 0.03339913,\n 0.06925241,\n 0.09387045,\n 0.15184258,\n -0.00684002,\n 0.05070481,\n 0.01409407,\n -0.03632583,\n 0.00151133,\n 0.05102589,\n 0.00766463,\n -0.00898967,\n 0.00232938,\n -0.00617045,\n -0.00201032,\n 0.00410065,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.09723657,\n -0.00240533,\n 0.02445251,\n -0.00035474,\n 0.04765627,\n 0.04286841,\n 0.07209076,\n 0.0,\n 0.0,\n -0.07938144,\n -0.00142567,\n 0.02882954,\n -0.00049514,\n 0.04170151,\n 0.05102589,\n 0.09544909,\n -0.04401167,\n -0.06158172,\n 0.03359772,\n -0.00838454,\n 0.01722163,\n -0.13376027,\n 0.08206709,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.03347399,\n -0.03195872,\n -0.02650188,\n 0.04111874,\n 0.08676253,\n 0.03339913,\n 0.06925241,\n 0.09387045,\n 0.15184258,\n -0.00684002,\n 0.05070481,\n 0.01409407,\n -0.03632583,\n 0.00151133,\n 0.05102589,\n 0.00766463,\n -0.00898967,\n 0.00232938,\n -0.00617045,\n -0.00201032,\n 0.00410065,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.09723657,\n -0.00240533,\n 0.02445251,\n -0.00035474,\n 0.04765627,\n 0.04286841,\n 0.07209076,\n 0.0,\n 0.0,\n -0.07938144,\n -0.00142567,\n 0.02882954,\n -0.00049514,\n 0.04170151,\n 0.05102589,\n 0.09544909,\n -0.04401167,\n -0.06158172,\n 0.03359772,\n -0.00838454,\n 0.01722163,\n -0.13376027,\n 0.08206709,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n 0.06860766,\n 0.065502,\n 0.08539103,\n 0.13868105,\n -0.05520725,\n -0.18788849,\n 0.02264893,\n 0.02980516,\n 0.2226511,\n 0.11288887,\n -0.00678776,\n 0.02045561,\n -0.03120914,\n 0.00642691,\n 0.08449504,\n 0.02848018,\n -0.03251382,\n 0.00854315,\n -0.02354656,\n -0.00767687,\n 0.01565931,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.0487146,\n -0.0171556,\n -0.03161772,\n -0.0420007,\n 0.03360246,\n -0.01864819,\n 0.00315916,\n 0.0,\n 0.0,\n -0.07631349,\n -0.00374462,\n 0.04229517,\n -0.01131879,\n 0.05044588,\n 0.08449504,\n 0.12417868,\n 0.07536847,\n 0.03906382,\n 0.09467953,\n 0.00543209,\n -0.00504872,\n -0.03366479,\n -0.00385999,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n 3,\n 4,\n 4,\n 0,\n 1,\n 1,\n 1,\n 2,\n 3,\n 4,\n 4,\n 2,\n 2,\n 0,\n 0,\n 4,\n 0,\n 1,\n 2,\n 0,\n 3,\n 4,\n 2,\n 2,\n 3,\n 3,\n 0,\n 1,\n 3,\n 0,\n 3,\n 2,\n 3,\n 4,\n 1,\n 3,\n 3,\n 3,\n 2,\n 1,\n 3,\n 4,\n 2,\n 3,\n 4,\n 1,\n 4,\n 0,\n 4,\n 1,\n 1,\n 4,\n 1,\n 4,\n 0,\n 1,\n 0,\n 0,\n 4,\n 0,\n 4,\n 2,\n 3,\n 1,\n 2,\n 2,\n 4,\n 3,\n 4,\n 2,\n 2,\n 4,\n 4,\n 2,\n 1,\n 3,\n 2,\n 1,\n 4,\n 1,\n 0,\n 1,\n 2,\n 1,\n 2,\n 1,\n 2,\n 1,\n 1,\n 4,\n 1,\n 2,\n 4,\n 0,\n 4,\n 1,\n 2,\n 1,\n 1,\n 3\n ]\n ],\n \"test_loss_gradient\": [\n [\n [\n 0.00210803,\n 0.00213919,\n 0.0052098,\n 0.00548,\n -0.0023059,\n 0.00432076,\n 0.00274945,\n 0.0,\n 0.0,\n -0.0583441,\n -0.00616604,\n 0.05262191,\n -0.02373985,\n 0.05273107,\n 0.10711591,\n 0.12773865,\n 0.06892889,\n 0.01337799,\n 0.1003202,\n 0.01681095,\n -0.00028647,\n -0.05588859,\n 0.01474165,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n 0.0559206,\n 0.05338925,\n 0.0648919,\n 0.07925165,\n -0.04029291,\n -0.11281465,\n 0.01850601,\n 0.00325053,\n 0.08163194,\n 0.03333949,\n 0.031766,\n -0.02420464,\n -0.07815557,\n -0.04698735,\n 0.10711591,\n 0.04086433,\n -0.03441072,\n 0.01071284,\n -0.04229196,\n -0.01386157,\n 0.02827487,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ]\n ],\n \"test_predict\": [\n [\n 0.15710345,\n -0.73106134,\n -0.04039804,\n -0.47904843,\n 0.09378531,\n -0.80105764,\n -0.47753483,\n 1.0868737,\n -0.3065778,\n -0.57497704\n ]\n ],\n \"test_repr_tensorflow2\": [\n \"TensorFlowV2Classifier\",\n \"model=\",\n \"nb_classes=10\",\n \"input_shape=(28, 28, 1)\",\n \"loss_object=\",\n \"optimizer=\",\n \"channels_first=False, \",\n \"clip_values=array([0., 1.], dtype=float32), \",\n \"preprocessing_defences=None, postprocessing_defences=None, preprocessing=StandardisationMeanStdTensorFlow(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\"\n ],\n \"test_repr_pytorch\": [\n \"art.estimators.classification.pytorch.PyTorchClassifier\",\n \"(conv): Conv2d(1, 1, kernel_size=(7, 7), stride=(1, 1))\",\n \"(pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False)\",\n \"(fullyconnected): Linear(in_features=25, out_features=10, bias=True)\",\n \"loss=CrossEntropyLoss(), optimizer=Adam\",\n \"input_shape=(1, 28, 28), nb_classes=10\",\n \"clip_values=array([0., 1.], dtype=float32\",\n \"preprocessing_defences=None, postprocessing_defences=None, preprocessing=StandardisationMeanStdPyTorch(mean=0.0, std=1.0, apply_fit=True, apply_predict=True, device=cpu)\"\n ],\n \"test_repr_huggingface\": [\n \"art.estimators.classification.hugging_face.HuggingFaceClassifierPyTorch\",\n \"(conv): Conv2d(1, 1, kernel_size=(7, 7), stride=(1, 1))\",\n \"(pool): MaxPool2d(kernel_size=4, stride=4, padding=0, dilation=1, ceil_mode=False)\",\n \"(fullyconnected): Linear(in_features=25, out_features=10, bias=True)\",\n \"loss=CrossEntropyLoss(), optimizer=Adam\",\n \"input_shape=(1, 28, 28), nb_classes=10\",\n \"clip_values=array([0., 1.], dtype=float32\",\n \"preprocessing_defences=None, postprocessing_defences=None, preprocessing=StandardisationMeanStdPyTorch(mean=0.0, std=1.0, apply_fit=True, apply_predict=True, device=cpu)\"\n ],\n \"test_repr_keras\": [\n \"art.estimators.classification.keras.KerasClassifier\",\n \"use_logits=True\",\n \"channels_first=False\",\n \"clip_values=array([0., 1.], dtype=float32)\",\n \"preprocessing_defences=None\",\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\",\n \"input_layer=0, output_layer=0\"\n ],\n \"test_repr_kerastf\": [\n \"art.estimators.classification.keras.KerasClassifier\",\n \"use_logits=True\",\n \"channels_first=False\",\n \"clip_values=array([0., 1.], dtype=float32)\",\n \"preprocessing_defences=None\",\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\",\n \"input_layer=0, output_layer=0\"\n ],\n \"test_class_gradient_tensorflow2\": [\n [\n [\n -0.03347398713231087,\n -0.031958721578121185,\n -0.026501882821321487,\n 0.041118744760751724,\n 0.08676252514123917,\n 0.03339913487434387,\n 0.06925240904092789,\n 0.09387044608592987,\n 0.15184257924556732,\n -0.006840024143457413,\n 0.05070481449365616,\n 0.014094067737460136,\n -0.036325834691524506,\n 0.0015113259432837367,\n 0.051025886088609695,\n 0.007664630189538002,\n -0.008989665657281876,\n 0.002329375362023711,\n -0.0061704539693892,\n -0.0020103193819522858,\n 0.004100654274225235,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.09723656624555588,\n -0.002405333798378706,\n 0.024452514946460724,\n -0.00035474030300974846,\n 0.04765626788139343,\n 0.04286840930581093,\n 0.0720907598733902,\n 0.0,\n 0.0,\n -0.07938143610954285,\n -0.0014256746508181095,\n 0.02882954478263855,\n -0.0004951448645442724,\n 0.04170151427388191,\n 0.051025886088609695,\n 0.09544909000396729,\n -0.0440116748213768,\n -0.06158171966671944,\n 0.03359771892428398,\n -0.008384542539715767,\n 0.017221633344888687,\n -0.1337602734565735,\n 0.0820670947432518,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.03347398713231087,\n -0.031958721578121185,\n -0.026501882821321487,\n 0.041118744760751724,\n 0.08676252514123917,\n 0.03339913487434387,\n 0.06925240904092789,\n 0.09387044608592987,\n 0.15184257924556732,\n -0.006840024143457413,\n 0.05070481449365616,\n 0.014094067737460136,\n -0.036325834691524506,\n 0.0015113259432837367,\n 0.051025886088609695,\n 0.007664630189538002,\n -0.008989665657281876,\n 0.002329375362023711,\n -0.0061704539693892,\n -0.0020103193819522858,\n 0.004100654274225235,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.09723656624555588,\n -0.002405333798378706,\n 0.024452514946460724,\n -0.00035474030300974846,\n 0.04765626788139343,\n 0.04286840930581093,\n 0.0720907598733902,\n 0.0,\n 0.0,\n -0.07938143610954285,\n -0.0014256746508181095,\n 0.02882954478263855,\n -0.0004951448645442724,\n 0.04170151427388191,\n 0.051025886088609695,\n 0.09544909000396729,\n -0.0440116748213768,\n -0.06158171966671944,\n 0.03359771892428398,\n -0.008384542539715767,\n 0.017221633344888687,\n -0.1337602734565735,\n 0.0820670947432518,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n 0.06860765814781189,\n 0.06550200283527374,\n 0.08539102971553802,\n 0.1386810541152954,\n -0.055207252502441406,\n -0.1878884881734848,\n 0.022648930549621582,\n 0.029805157333612442,\n 0.22265109419822693,\n 0.1128888726234436,\n -0.006787760183215141,\n 0.020455610007047653,\n -0.03120914287865162,\n 0.006426911801099777,\n 0.08449503779411316,\n 0.028480183333158493,\n -0.0325138159096241,\n 0.008543146774172783,\n -0.023546557873487473,\n -0.007676873821765184,\n 0.015659306198358536,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n [\n -0.04871459677815437,\n -0.01715559884905815,\n -0.031617723405361176,\n -0.042000703513622284,\n 0.033602457493543625,\n -0.018648194149136543,\n 0.0031591616570949554,\n 0.0,\n 0.0,\n -0.07631348818540573,\n -0.003744617337360978,\n 0.042295172810554504,\n -0.011318785138428211,\n 0.050445880740880966,\n 0.08449503779411316,\n 0.1241786777973175,\n 0.0753684714436531,\n 0.039063822478055954,\n 0.09467952698469162,\n 0.0054320949129760265,\n -0.005048719234764576,\n -0.03366478532552719,\n -0.0038599905092269182,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n 4\n ],\n [\n 3,\n 4,\n 4,\n 0,\n 1,\n 1,\n 1,\n 2,\n 3,\n 4,\n 4,\n 2,\n 2,\n 0,\n 0,\n 4,\n 0,\n 1,\n 2,\n 0,\n 3,\n 4,\n 2,\n 2,\n 3,\n 3,\n 0,\n 1,\n 3,\n 0,\n 3,\n 2,\n 3,\n 4,\n 1,\n 3,\n 3,\n 3,\n 2,\n 1,\n 3,\n 4,\n 2,\n 3,\n 4,\n 1,\n 4,\n 0,\n 4,\n 1,\n 1,\n 4,\n 1,\n 4,\n 0,\n 1,\n 0,\n 0,\n 4,\n 0,\n 4,\n 2,\n 3,\n 1,\n 2,\n 2,\n 4,\n 3,\n 4,\n 2,\n 2,\n 4,\n 4,\n 2,\n 1,\n 3,\n 2,\n 1,\n 4,\n 1,\n 0,\n 1,\n 2,\n 1,\n 2,\n 1,\n 2,\n 1,\n 1,\n 4,\n 1,\n 2,\n 4,\n 0,\n 4,\n 1,\n 2,\n 1,\n 1,\n 3\n ]\n ],\n \"test_loss_functions[categorical_crossentropy-True]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.08147776,\n 0.01847786,\n 0.07045883,\n -0.00269106,\n -0.03189164,\n 0.01643312,\n 0.1185048,\n 0.02166386,\n 0.00905327,\n 0.06592228,\n 0.04471018,\n -0.02879605,\n 0.04668707,\n 0.06856851,\n 0.06857751,\n 0.00657996,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[categorical_crossentropy-False]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0023582461,\n 0.00048802234,\n 0.0016699843,\n -6.4777887e-05,\n -0.0014215634,\n -0.00013359448,\n 0.0020448549,\n 0.00028171093,\n 0.00019665064,\n 0.0015335126,\n 0.0017000455,\n -0.00020136381,\n 0.00064588618,\n 0.0020524357,\n 0.002199081,\n 0.00083692279,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[categorical_hinge-False]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0023582461,\n 0.00048802234,\n 0.0016699843,\n -6.4777887e-05,\n -0.0014215634,\n -0.00013359448,\n 0.0020448549,\n 0.00028171093,\n 0.00019665064,\n 0.0015335126,\n 0.0017000455,\n -0.00020136381,\n 0.00064588618,\n 0.0020524357,\n 0.002199081,\n 0.00083692279,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[sparse_categorical_crossentropy-True]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.08147776,\n 0.01847786,\n 0.07045883,\n -0.00269106,\n -0.03189164,\n 0.01643312,\n 0.1185048,\n 0.02166386,\n 0.00905327,\n 0.06592228,\n 0.04471018,\n -0.02879605,\n 0.04668707,\n 0.06856851,\n 0.06857751,\n 0.00657996,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[sparse_categorical_crossentropy-False]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0023582461,\n 0.00048802234,\n 0.0016699843,\n -6.4777887e-05,\n -0.0014215634,\n -0.00013359448,\n 0.0020448549,\n 0.00028171093,\n 0.00019665064,\n 0.0015335126,\n 0.0017000455,\n -0.00020136381,\n 0.00064588618,\n 0.0020524357,\n 0.002199081,\n 0.00083692279,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[kullback_leibler_divergence-False]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0023582461,\n 0.00048802234,\n 0.0016699843,\n -6.4777887e-05,\n -0.0014215634,\n -0.00013359448,\n 0.0020448549,\n 0.00028171093,\n 0.00019665064,\n 0.0015335126,\n 0.0017000455,\n -0.00020136381,\n 0.00064588618,\n 0.0020524357,\n 0.002199081,\n 0.00083692279,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[categorical_hinge-True]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.08147776,\n 0.01847786,\n 0.07045883,\n -0.00269106,\n -0.03189164,\n 0.01643312,\n 0.1185048,\n 0.02166386,\n 0.00905327,\n 0.06592228,\n 0.04471018,\n -0.02879605,\n 0.04668707,\n 0.06856851,\n 0.06857751,\n 0.00657996,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_loss_functions[kullback_leibler_divergence-True]\": [\n [\n 7,\n 1,\n 1,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 8,\n 4,\n 4,\n 4,\n 4,\n 3,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 7,\n 4,\n 3,\n 4,\n 7,\n 0,\n 7,\n 7,\n 1,\n 1,\n 7,\n 7,\n 4,\n 0,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 3,\n 0,\n 7,\n 4,\n 0,\n 1,\n 7,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 7,\n 4,\n 4,\n 4,\n 4,\n 4,\n 1,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4\n ],\n [\n 0.0,\n 0.0,\n 0.0,\n 0.08147776,\n 0.01847786,\n 0.07045883,\n -0.00269106,\n -0.03189164,\n 0.01643312,\n 0.1185048,\n 0.02166386,\n 0.00905327,\n 0.06592228,\n 0.04471018,\n -0.02879605,\n 0.04668707,\n 0.06856851,\n 0.06857751,\n 0.00657996,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n {\n \"categorical_hinge\": [\n 0.0,\n 0.0,\n 0.0,\n -0.00644846,\n -0.00274792,\n -0.01334668,\n -0.01417109,\n 0.03608133,\n 0.00670766,\n 0.02741555,\n -0.00938758,\n 0.002172,\n 0.01400783,\n -0.00224488,\n -0.01445661,\n 0.01775403,\n 0.00643058,\n 0.00382644,\n -0.01077214,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"sparse_categorical_crossentropy\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ],\n \"kullback_leibler_divergence\": [\n 0.0,\n 0.0,\n 0.0,\n -0.09573442,\n -0.0089094,\n 0.01402334,\n 0.0258659,\n 0.08960329,\n 0.10324767,\n 0.10624839,\n 0.06578761,\n -0.00018638,\n -0.01345262,\n -0.08770822,\n -0.04990875,\n 0.04288402,\n -0.06845165,\n -0.08588978,\n -0.08277036,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n }\n ],\n \"test_compute_loss\": [198.34773, 1037.3748779296875]\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_deeplearning_common.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nimport logging\nimport os\nfrom os import listdir, path\nimport pickle\nimport tempfile\n\nimport keras\nimport numpy as np\nimport pytest\nfrom tensorflow.keras.callbacks import LearningRateScheduler\n\nfrom art.defences.preprocessor import FeatureSqueezing, JpegCompression, SpatialSmoothing\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_get_activations(art_warning, get_default_mnist_subset, framework, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n batch_size = 128\n for i, name in enumerate(classifier.layer_names):\n activation_i = classifier.get_activations(x_test_mnist, i, batch_size=batch_size)\n activation_name = classifier.get_activations(x_test_mnist, name, batch_size=batch_size)\n np.testing.assert_array_equal(activation_name, activation_i)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_loss_gradient_with_wildcard(art_warning, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(wildcard=True)\n shapes = [(1, 10, 1), (1, 20, 1)]\n for shape in shapes:\n x = np.random.normal(size=shape)\n y = np.array([[0, 1]])\n loss_gradient = classifier.loss_gradient(x, y=y)\n assert loss_gradient.shape == shape\n\n class_gradient = classifier.class_gradient(x, 0)\n assert class_gradient[0].shape == shape\n\n except ARTTestException as e:\n art_warning(e)\n\n\n# change for all other tests using that fitted model\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_fit(art_warning, get_default_mnist_subset, default_batch_size, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n labels = np.argmax(y_test_mnist, axis=1)\n classifier, sess = image_dl_estimator(from_logits=True)\n\n accuracy = np.sum(np.argmax(classifier.predict(x_test_mnist), axis=1) == labels) / x_test_mnist.shape[0]\n np.testing.assert_array_almost_equal(accuracy, 0.32, decimal=0.06)\n\n classifier.fit(x_train_mnist, y_train_mnist, batch_size=default_batch_size, nb_epochs=2)\n accuracy_2 = np.sum(np.argmax(classifier.predict(x_test_mnist), axis=1) == labels) / x_test_mnist.shape[0]\n np.testing.assert_array_almost_equal(accuracy_2, 0.73, decimal=0.06)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\n@pytest.mark.skipif(keras.__version__.startswith(\"2.2\"), reason=\"requires Keras 2.3.0 or higher\")\ndef test_predict(\n art_warning, framework, get_default_mnist_subset, image_dl_estimator, expected_values, store_expected_values\n):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n\n y_predicted = classifier.predict(x_test_mnist[0:1])\n np.testing.assert_array_almost_equal(y_predicted, expected_values(), decimal=4)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_shapes(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, sess = image_dl_estimator(from_logits=True)\n\n predictions = classifier.predict(x_test_mnist)\n assert predictions.shape == y_test_mnist.shape\n\n assert classifier.nb_classes == 10\n\n class_gradients = classifier.class_gradient(x_test_mnist[:11])\n assert class_gradients.shape == tuple([11, 10] + list(x_test_mnist[1].shape))\n\n loss_gradients = classifier.loss_gradient(x_test_mnist[:11], y_test_mnist[:11])\n assert loss_gradients.shape == x_test_mnist[:11].shape\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\n@pytest.mark.parametrize(\"from_logits\", [True, False])\n@pytest.mark.parametrize(\n \"loss_name\",\n [\"categorical_crossentropy\", \"categorical_hinge\", \"sparse_categorical_crossentropy\", \"kullback_leibler_divergence\"],\n)\ndef test_loss_functions(\n art_warning,\n image_dl_estimator,\n get_default_mnist_subset,\n loss_name,\n supported_losses_proba,\n supported_losses_logit,\n store_expected_values,\n supported_losses_types,\n from_logits,\n expected_values,\n):\n # prediction and class_gradient should be independent of logits/probabilities and of loss function\n\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n if from_logits:\n supported_losses = supported_losses_logit()\n else:\n supported_losses = supported_losses_proba()\n\n for loss_type in supported_losses_types():\n (y_test_pred_exp, class_gradient_exp, loss_grad_exp) = expected_values()\n # store_expected_values(expected_values)\n\n if loss_name + \"_\" + loss_type in supported_losses:\n classifier, _ = image_dl_estimator(loss_name=loss_name, loss_type=loss_type, from_logits=from_logits)\n\n y_test_pred_exp = np.argmax(classifier.predict(x=x_test_mnist), axis=1)\n np.testing.assert_array_equal(y_test_pred_exp, y_test_pred_exp)\n\n class_gradient = classifier.class_gradient(x_test_mnist, label=5)\n # np.testing.assert_array_almost_equal(class_gradient[99, 0, 14, :, 0], class_gradient_prob_exp)\n np.testing.assert_array_almost_equal(class_gradient[99, 0, 14, :, 0], class_gradient_exp)\n\n loss_gradient_value = classifier.loss_gradient(x=x_test_mnist, y=y_test_mnist)\n np.testing.assert_array_almost_equal(loss_gradient_value[99, 14, :, 0], loss_grad_exp[loss_name])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"huggingface\", \"tensorflow2\", \"kerastf\")\ndef test_pickle(art_warning, image_dl_estimator, image_dl_estimator_defended, tmp_path):\n try:\n full_path = os.path.join(tmp_path, \"my_classifier.p\")\n\n classifier, _ = image_dl_estimator(functional=True)\n with open(full_path, \"wb\") as save_file:\n pickle.dump(classifier, save_file)\n\n with open(full_path, \"rb\") as load_file:\n loaded = pickle.load(load_file)\n\n assert (classifier._clip_values == loaded._clip_values).all()\n assert classifier._channels_first == loaded._channels_first\n if hasattr(classifier, \"_use_logits\"):\n assert classifier._use_logits == loaded._use_logits\n if hasattr(classifier, \"_input_layer\"):\n assert classifier._input_layer == loaded._input_layer\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\", \"pytorch\", \"huggingface\")\ndef test_functional_model(art_warning, image_dl_estimator):\n try:\n # Need to update the functional_model code to produce a model with more than one input and output layers...\n classifier, _ = image_dl_estimator(functional=True, input_layer=1, output_layer=1)\n assert \"input1\" in classifier._input.name\n assert \"output1\" in classifier._output.name\n\n classifier, _ = image_dl_estimator(functional=True, input_layer=0, output_layer=0)\n assert \"input0\" in classifier._input.name\n assert \"output0\" in classifier._output.name\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_fit_kwargs(\n art_warning, image_dl_estimator, get_default_mnist_subset, image_data_generator, default_batch_size, framework\n):\n try:\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n\n def get_lr(_):\n return 0.01\n\n # Test a valid callback\n classifier, sess = image_dl_estimator(from_logits=True)\n\n kwargs = {\"callbacks\": [LearningRateScheduler(get_lr)]}\n classifier.fit(x_train_mnist, y_train_mnist, batch_size=default_batch_size, nb_epochs=1, verbose=True, **kwargs)\n\n # Check for fit_generator kwargs as well\n data_gen = image_data_generator(sess=sess)\n classifier.fit_generator(generator=data_gen, nb_epochs=1, **kwargs)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_defences_predict(art_warning, get_default_mnist_subset, image_dl_estimator_defended, image_dl_estimator):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator()\n y_check_clean = classifier.predict(x_test_mnist)\n clip_values = (0, 1)\n\n classifier_defended, _ = image_dl_estimator_defended(defenses=[\"FeatureSqueezing\"])\n assert len(classifier_defended.preprocessing_defences) == 1\n y_defended = classifier_defended.predict(x_test_mnist)\n fs = FeatureSqueezing(clip_values=clip_values, bit_depth=2)\n x_test_defense, _ = fs(x_test_mnist, y_test_mnist)\n y_check = classifier.predict(x_test_defense)\n np.testing.assert_array_almost_equal(y_defended, y_check, decimal=4)\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, y_check, y_check_clean)\n\n classifier_defended, _ = image_dl_estimator_defended(defenses=[\"JpegCompression\"])\n assert len(classifier_defended.preprocessing_defences) == 1\n y_defended = classifier_defended.predict(x_test_mnist)\n jpeg = JpegCompression(\n clip_values=clip_values, apply_predict=True, channels_first=classifier_defended.channels_first\n )\n x_test_defense, _ = jpeg(x_test_mnist, y_test_mnist)\n y_check = classifier.predict(x_test_defense)\n np.testing.assert_array_almost_equal(y_defended, y_check, decimal=4)\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, y_check, y_check_clean)\n\n classifier_defended, _ = image_dl_estimator_defended(defenses=[\"SpatialSmoothing\"])\n assert len(classifier_defended.preprocessing_defences) == 1\n y_defended = classifier_defended.predict(x_test_mnist)\n smooth = SpatialSmoothing(channels_first=classifier_defended.channels_first)\n x_test_defense, _ = smooth(x_test_mnist, y_test_mnist)\n y_check = classifier.predict(x_test_defense)\n np.testing.assert_array_almost_equal(y_defended, y_check, decimal=4)\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, y_check, y_check_clean)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n# change for all other tests using that fitted model\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_fit_image_generator(\n art_warning, framework, image_dl_estimator, image_data_generator, get_default_mnist_subset\n):\n try:\n classifier, sess = image_dl_estimator(from_logits=True)\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n true_class = np.argmax(y_test_mnist, axis=1)\n\n predictions = classifier.predict(x_test_mnist)\n prediction_class = np.argmax(predictions, axis=1)\n pre_fit_accuracy = np.sum(prediction_class == true_class) / x_test_mnist.shape[0]\n\n assert pre_fit_accuracy == pytest.approx(0.32, abs=0.01)\n\n data_gen = image_data_generator(sess=sess)\n classifier.fit_generator(generator=data_gen, nb_epochs=2)\n predictions = classifier.predict(x_test_mnist)\n prediction_class = np.argmax(predictions, axis=1)\n post_fit_accuracy = np.sum(prediction_class == true_class) / x_test_mnist.shape[0]\n\n np.testing.assert_array_almost_equal(post_fit_accuracy, 0.68, decimal=0.06)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\n@pytest.mark.skipif(keras.__version__.startswith(\"2.2\"), reason=\"requires Keras 2.3.0 or higher\")\ndef test_loss_gradient(\n art_warning,\n framework,\n get_default_mnist_subset,\n image_dl_estimator,\n expected_values,\n mnist_shape,\n store_expected_values,\n):\n try:\n (expected_gradients_1, expected_gradients_2) = expected_values()\n\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(from_logits=True)\n\n gradients = classifier.loss_gradient(x_test_mnist, y_test_mnist)\n\n assert gradients.shape == (x_test_mnist.shape[0],) + mnist_shape\n\n if mnist_shape[0] == 1:\n sub_gradients = gradients[0, 0, :, 14]\n else:\n sub_gradients = gradients[0, :, 14, 0]\n\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_1[0],\n decimal=expected_gradients_1[1],\n )\n\n if mnist_shape[0] == 1:\n sub_gradients = gradients[0, 0, 14, :]\n else:\n sub_gradients = gradients[0, 14, :, 0]\n\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_2[0],\n decimal=expected_gradients_2[1],\n )\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_nb_classes(art_warning, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n assert classifier.nb_classes == 10\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_input_shape(art_warning, image_dl_estimator, mnist_shape):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n assert classifier.input_shape == mnist_shape\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"non_dl_frameworks\")\ndef test_save_1(art_warning, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n t_file = tempfile.NamedTemporaryFile()\n model_path = t_file.name\n t_file.close()\n filename = \"model_to_save.keras\"\n classifier.save(filename, path=model_path)\n\n assert path.exists(model_path)\n\n created_model = False\n\n for file in listdir(model_path):\n if filename in file:\n created_model = True\n assert created_model\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"non_dl_frameworks\")\ndef test_save_2(art_warning, image_dl_estimator, get_default_mnist_subset, tmp_path):\n try:\n classifier, _ = image_dl_estimator()\n (x_train_mnist, y_train_mnist), (_, _) = get_default_mnist_subset\n classifier.fit(x_train_mnist, y_train_mnist, batch_size=128, nb_epochs=2)\n full_path = tmp_path / \"sub\"\n full_path.mkdir()\n\n assert not os.listdir(full_path._str)\n classifier.save(\"modelFile.keras\", path=full_path._str)\n assert os.listdir(full_path._str)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_repr(art_warning, image_dl_estimator, framework, expected_values, store_expected_values):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n repr_ = repr(classifier)\n for message in expected_values():\n assert message in repr_, \"{0}: was not contained within repr\".format(message)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\n@pytest.mark.skipif(keras.__version__.startswith(\"2.2\"), reason=\"requires Keras 2.3.0 or higher\")\ndef test_class_gradient(\n art_warning,\n framework,\n image_dl_estimator,\n get_default_mnist_subset,\n mnist_shape,\n store_expected_values,\n expected_values,\n):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n\n (\n grad_1_all_labels,\n grad_2_all_labels,\n grad_1_label5,\n grad_2_label5,\n grad_1_labelArray,\n grad_2_labelArray,\n labels_list,\n ) = expected_values()\n\n labels = np.array(labels_list, dtype=object)\n\n # TODO we should consider checking channel independent columns to make this test truly framework independent\n def get_gradient1_column(gradients):\n if mnist_shape[0] == 1:\n return gradients[0, 5, 0, 14, :] # expected_gradients_1_all_labels\n else:\n return gradients[0, 5, 14, :, 0]\n\n def get_gradient2_column(gradients):\n if mnist_shape[0] == 1:\n return gradients[0, 5, 0, :, 14] # expected_gradients_2_all_labels\n else:\n return gradients[0, 5, :, 14, 0]\n\n def get_gradient3_column(gradients):\n if mnist_shape[0] == 1:\n return gradients[0, 0, 0, 14, :] # expected_gradients_1_label5\n else:\n return gradients[0, 0, 14, :, 0]\n\n def get_gradient4_column(gradients):\n if mnist_shape[0] == 1:\n return gradients[0, 0, 0, :, 14] # expected_gradients_2_all_labels\n else:\n return gradients[0, 0, :, 14, 0]\n\n # Test all gradients label\n gradients = classifier.class_gradient(x_test_mnist)\n\n new_shape = (\n x_test_mnist.shape[0],\n 10,\n ) + mnist_shape\n assert gradients.shape == new_shape\n\n sub_gradients2 = get_gradient2_column(gradients)\n np.testing.assert_array_almost_equal(\n sub_gradients2,\n grad_2_all_labels[0],\n decimal=4,\n )\n\n # Test 1 gradient label = 5\n gradients = classifier.class_gradient(x_test_mnist, label=5)\n\n assert (\n gradients.shape\n == (\n x_test_mnist.shape[0],\n 1,\n )\n + mnist_shape\n )\n\n sub_gradients2 = get_gradient3_column(gradients)\n np.testing.assert_array_almost_equal(\n sub_gradients2,\n grad_1_label5[0],\n decimal=4,\n )\n\n sub_gradients4 = get_gradient4_column(gradients)\n np.testing.assert_array_almost_equal(\n sub_gradients4,\n grad_2_label5[0],\n decimal=4,\n )\n\n # # Test a set of gradients label = array\n gradients = classifier.class_gradient(x_test_mnist, label=labels)\n\n new_shape = (\n x_test_mnist.shape[0],\n 1,\n ) + mnist_shape\n assert gradients.shape == new_shape\n\n sub_gradients5 = get_gradient3_column(gradients)\n np.testing.assert_array_almost_equal(\n sub_gradients5,\n grad_1_labelArray[0],\n decimal=4,\n )\n\n sub_gradients6 = get_gradient4_column(gradients)\n np.testing.assert_array_almost_equal(\n sub_gradients6,\n grad_2_labelArray[0],\n decimal=4,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"non_dl_frameworks\")\ndef test_compute_loss(\n art_warning,\n framework,\n image_dl_estimator,\n get_default_mnist_subset,\n mnist_shape,\n store_expected_values,\n expected_values,\n):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n classifier, _ = image_dl_estimator(from_logits=True)\n expected_loss = expected_values()\n computed_loss = float(classifier.compute_loss(x=x_test_mnist, y=y_test_mnist, reduction=\"sum\"))\n\n assert pytest.approx(computed_loss, rel=0.01) in expected_loss\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_clone_for_refitting(\n art_warning,\n image_dl_estimator,\n):\n try:\n classifier, _ = image_dl_estimator(functional=True)\n _ = classifier.clone_for_refitting()\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_deeplearning_specific.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_loss_gradient_amp[cpu]\": [\n [\n 2.1159649e-05,\n 2.1398067e-05,\n 5.2034855e-05,\n 5.4776669e-05,\n -2.3066998e-05,\n 4.3153763e-05,\n 2.7418137e-05,\n 0.0,\n -0.0,\n -0.00058364868,\n -6.1690807e-05,\n 0.00052642822,\n -0.0002373457,\n 0.00052785873,\n 0.0010719299,\n 0.0012779236,\n 0.00068902969,\n 0.0001333952,\n 0.0010032654,\n 0.00016820431,\n -2.8014183e-06,\n -0.00055932999,\n 0.00014781952,\n -0.0,\n 0.0,\n -0.0,\n 0.0,\n -0.0\n ],\n [\n 0.00055932999,\n 0.00053405762,\n 0.00064897537,\n 0.00079298019,\n -0.00040316582,\n -0.0011281967,\n 0.00018537045,\n 3.2603741e-05,\n 0.00081682205,\n 0.00033354759,\n 0.00031805038,\n -0.00024235249,\n -0.00078201294,\n -0.00047016144,\n 0.0010719299,\n 0.00040864944,\n -0.00034427643,\n 0.00010716915,\n -0.00042295456,\n -0.0001386404,\n 0.00028300285,\n -0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n ],\n \"test_loss_gradient_amp[gpu]\": [\n [\n 2.1159649e-05,\n 2.1398067e-05,\n 5.2034855e-05,\n 5.4776669e-05,\n -2.3066998e-05,\n 4.3153763e-05,\n 2.7418137e-05,\n 0.0,\n -0.0,\n -0.00058364868,\n -6.1690807e-05,\n 0.00052642822,\n -0.0002373457,\n 0.00052785873,\n 0.0010719299,\n 0.0012779236,\n 0.00068902969,\n 0.0001333952,\n 0.0010032654,\n 0.00016820431,\n -2.8014183e-06,\n -0.00055932999,\n 0.00014781952,\n -0.0,\n 0.0,\n -0.0,\n 0.0,\n -0.0\n ],\n [\n 0.00055932999,\n 0.00053405762,\n 0.00064897537,\n 0.00079298019,\n -0.00040316582,\n -0.0011281967,\n 0.00018537045,\n 3.2603741e-05,\n 0.00081682205,\n 0.00033354759,\n 0.00031805038,\n -0.00024235249,\n -0.00078201294,\n -0.00047016144,\n 0.0010719299,\n 0.00040864944,\n -0.00034427643,\n 0.00010716915,\n -0.00042295456,\n -0.0001386404,\n 0.00028300285,\n -0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0\n ]\n ]\n}\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_deeplearning_specific.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport logging\nimport numpy as np\nimport pytest\nimport pickle\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.conv = nn.Conv2d(1, 2, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.fc = nn.Linear(288, 10)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv(x)))\n x = x.view(-1, 288)\n logit_output = self.fc(x)\n return logit_output\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_device(art_warning):\n try:\n\n class Flatten(nn.Module):\n def forward(self, x):\n n, _, _, _ = x.size()\n result = x.view(n, -1)\n\n return result\n\n # Define the network\n model = nn.Sequential(nn.Conv2d(1, 2, 5), nn.ReLU(), nn.MaxPool2d(2, 2), Flatten(), nn.Linear(288, 10))\n\n # Define a loss function and optimizer\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n\n # First test cpu\n classifier_cpu = PyTorchClassifier(\n model=model,\n clip_values=(0, 1),\n loss=loss_fn,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n device_type=\"cpu\",\n )\n\n assert classifier_cpu._device == torch.device(\"cpu\")\n assert classifier_cpu._device != torch.device(\"cuda\")\n\n # Then test gpu\n if torch.cuda.device_count() >= 2:\n with torch.cuda.device(0):\n classifier_gpu0 = PyTorchClassifier(\n model=model,\n clip_values=(0, 1),\n loss=loss_fn,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n assert classifier_gpu0._device == torch.device(\"cuda:0\")\n assert classifier_gpu0._device != torch.device(\"cuda:1\")\n\n with torch.cuda.device(1):\n classifier_gpu1 = PyTorchClassifier(\n model=model,\n clip_values=(0, 1),\n loss=loss_fn,\n optimizer=optimizer,\n input_shape=(1, 28, 28),\n nb_classes=10,\n )\n assert classifier_gpu1._device == torch.device(\"cuda:1\")\n assert classifier_gpu1._device != torch.device(\"cuda:0\")\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pickle(art_warning, get_default_mnist_subset, image_dl_estimator):\n try:\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n from art import config\n\n full_path = os.path.join(config.ART_DATA_PATH, \"my_classifier\")\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # The model used within the common ART pytorch get_image_classifier_list does not support pickling\n model = Model()\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n myclassifier_2 = PyTorchClassifier(\n model=model, clip_values=(0, 1), loss=loss_fn, optimizer=optimizer, input_shape=(1, 28, 28), nb_classes=10\n )\n myclassifier_2.fit(x_train_mnist, y_train_mnist, batch_size=100, nb_epochs=1)\n\n pickle.dump(myclassifier_2, open(full_path, \"wb\"))\n\n with open(full_path, \"rb\") as f:\n loaded_model = pickle.load(f)\n np.testing.assert_equal(myclassifier_2._clip_values, loaded_model._clip_values)\n assert myclassifier_2._channels_first == loaded_model._channels_first\n assert set(myclassifier_2.__dict__.keys()) == set(loaded_model.__dict__.keys())\n\n # Test predict\n predictions_1 = myclassifier_2.predict(x_test_mnist)\n accuracy_1 = np.sum(np.argmax(predictions_1, axis=1) == np.argmax(y_test_mnist, axis=1)) / y_test_mnist.shape[0]\n predictions_2 = loaded_model.predict(x_test_mnist)\n accuracy_2 = np.sum(np.argmax(predictions_2, axis=1) == np.argmax(y_test_mnist, axis=1)) / y_test_mnist.shape[0]\n assert accuracy_1 == accuracy_2\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"apex.amp\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_loss_gradient_amp(\n art_warning,\n get_default_mnist_subset,\n image_dl_estimator,\n expected_values,\n mnist_shape,\n device_type,\n):\n import torch\n import torch.nn as nn\n\n from art.estimators.classification.pytorch import PyTorchClassifier\n\n try:\n (expected_gradients_1, expected_gradients_2) = expected_values()\n\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n classifier, _ = image_dl_estimator(from_logits=True)\n optimizer = torch.optim.Adam(classifier.model.parameters(), lr=0.01)\n\n # Redefine the classifier with amp\n clip_values = (0, 1)\n criterion = nn.CrossEntropyLoss()\n classifier = PyTorchClassifier(\n clip_values=clip_values,\n model=classifier.model,\n preprocessing_defences=[],\n loss=criterion,\n input_shape=(1, 28, 28),\n nb_classes=10,\n device_type=device_type,\n optimizer=optimizer,\n use_amp=True,\n loss_scale=1.0,\n )\n\n # Compute loss gradients\n gradients = classifier.loss_gradient(x_test_mnist, y_test_mnist)\n\n # Test shape\n assert gradients.shape == (x_test_mnist.shape[0],) + mnist_shape\n\n # First test of gradients\n sub_gradients = gradients[0, 0, :, 14]\n\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_1,\n decimal=4,\n )\n\n # Second test of gradients\n sub_gradients = gradients[0, 0, 14, :]\n\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_2,\n decimal=4,\n )\n\n # Compute loss gradients with framework\n gradients = classifier.loss_gradient_framework(\n torch.tensor(x_test_mnist).to(classifier.device), torch.tensor(y_test_mnist).to(classifier.device)\n )\n gradients = gradients.cpu().numpy()\n\n # Test shape\n assert gradients.shape == (x_test_mnist.shape[0],) + mnist_shape\n\n # First test of gradients\n sub_gradients = gradients[0, 0, :, 14]\n\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_1,\n decimal=4,\n )\n\n # Second test of gradients\n sub_gradients = gradients[0, 0, 14, :]\n\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_2,\n decimal=4,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow2\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_tensorflow_1_state(\n art_warning,\n image_dl_estimator,\n):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n state = classifier.__getstate__()\n assert isinstance(state, dict)\n classifier.__setstate__(state=state)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_detector_classifier.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport tempfile\nimport logging\nimport unittest\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.estimators.classification.detector_classifier import DetectorClassifier\n\nfrom tests.utils import TestBase, get_image_classifier_pt\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(nn.Module):\n def __init__(self, model):\n super(Model, self).__init__()\n self.model = model\n\n def forward(self, x):\n x = self.model(x)\n x = x - 100000\n\n return x\n\n\nclass Flatten(nn.Module):\n def forward(self, x):\n n, _, _, _ = x.size()\n result = x.view(n, -1)\n\n return result\n\n\nclass TestDetectorClassifier(TestBase):\n \"\"\"\n This class tests the Detector Classifier.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.x_train_mnist = np.reshape(cls.x_train_mnist, (cls.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n cls.x_test_mnist = np.reshape(cls.x_test_mnist, (cls.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n\n # Define the internal classifier\n classifier = get_image_classifier_pt()\n\n # Define the internal detector\n conv = nn.Conv2d(1, 16, 5)\n linear = nn.Linear(2304, 1)\n torch.nn.init.xavier_uniform_(conv.weight)\n torch.nn.init.xavier_uniform_(linear.weight)\n model = nn.Sequential(conv, nn.ReLU(), nn.MaxPool2d(2, 2), Flatten(), linear)\n model = Model(model)\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n detector = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(1, 28, 28), nb_classes=2, clip_values=(0, 1)\n )\n\n # Define the detector-classifier\n cls.detector_classifier = DetectorClassifier(classifier=classifier, detector=detector)\n\n cls.x_train_mnist = np.reshape(cls.x_train_mnist, (cls.x_train_mnist.shape[0], 28, 28, 1)).astype(np.float32)\n cls.x_test_mnist = np.reshape(cls.x_test_mnist, (cls.x_test_mnist.shape[0], 28, 28, 1)).astype(np.float32)\n\n def setUp(self):\n self.x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n self.x_test_mnist = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 1, 28, 28)).astype(np.float32)\n super().setUp()\n\n def tearDown(self):\n self.x_train_mnist = np.reshape(self.x_train_mnist, (self.x_train_mnist.shape[0], 28, 28, 1)).astype(np.float32)\n self.x_test_mnist = np.reshape(self.x_test_mnist, (self.x_test_mnist.shape[0], 28, 28, 1)).astype(np.float32)\n super().tearDown()\n\n def test_predict(self):\n predictions = self.detector_classifier.predict(x=self.x_test_mnist[0:1])\n predictions_expected = 7\n self.assertEqual(predictions.shape, (1, 11))\n self.assertEqual(np.argmax(predictions, axis=1)[0], predictions_expected)\n\n def test_nb_classes(self):\n self.assertEqual(self.detector_classifier.nb_classes, 11)\n\n def test_input_shape(self):\n self.assertEqual(self.detector_classifier.input_shape, (1, 28, 28))\n\n def test_class_gradient_1(self):\n # Test label = None\n gradients = self.detector_classifier.class_gradient(x=self.x_test_mnist[0:1], label=None)\n self.assertEqual(gradients.shape, (1, 11, 1, 28, 28))\n\n def test_class_gradient_2(self):\n # Test label = 5\n gradients = self.detector_classifier.class_gradient(x=self.x_test_mnist, label=5)\n self.assertEqual(gradients.shape, (self.n_test, 1, 1, 28, 28))\n\n def test_class_gradient_3(self):\n # Test label = 10 (detector classifier has 11 classes (10 + 1))\n gradients = self.detector_classifier.class_gradient(x=self.x_test_mnist, label=10)\n self.assertEqual(gradients.shape, (self.n_test, 1, 1, 28, 28))\n\n def test_class_gradient_4(self):\n # Test label = array\n n_test_local = 2\n label = np.array([2, 10])\n gradients = self.detector_classifier.class_gradient(x=self.x_test_mnist[0:n_test_local], label=label)\n self.assertEqual(gradients.shape, (n_test_local, 1, 1, 28, 28))\n\n def test_save(self):\n model = self.detector_classifier\n t_file = tempfile.NamedTemporaryFile()\n full_path = t_file.name\n t_file.close()\n base_name = os.path.basename(full_path)\n dir_name = os.path.dirname(full_path)\n model.save(base_name, path=dir_name)\n\n self.assertTrue(os.path.exists(full_path + \"_classifier.optimizer\"))\n self.assertTrue(os.path.exists(full_path + \"_classifier.model\"))\n os.remove(full_path + \"_classifier.optimizer\")\n os.remove(full_path + \"_classifier.model\")\n\n self.assertTrue(os.path.exists(full_path + \"_detector.optimizer\"))\n self.assertTrue(os.path.exists(full_path + \"_detector.model\"))\n os.remove(full_path + \"_detector.optimizer\")\n os.remove(full_path + \"_detector.model\")\n\n def test_repr(self):\n repr_ = repr(self.detector_classifier)\n self.assertIn(\"art.estimators.classification.detector_classifier.DetectorClassifier\", repr_)\n self.assertIn(\n \"preprocessing=StandardisationMeanStd(mean=0.0, std=1.0, apply_fit=True, apply_predict=True)\", repr_\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_ensemble.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport keras.backend as k\nimport numpy as np\n\nfrom art.estimators.classification.ensemble import EnsembleClassifier\nfrom tests.utils import TestBase, get_image_classifier_kr\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestEnsembleClassifier(TestBase):\n \"\"\"\n This class tests the ensemble classifier.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n # Use twice the same classifier for unit-testing, in application they would be different\n classifier_1 = get_image_classifier_kr()\n classifier_2 = get_image_classifier_kr()\n cls.ensemble = EnsembleClassifier(classifiers=[classifier_1, classifier_2], clip_values=(0, 1))\n\n @classmethod\n def tearDownClass(cls):\n k.clear_session()\n\n def test_fit(self):\n with self.assertRaises(NotImplementedError):\n self.ensemble.fit(self.x_train_mnist, self.y_train_mnist)\n\n def test_fit_generator(self):\n with self.assertRaises(NotImplementedError):\n self.ensemble.fit_generator(None)\n\n def test_layers(self):\n with self.assertRaises(NotImplementedError):\n self.ensemble.get_activations(self.x_test_mnist, layer=2)\n\n def test_predict(self):\n predictions = self.ensemble.predict(self.x_test_mnist, raw=False)\n self.assertTrue(predictions.shape, (self.n_test, 10))\n\n expected_predictions_1 = np.asarray(\n [\n 0.12109935,\n 0.0498215,\n 0.0993958,\n 0.06410097,\n 0.11366927,\n 0.04645343,\n 0.06419807,\n 0.30685693,\n 0.07616713,\n 0.05823759,\n ]\n )\n np.testing.assert_array_almost_equal(predictions[0, :], expected_predictions_1, decimal=4)\n\n predictions_raw = self.ensemble.predict(self.x_test_mnist, raw=True)\n self.assertEqual(predictions_raw.shape, (2, self.n_test, 10))\n\n expected_predictions_2 = np.asarray(\n [\n 0.06054967,\n 0.02491075,\n 0.0496979,\n 0.03205048,\n 0.05683463,\n 0.02322672,\n 0.03209903,\n 0.15342847,\n 0.03808356,\n 0.02911879,\n ]\n )\n np.testing.assert_array_almost_equal(predictions_raw[0, 0, :], expected_predictions_2, decimal=4)\n\n def test_loss_gradient(self):\n gradients = self.ensemble.loss_gradient(self.x_test_mnist, self.y_test_mnist, raw=False)\n self.assertEqual(gradients.shape, (self.n_test, 28, 28, 1))\n\n expected_predictions_1 = np.asarray(\n [\n 0.0559206,\n 0.05338925,\n 0.0648919,\n 0.07925165,\n -0.04029291,\n -0.11281465,\n 0.01850601,\n 0.00325054,\n 0.08163195,\n 0.03333949,\n 0.031766,\n -0.02420463,\n -0.07815556,\n -0.04698735,\n 0.10711591,\n 0.04086434,\n -0.03441073,\n 0.01071284,\n -0.04229195,\n -0.01386157,\n 0.02827487,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n np.testing.assert_array_almost_equal(gradients[0, 14, :, 0], expected_predictions_1, decimal=4)\n\n gradients_2 = self.ensemble.loss_gradient(self.x_test_mnist, self.y_test_mnist, raw=True)\n self.assertEqual(gradients_2.shape, (2, self.n_test, 28, 28, 1))\n\n expected_predictions_2 = np.asarray(\n [\n -0.02444103,\n -0.06092717,\n -0.0449727,\n 0.00737736,\n -0.0462507,\n -0.06225448,\n -0.08359106,\n -0.00270847,\n -0.009243,\n -0.00214317,\n -0.04728884,\n 0.00369186,\n 0.02211389,\n 0.02094269,\n 0.00219593,\n -0.02638348,\n 0.00148741,\n -0.004582,\n -0.00621604,\n 0.01604268,\n 0.0174383,\n -0.01077293,\n -0.00548703,\n -0.01247547,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n np.testing.assert_array_almost_equal(gradients_2[0, 5, 14, :, 0], expected_predictions_2, decimal=4)\n\n def test_class_gradient(self):\n gradients = self.ensemble.class_gradient(self.x_test_mnist, None, raw=False)\n self.assertEqual(gradients.shape, (self.n_test, 10, 28, 28, 1))\n\n expected_predictions_1 = np.asarray(\n [\n -1.0557447e-03,\n -1.0079544e-03,\n -7.7426434e-04,\n 1.7387432e-03,\n 2.1773507e-03,\n 5.0880699e-05,\n 1.6497371e-03,\n 2.6113100e-03,\n 6.0904310e-03,\n 4.1080985e-04,\n 2.5268078e-03,\n -3.6661502e-04,\n -3.0568996e-03,\n -1.1665225e-03,\n 3.8904310e-03,\n 3.1726385e-04,\n 1.3203260e-03,\n -1.1720930e-04,\n -1.4315104e-03,\n -4.7676818e-04,\n 9.7251288e-04,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n ]\n )\n np.testing.assert_array_almost_equal(gradients[0, 5, 14, :, 0], expected_predictions_1, decimal=4)\n\n gradients_2 = self.ensemble.class_gradient(self.x_test_mnist, raw=True)\n self.assertEqual(gradients_2.shape, (2, self.n_test, 10, 28, 28, 1))\n\n expected_predictions_2 = np.asarray(\n [\n -5.2787235e-04,\n -5.0397718e-04,\n -3.8713217e-04,\n 8.6937158e-04,\n 1.0886753e-03,\n 2.5440349e-05,\n 8.2486856e-04,\n 1.3056550e-03,\n 3.0452155e-03,\n 2.0540493e-04,\n 1.2634039e-03,\n -1.8330751e-04,\n -1.5284498e-03,\n -5.8326125e-04,\n 1.9452155e-03,\n 1.5863193e-04,\n 6.6016300e-04,\n -5.8604652e-05,\n -7.1575522e-04,\n -2.3838409e-04,\n 4.8625644e-04,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n ]\n )\n np.testing.assert_array_almost_equal(gradients_2[0, 0, 5, 14, :, 0], expected_predictions_2, decimal=4)\n\n def test_repr(self):\n repr_ = repr(self.ensemble)\n self.assertIn(\"art.estimators.classification.ensemble.EnsembleClassifier\", repr_)\n self.assertIn(\"classifier_weights=array([0.5, 0.5])\", repr_)\n self.assertIn(\n \"channels_first=False, clip_values=array([0., 1.], dtype=float32), \"\n \"preprocessing_defences=None, postprocessing_defences=None, preprocessing=StandardisationMeanStd(mean=0.0, \"\n \"std=1.0, apply_fit=True, apply_predict=True)\",\n repr_,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_input_filter.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom tests.utils import TestBase, master_seed, get_image_classifier_kr_tf\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 500\nNB_TEST = 100\n\n\nclass TestInputFilter(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n def setUp(self):\n master_seed(1234)\n super().setUp()\n\n def test_fit(self):\n labels = np.argmax(self.y_test_mnist, axis=1)\n classifier = get_image_classifier_kr_tf()\n\n acc = np.sum(np.argmax(classifier.predict(self.x_test_mnist), axis=1) == labels) / NB_TEST\n logger.info(\"Accuracy: %.2f%%\", (acc * 100))\n\n classifier.fit(self.x_train_mnist, self.y_train_mnist, batch_size=BATCH_SIZE, nb_epochs=2)\n acc2 = np.sum(np.argmax(classifier.predict(self.x_test_mnist), axis=1) == labels) / NB_TEST\n logger.info(\"Accuracy: %.2f%%\", (acc2 * 100))\n\n self.assertEqual(acc, 0.32)\n self.assertGreaterEqual(acc2, 0.65)\n\n classifier.fit(self.x_train_mnist, y=self.y_train_mnist, batch_size=BATCH_SIZE, nb_epochs=2)\n classifier.fit(x=self.x_train_mnist, y=self.y_train_mnist, batch_size=BATCH_SIZE, nb_epochs=2)\n\n # def test_class_gradient(self):\n # classifier = get_image_classifier_kr_tf()\n #\n # # Test all gradients label\n # gradients = classifier.class_gradient(self.x_test_mnist)\n #\n # self.assertTrue(gradients.shape == (NB_TEST, 10, 28, 28, 1))\n #\n # expected_gradients_1 = np.asarray(\n # [\n # -1.0557447e-03,\n # -1.0079544e-03,\n # -7.7426434e-04,\n # 1.7387432e-03,\n # 2.1773507e-03,\n # 5.0880699e-05,\n # 1.6497371e-03,\n # 2.6113100e-03,\n # 6.0904310e-03,\n # 4.1080985e-04,\n # 2.5268078e-03,\n # -3.6661502e-04,\n # -3.0568996e-03,\n # -1.1665225e-03,\n # 3.8904310e-03,\n # 3.1726385e-04,\n # 1.3203260e-03,\n # -1.1720930e-04,\n # -1.4315104e-03,\n # -4.7676818e-04,\n # 9.7251288e-04,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 5, 14, :, 0], expected_gradients_1, decimal=4)\n #\n # expected_gradients_2 = np.asarray(\n # [\n # -0.00367321,\n # -0.0002892,\n # 0.00037825,\n # -0.00053344,\n # 0.00192121,\n # 0.00112047,\n # 0.0023135,\n # 0.0,\n # 0.0,\n # -0.00391743,\n # -0.0002264,\n # 0.00238103,\n # -0.00073711,\n # 0.00270405,\n # 0.00389043,\n # 0.00440818,\n # -0.00412769,\n # -0.00441794,\n # 0.00081916,\n # -0.00091284,\n # 0.00119645,\n # -0.00849089,\n # 0.00547925,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 5, :, 14, 0], expected_gradients_2, decimal=4)\n #\n # # Test 1 gradient label = 5\n # gradients = classifier.class_gradient(self.x_test_mnist, label=5)\n #\n # self.assertTrue(gradients.shape == (NB_TEST, 1, 28, 28, 1))\n #\n # expected_gradients_1 = np.asarray(\n # [\n # -1.0557447e-03,\n # -1.0079544e-03,\n # -7.7426434e-04,\n # 1.7387432e-03,\n # 2.1773507e-03,\n # 5.0880699e-05,\n # 1.6497371e-03,\n # 2.6113100e-03,\n # 6.0904310e-03,\n # 4.1080985e-04,\n # 2.5268078e-03,\n # -3.6661502e-04,\n # -3.0568996e-03,\n # -1.1665225e-03,\n # 3.8904310e-03,\n # 3.1726385e-04,\n # 1.3203260e-03,\n # -1.1720930e-04,\n # -1.4315104e-03,\n # -4.7676818e-04,\n # 9.7251288e-04,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 0, 14, :, 0], expected_gradients_1, decimal=4)\n #\n # expected_gradients_2 = np.asarray(\n # [\n # -0.00367321,\n # -0.0002892,\n # 0.00037825,\n # -0.00053344,\n # 0.00192121,\n # 0.00112047,\n # 0.0023135,\n # 0.0,\n # 0.0,\n # -0.00391743,\n # -0.0002264,\n # 0.00238103,\n # -0.00073711,\n # 0.00270405,\n # 0.00389043,\n # 0.00440818,\n # -0.00412769,\n # -0.00441794,\n # 0.00081916,\n # -0.00091284,\n # 0.00119645,\n # -0.00849089,\n # 0.00547925,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 0, :, 14, 0], expected_gradients_2, decimal=4)\n #\n # # Test a set of gradients label = array\n # label = np.random.randint(5, size=NB_TEST)\n # gradients = classifier.class_gradient(self.x_test_mnist, label=label)\n #\n # self.assertTrue(gradients.shape == (NB_TEST, 1, 28, 28, 1))\n #\n # expected_gradients_1 = np.asarray(\n # [\n # 5.0867125e-03,\n # 4.8564528e-03,\n # 6.1040390e-03,\n # 8.6531248e-03,\n # -6.0958797e-03,\n # -1.4114540e-02,\n # -7.1085989e-04,\n # -5.0330814e-04,\n # 1.2943064e-02,\n # 8.2416134e-03,\n # -1.9859476e-04,\n # -9.8109958e-05,\n # -3.8902222e-03,\n # -1.2945873e-03,\n # 7.5137997e-03,\n # 1.7720886e-03,\n # 3.1399424e-04,\n # 2.3657181e-04,\n # -3.0891625e-03,\n # -1.0211229e-03,\n # 2.0828887e-03,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # 0.0000000e00,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 0, 14, :, 0], expected_gradients_1, decimal=4)\n #\n # expected_gradients_2 = np.asarray(\n # [\n # -0.00195835,\n # -0.00134457,\n # -0.00307221,\n # -0.00340564,\n # 0.00175022,\n # -0.00239714,\n # -0.00122619,\n # 0.0,\n # 0.0,\n # -0.00520899,\n # -0.00046105,\n # 0.00414874,\n # -0.00171095,\n # 0.00429184,\n # 0.0075138,\n # 0.00792442,\n # 0.0019566,\n # 0.00035517,\n # 0.00504575,\n # -0.00037397,\n # 0.00022343,\n # -0.00530034,\n # 0.0020528,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 0, :, 14, 0], expected_gradients_2, decimal=4)\n #\n # def test_loss_gradient(self):\n # classifier = get_image_classifier_kr_tf()\n #\n # # Test gradient\n # gradients = classifier.loss_gradient(x=self.x_test_mnist, y=self.y_test_mnist)\n #\n # self.assertTrue(gradients.shape == (NB_TEST, 28, 28, 1))\n #\n # expected_gradients_1 = np.asarray(\n # [\n # 0.0559206,\n # 0.05338925,\n # 0.0648919,\n # 0.07925165,\n # -0.04029291,\n # -0.11281465,\n # 0.01850601,\n # 0.00325054,\n # 0.08163195,\n # 0.03333949,\n # 0.031766,\n # -0.02420463,\n # -0.07815556,\n # -0.04698735,\n # 0.10711591,\n # 0.04086434,\n # -0.03441073,\n # 0.01071284,\n # -0.04229195,\n # -0.01386157,\n # 0.02827487,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, 14, :, 0], expected_gradients_1, decimal=4)\n #\n # expected_gradients_2 = np.asarray(\n # [\n # 0.00210803,\n # 0.00213919,\n # 0.00520981,\n # 0.00548001,\n # -0.0023059,\n # 0.00432077,\n # 0.00274945,\n # 0.0,\n # 0.0,\n # -0.0583441,\n # -0.00616604,\n # 0.0526219,\n # -0.02373985,\n # 0.05273106,\n # 0.10711591,\n # 0.12773865,\n # 0.0689289,\n # 0.01337799,\n # 0.10032021,\n # 0.01681096,\n # -0.00028647,\n # -0.05588859,\n # 0.01474165,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # 0.0,\n # ]\n # )\n # np.testing.assert_array_almost_equal(gradients[0, :, 14, 0], expected_gradients_2, decimal=4)\n\n def test_layers(self):\n classifier = get_image_classifier_kr_tf()\n self.assertEqual(len(classifier.layer_names), 3)\n\n layer_names = classifier.layer_names\n for i, name in enumerate(layer_names):\n act_i = classifier.get_activations(self.x_test_mnist, i, batch_size=128)\n act_name = classifier.get_activations(self.x_test_mnist, name, batch_size=128)\n np.testing.assert_array_equal(act_name, act_i)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_jax.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_loss_gradient\": [\n [\n [\n 5.7007334e-08,\n -1.2159828e-07,\n 7.3952961e-08,\n -7.6091261e-08,\n -1.5173376e-07,\n -3.3684202e-08,\n -3.6483410e-08,\n -7.1950403e-08,\n -9.4847195e-08,\n 2.4720695e-08,\n -3.9136850e-08,\n 7.6634500e-08,\n 3.2928440e-08,\n 9.6518704e-08,\n -2.5718967e-07,\n 5.1464031e-08,\n 9.0709044e-08,\n -5.3285067e-08,\n -1.2674005e-07,\n 5.3067343e-08,\n 1.4236125e-08,\n 2.9228334e-08,\n -4.5179490e-08,\n -6.4782910e-08,\n -5.1073641e-08,\n 1.3607444e-08,\n 1.3632229e-07,\n -7.1737256e-09\n ],\n 4\n ],\n [\n [\n -2.5718967e-07,\n -9.4962358e-09,\n -4.2096822e-08,\n -5.2268156e-08,\n 5.4082140e-08,\n -3.1010543e-08,\n 1.4606437e-07,\n -1.5801379e-07,\n -6.3756580e-08,\n -1.8729553e-07,\n 4.4209742e-08,\n -5.9424867e-08,\n -2.5230258e-07,\n 2.0625974e-08,\n -6.9952262e-09,\n 2.5941466e-08,\n -8.0173876e-09,\n -6.5055005e-08,\n -3.9427686e-08,\n 4.5256215e-08,\n -1.2948578e-07,\n -8.0443714e-09,\n -2.9269282e-08,\n -8.4470116e-08,\n 6.3251292e-08,\n 3.4007662e-08,\n 4.8702319e-08,\n -4.8003166e-08\n ],\n 4\n ]\n ],\n \"test_predict\": [\n [\n -2.2984657,\n -2.2984138,\n -2.2961087,\n -2.3172646,\n -2.2990053,\n -2.3129113,\n -2.3047698,\n -2.3016658,\n -2.304994,\n -2.2925131\n ]\n ]\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_jax.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\nimport logging\n\nimport numpy as np\nimport pytest\nfrom jax import random\nfrom jax import grad, jit, vmap\nimport jax.numpy as jnp\nfrom jax.scipy.special import logsumexp\n\nfrom art.experimental.estimators.classification.jax import JaxClassifier\nfrom tests.utils import ARTTestException\n\n\nlogger = logging.getLogger(__name__)\n\n\n# Define a jax model\ndef jax_classifier():\n # Define model sizes\n layer_sizes = [784, 256, 128, 10]\n\n # Initialize random weights\n def random_init(m, n, k):\n w, b = random.split(k)\n rw, rb = random.normal(w, (n, m)) * 0.01, random.normal(b, (n,)) * 0.01\n return rw, rb\n\n model = [\n random_init(m, n, k) for m, n, k in zip(layer_sizes[:-1], layer_sizes[1:], random.split(random.PRNGKey(0), 4))\n ]\n\n # Forward function\n def forward(model, x):\n activation = jnp.reshape(x, 784)\n for w, b in model[:-1]:\n output = jnp.dot(w, activation) + b\n activation = jnp.maximum(0, output)\n\n f_w, f_b = model[-1]\n logit = jnp.dot(f_w, activation) + f_b\n return logit - logsumexp(logit)\n\n # Prediction function\n predict_func = vmap(forward, in_axes=(None, 0))\n\n # Loss function\n def loss_func(model, x, y):\n preds = predict_func(model, x)\n return -jnp.mean(preds * y)\n\n # Update function\n @jit\n def update_func(model, x, y):\n grads = grad(loss_func)(model, x, y)\n return [(w - 0.01 * dw, b - 0.01 * db) for (w, b), (dw, db) in zip(model, grads)]\n\n classifier = JaxClassifier(\n model=model,\n predict_func=predict_func,\n loss_func=loss_func,\n update_func=update_func,\n input_shape=(28, 28, 1),\n nb_classes=10,\n )\n\n return classifier\n\n\nclassifier = jax_classifier()\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_fit(art_warning, get_default_mnist_subset, default_batch_size):\n try:\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n labels = np.argmax(y_test_mnist, axis=1)\n\n accuracy = np.sum(np.argmax(classifier.predict(x_test_mnist), axis=1) == labels) / x_test_mnist.shape[0]\n np.testing.assert_array_almost_equal(accuracy, 0.32, decimal=0.06)\n\n classifier.fit(x_train_mnist, y_train_mnist, batch_size=default_batch_size, nb_epochs=2)\n accuracy_2 = np.sum(np.argmax(classifier.predict(x_test_mnist), axis=1) == labels) / x_test_mnist.shape[0]\n np.testing.assert_array_almost_equal(accuracy_2, 0.73, decimal=0.06)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_predict(art_warning, get_default_mnist_subset, expected_values):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n y_predicted = classifier.predict(x_test_mnist[0:1])\n\n np.testing.assert_array_almost_equal(y_predicted, expected_values(), decimal=4)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_shapes(art_warning, get_default_mnist_subset):\n try:\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n predictions = classifier.predict(x_test_mnist)\n\n assert predictions.shape == y_test_mnist.shape\n\n assert classifier.nb_classes == 10\n\n loss_gradients = classifier.loss_gradient(x_test_mnist[:11], y_test_mnist[:11])\n\n assert loss_gradients.shape == x_test_mnist[:11].shape\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_loss_gradient(art_warning, get_default_mnist_subset, expected_values, mnist_shape):\n try:\n (expected_gradients_1, expected_gradients_2) = expected_values()\n\n (_, _), (x_test_mnist, y_test_mnist) = get_default_mnist_subset\n\n gradients = classifier.loss_gradient(x_test_mnist, y_test_mnist)\n\n assert gradients.shape == (x_test_mnist.shape[0],) + mnist_shape\n\n sub_gradients = gradients[0, 0, :, 0]\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_1[0],\n decimal=expected_gradients_1[1],\n )\n\n sub_gradients = gradients[0, :, 14, 0]\n np.testing.assert_array_almost_equal(\n sub_gradients,\n expected_gradients_2[0],\n decimal=expected_gradients_2[1],\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_nb_classes(art_warning):\n try:\n assert classifier.nb_classes == 10\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_input_shape(art_warning, mnist_shape):\n try:\n assert classifier.input_shape == mnist_shape\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_lightgbm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport lightgbm as lgb\nimport numpy as np\n\nfrom art.estimators.classification.lightgbm import LightGBMClassifier\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestLightGBMClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.y_train_iris_index = np.argmax(cls.y_train_iris, axis=1)\n cls.y_test_iris_index = np.argmax(cls.y_test_iris, axis=1)\n\n num_round = 10\n param = {\"objective\": \"multiclass\", \"metric\": \"multi_logloss\", \"num_class\": 3}\n train_data = lgb.Dataset(cls.x_train_iris, label=cls.y_train_iris_index)\n model = lgb.train(param, train_data, num_round, valid_sets=[train_data])\n\n cls.classifier = LightGBMClassifier(model=model)\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.1083, 0.1255, 0.7663]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_query_efficient_bb.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport unittest\n\nimport keras.backend as k\nimport numpy as np\n\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.defences.preprocessor import FeatureSqueezing\nfrom art.utils import load_dataset, get_labels_np_array\nfrom art.estimators.classification.query_efficient_bb import QueryEfficientGradientEstimationClassifier\n\nfrom tests.utils import master_seed, get_image_classifier_kr, get_tabular_classifier_kr\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 100\nNB_TEST = 11\n\n\nclass TestClassifierAttack(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n x_train, y_train, x_test, y_test = x_train[:NB_TRAIN], y_train[:NB_TRAIN], x_test[:NB_TEST], y_test[:NB_TEST]\n cls.mnist = (x_train, y_train), (x_test, y_test)\n\n # Keras classifier\n cls.classifier_k = get_image_classifier_kr()\n\n def setUp(self):\n master_seed(seed=1234)\n\n @classmethod\n def tearDownClass(cls):\n k.clear_session()\n\n def test_without_defences(self):\n (x_train, y_train), (x_test, y_test) = self.mnist\n\n # Get the ready-trained Keras model and wrap it in query efficient gradient estimator\n classifier = QueryEfficientGradientEstimationClassifier(\n self.classifier_k, 20, 1 / 64.0, round_samples=1 / 255.0\n )\n\n attack = FastGradientMethod(classifier, eps=1)\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train == x_train_adv).all())\n self.assertFalse((x_test == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((y_train == train_y_pred).all())\n self.assertFalse((y_test == test_y_pred).all())\n\n def test_with_defences(self):\n (x_train, y_train), (x_test, y_test) = self.mnist\n\n # Get the trained Keras model\n model = self.classifier_k._model\n fs = FeatureSqueezing(bit_depth=1, clip_values=(0, 1))\n classifier = KerasClassifier(model=model, clip_values=(0, 1), preprocessing_defences=fs)\n\n # Create the classifier\n classifier = QueryEfficientGradientEstimationClassifier(classifier, 20, 1 / 64.0, round_samples=1 / 255.0)\n\n attack = FastGradientMethod(classifier, eps=1)\n x_train_adv = attack.generate(x_train)\n x_test_adv = attack.generate(x_test)\n\n self.assertFalse((x_train == x_train_adv).all())\n self.assertFalse((x_test == x_test_adv).all())\n\n train_y_pred = get_labels_np_array(classifier.predict(x_train_adv))\n test_y_pred = get_labels_np_array(classifier.predict(x_test_adv))\n\n self.assertFalse((y_train == train_y_pred).all())\n self.assertFalse((y_test == test_y_pred).all())\n\n\nclass TestQueryEfficientVectors(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # Get Iris\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"iris\")\n cls.iris = (x_train, y_train), (x_test, y_test)\n\n def setUp(self):\n master_seed(seed=1234)\n\n def test_iris_clipped(self):\n (_, _), (x_test, y_test) = self.iris\n\n classifier = get_tabular_classifier_kr()\n classifier = QueryEfficientGradientEstimationClassifier(classifier, 20, 1 / 64.0, round_samples=1 / 255.0)\n\n # Test untargeted attack\n attack = FastGradientMethod(classifier, eps=0.1)\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n self.assertTrue((x_test_adv <= 1).all())\n self.assertTrue((x_test_adv >= 0).all())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(y_test, axis=1) == preds_adv).all())\n\n def test_iris_unbounded(self):\n (_, _), (x_test, y_test) = self.iris\n classifier = get_tabular_classifier_kr()\n\n # Recreate a classifier without clip values\n classifier = KerasClassifier(model=classifier._model, use_logits=False, channels_first=True)\n classifier = QueryEfficientGradientEstimationClassifier(classifier, 20, 1 / 64.0, round_samples=1 / 255.0)\n attack = FastGradientMethod(classifier, eps=1)\n x_test_adv = attack.generate(x_test)\n self.assertFalse((x_test == x_test_adv).all())\n self.assertTrue((x_test_adv > 1).any())\n self.assertTrue((x_test_adv < 0).any())\n\n preds_adv = np.argmax(classifier.predict(x_test_adv), axis=1)\n self.assertFalse((np.argmax(y_test, axis=1) == preds_adv).all())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_scikitlearn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier\nfrom sklearn.ensemble import (\n AdaBoostClassifier,\n BaggingClassifier,\n ExtraTreesClassifier,\n GradientBoostingClassifier,\n RandomForestClassifier,\n)\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline\n\nfrom art.estimators.classification.scikitlearn import (\n ScikitlearnDecisionTreeClassifier,\n ScikitlearnExtraTreeClassifier,\n ScikitlearnAdaBoostClassifier,\n ScikitlearnBaggingClassifier,\n ScikitlearnExtraTreesClassifier,\n ScikitlearnGradientBoostingClassifier,\n ScikitlearnRandomForestClassifier,\n ScikitlearnLogisticRegression,\n ScikitlearnSVC,\n)\nfrom art.estimators.classification.scikitlearn import SklearnClassifier\nfrom art.utils import check_and_transform_label_format\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestScikitlearnDecisionTreeClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = DecisionTreeClassifier()\n cls.classifier = ScikitlearnDecisionTreeClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnDecisionTreeClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n def test_multi_label(self):\n x_train = self.x_train_iris\n y_train = self.y_train_iris\n x_test = self.x_test_iris\n y_test = self.y_test_iris\n\n # make multi-label binary\n y_train = np.column_stack((y_train, y_train, y_train))\n y_train[y_train > 1] = 1\n y_test = np.column_stack((y_test, y_test, y_test))\n y_test[y_test > 1] = 1\n\n underlying_model = DecisionTreeClassifier()\n underlying_model.fit(x_train, y_train)\n model = ScikitlearnDecisionTreeClassifier(model=underlying_model)\n\n pred = model.predict(x_test)\n assert pred[0].shape[0] == x_test.shape[0]\n assert isinstance(model.nb_classes, np.ndarray)\n with self.assertRaises(TypeError):\n check_and_transform_label_format(y_train, nb_classes=model.nb_classes)\n\n\nclass TestScikitlearnExtraTreeClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = ExtraTreeClassifier()\n cls.classifier = ScikitlearnExtraTreeClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnExtraTreeClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnAdaBoostClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = AdaBoostClassifier()\n cls.classifier = ScikitlearnAdaBoostClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnAdaBoostClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.25544427, 0.35099888, 0.39355685]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnBaggingClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = BaggingClassifier()\n cls.classifier = ScikitlearnBaggingClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnBaggingClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnExtraTreesClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = ExtraTreesClassifier(n_estimators=10)\n cls.classifier = ScikitlearnExtraTreesClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnExtraTreesClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnGradientBoostingClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = GradientBoostingClassifier(n_estimators=100)\n cls.classifier = ScikitlearnGradientBoostingClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnGradientBoostingClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[1.00105813e-05, 2.07276221e-05, 9.99969262e-01]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnRandomForestClassifier(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = RandomForestClassifier(n_estimators=10)\n cls.classifier = ScikitlearnRandomForestClassifier(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnRandomForestClassifier(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[11:12])\n y_expected = np.asarray([[0.9, 0.1, 0.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=1)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnLogisticRegression(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = LogisticRegression(\n verbose=0, C=1, solver=\"newton-cg\", dual=False, fit_intercept=True, multi_class=\"ovr\"\n )\n cls.classifier = ScikitlearnLogisticRegression(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnLogisticRegression(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.07997696, 0.36272544, 0.5572976]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=3)\n\n def test_class_gradient_none_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=None)\n grad_expected = [\n [\n [-1.97804999, 1.35988402, -6.28209543, -2.59983373],\n [-0.56164223, -0.70078993, -0.98865014, -0.66950917],\n [0.64962, 0.2610305, 1.54549754, 0.80910802],\n ]\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=3)\n\n def test_class_gradient_none_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=None)\n grad_expected = [\n [\n [\n -1.97804999,\n 1.35988402,\n -6.28209543,\n -2.59983397,\n ],\n [\n -0.56164235,\n -0.70078993,\n -0.98865038,\n -0.66950929,\n ],\n [\n 0.64961988,\n 0.26103044,\n 1.5454973,\n 0.8091079,\n ],\n ],\n [\n [-1.9202075, 1.34698176, -6.1180439, -2.5255065],\n [-0.50379974, -0.71369207, -0.82459873, -0.59518182],\n [0.70746249, 0.24812828, 1.70954895, 0.88343531],\n ],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=3)\n\n def test_class_gradient_int_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=1)\n grad_expected = [[[-0.56164223, -0.70078993, -0.98865014, -0.66950917]]]\n\n for i_shape in range(4):\n self.assertAlmostEqual(grad_predicted[0, 0, i_shape], grad_expected[0][0][i_shape], 3)\n\n def test_class_gradient_int_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=1)\n grad_expected = [\n [[-0.56164235, -0.70078993, -0.98865038, -0.66950929]],\n [[-0.50379974, -0.71369207, -0.82459873, -0.59518182]],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_list_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=[1])\n grad_expected = [[[-0.56164223, -0.70078993, -0.98865014, -0.66950917]]]\n\n for i_shape in range(4):\n self.assertAlmostEqual(grad_predicted[0, 0, i_shape], grad_expected[0][0][i_shape], 3)\n\n def test_class_gradient_list_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=[1, 2])\n grad_expected = [\n [[-0.56164235, -0.70078993, -0.98865038, -0.66950929]],\n [[0.70746249, 0.24812828, 1.70954895, 0.88343531]],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=3)\n\n def test_class_gradient_label_wrong_type(self):\n\n with self.assertRaises(TypeError) as context:\n _ = self.classifier.class_gradient(self.x_test_iris[0:2], label=np.asarray([0, 1, 0]))\n\n self.assertIn(\n \"Unrecognized type for argument `label` with type \", str(context.exception)\n )\n\n def test_loss_gradient(self):\n grad_predicted = self.classifier.loss_gradient(self.x_test_iris[0:1], self.y_test_iris[0:1])\n grad_expected = np.asarray([[-0.21654, -0.08701016, -0.51516586, -0.26970267]])\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnBinaryLogisticRegression(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n binary_class_index = np.argmax(cls.y_train_iris, axis=1) < 2\n x_train_binary = cls.x_train_iris[binary_class_index,]\n y_train_binary = cls.y_train_iris[binary_class_index,][:, [0, 1]]\n\n cls.sklearn_model = LogisticRegression(\n verbose=0, C=1, solver=\"newton-cg\", dual=False, fit_intercept=True, multi_class=\"ovr\"\n )\n cls.classifier = ScikitlearnLogisticRegression(model=cls.sklearn_model)\n cls.classifier.fit(x=x_train_binary, y=y_train_binary)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnLogisticRegression(model=\"sklearn_model\")\n\n def test_class_gradient(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=None)\n grad_expected = np.asarray(\n [[[-0.14551339, 0.12298754, -0.45839342, -0.17835225], [0.14551339, -0.12298754, 0.45839342, 0.17835225]]]\n )\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=3)\n\n def test_loss_gradient(self):\n binary_class_index = np.argmax(self.y_test_iris, axis=1) < 2\n x_test_binary = self.x_test_iris[binary_class_index,]\n y_test_binary = self.y_test_iris[binary_class_index,][:, [0, 1]]\n\n grad_predicted = self.classifier.loss_gradient(x_test_binary[0:1], y_test_binary[0:1])\n grad_expected = np.asarray([[-0.37703343, 0.31890249, -1.18813638, -0.46208951]])\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnSVCSVC(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = SVC(gamma=\"auto\")\n cls.classifier = ScikitlearnSVC(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnSVC(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_loss_gradient(self):\n grad_predicted = self.classifier.loss_gradient(self.x_test_iris[0:1], self.y_test_iris[0:1])\n grad_expected = np.asarray([[-2.9100819, 0.3048792, -7.935282, -3.840562]])\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_none_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=None)\n grad_expected = [\n [\n [-1.5939425, 1.67301144, -6.15095666, -2.4862934],\n [-0.40469415, -1.37572607, 0.46867108, -0.13317975],\n [1.99863665, -0.29728537, 5.68228559, 2.61947315],\n ]\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_none_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=None)\n grad_expected = [\n [\n [-1.5939425, 1.67301144, -6.15095666, -2.4862934],\n [-0.40469415, -1.37572607, 0.46867108, -0.13317975],\n [1.99863665, -0.29728537, 5.68228559, 2.61947315],\n ],\n [\n [-1.5962279, 1.64964639, -6.30453897, -2.60572715],\n [-0.40788449, -1.37232544, 0.53680777, -0.08368929],\n [2.00411239, -0.27732096, 5.7677312, 2.68941644],\n ],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_int_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=1)\n grad_expected = [[[-0.40469415, -1.37572607, 0.46867108, -0.13317975]]]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_int_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=1)\n grad_expected = [\n [[-0.40469415, -1.37572607, 0.46867108, -0.13317975]],\n [[-0.40788449, -1.37232544, 0.53680777, -0.08368929]],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_list_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=[1])\n grad_expected = [[[-0.40469415, -1.37572607, 0.46867108, -0.13317975]]]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_list_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=[1, 2])\n grad_expected = [\n [[-0.40469415, -1.37572607, 0.46867108, -0.13317975]],\n [[2.00411239, -0.27732096, 5.7677312, 2.68941644]],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_label_wrong_type(self):\n with self.assertRaises(TypeError) as context:\n _ = self.classifier.class_gradient(self.x_test_iris[0:2], label=np.asarray([0, 1, 0]))\n\n self.assertIn(\n \"Unrecognized type for argument `label` with type \", str(context.exception)\n )\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnSVCLinearSVC(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = LinearSVC()\n cls.classifier = ScikitlearnSVC(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(SklearnClassifier(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnSVC(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_loss_gradient(self):\n grad_predicted = self.classifier.loss_gradient(self.x_test_iris[0:1], self.y_test_iris[0:1])\n grad_expected = np.asarray([[0.38021886, 0.57562107, -3.599666, -2.3177252]])\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_none(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=None)\n grad_expected = [\n [\n [-0.34659522, 1.6376213, -3.51851979, -1.46078468],\n [-0.1121541, -2.51552211, 0.71569165, -0.44883585],\n [-0.380205, -0.57552204, 3.59972012, 2.31760663],\n ]\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_int_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=1)\n grad_expected = [[[-0.1121541, -2.51552211, 0.71569165, -0.44883585]]]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_int_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=1)\n grad_expected = [\n [[-0.1121541, -2.51552211, 0.71569165, -0.44883585]],\n [[-0.1121541, -2.51552211, 0.71569165, -0.44883585]],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_list_1(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:1], label=[1])\n grad_expected = [[[-0.1121541, -2.51552211, 0.71569165, -0.44883585]]]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_class_gradient_list_2(self):\n grad_predicted = self.classifier.class_gradient(self.x_test_iris[0:2], label=[1, 2])\n grad_expected = [\n [[-0.1121541, -2.51552211, 0.71569165, -0.44883585]],\n [[-0.380205, -0.57552204, 3.59972012, 2.31760663]],\n ]\n np.testing.assert_array_almost_equal(grad_predicted, grad_expected, decimal=4)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nclass TestScikitlearnPipeline(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n svc = SVC(C=1.0, kernel=\"rbf\", gamma=\"auto\")\n pca = PCA()\n sklearn_model = Pipeline(steps=[(\"pca\", pca), (\"svc\", svc)])\n cls.classifier = SklearnClassifier(model=sklearn_model)\n cls.classifier.fit(x=cls.x_train_iris, y=cls.y_train_iris)\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n with self.assertRaises(TypeError):\n TestScikitlearnPipeline(model=\"sklearn_model\")\n\n def test_input_shape(self):\n self.assertEqual(self.classifier.input_shape, (4,))\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/classification/test_xgboost.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport xgboost as xgb\nimport numpy as np\n\nfrom art.estimators.classification.xgboost import XGBoostClassifier\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestXGBoostClassifierBoosterSoftprob(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n num_round = 10\n param = {\"objective\": \"multi:softprob\", \"metric\": \"multi_logloss\", \"num_class\": 3}\n train_data = xgb.DMatrix(cls.x_train_iris, label=np.argmax(cls.y_train_iris, axis=1))\n eval_list = [(train_data, \"train\")]\n model = xgb.train(param, train_data, num_round, eval_list)\n\n cls.classifier = XGBoostClassifier(model=model, nb_classes=3)\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0236, 0.0268, 0.9496]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_type(self):\n with self.assertRaises(TypeError):\n XGBoostClassifier(model=\"xgb\")\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone(self):\n with self.assertRaises(NotImplementedError):\n self.classifier.clone_for_refitting()\n\n\nclass TestXGBoostClassifierBoosterSoftmax(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n num_round = 10\n param = {\"objective\": \"multi:softmax\", \"metric\": \"multi_logloss\", \"num_class\": 3}\n train_data = xgb.DMatrix(cls.x_train_iris, label=np.argmax(cls.y_train_iris, axis=1))\n eval_list = [(train_data, \"train\")]\n model = xgb.train(param, train_data, num_round, eval_list)\n\n cls.classifier = XGBoostClassifier(model=model, nb_classes=3)\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.0, 0.0, 1.0]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n\nclass TestXGBoostClassifierPythonAPI(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n model = xgb.XGBClassifier(n_estimators=30, max_depth=5)\n model.fit(cls.x_train_iris, np.argmax(cls.y_train_iris, axis=1))\n\n cls.classifier = XGBoostClassifier(model=model)\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_iris[0:1])\n y_expected = np.asarray([[0.00280161, 0.00359648, 0.99360186]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=4)\n\n def test_clone(self):\n new_classifier = self.classifier.clone_for_refitting()\n new_params = new_classifier.get_params()\n del new_params[\"model\"]\n prev_params = self.classifier.get_params()\n del prev_params[\"model\"]\n assert new_params == prev_params\n assert new_classifier.nb_classes == 3\n new_classifier.fit(self.x_test_iris, np.argmax(self.y_test_iris, axis=1))\n assert new_classifier.nb_classes == 3\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef get_pytorch_object_detector_data(get_default_cifar10_subset):\n import cv2\n\n (_, _), (x_test_cifar10, _) = get_default_cifar10_subset\n x_test = cv2.resize(np.reshape(x_test_cifar10[0], (32, 32, 3)), dsize=(416, 416), interpolation=cv2.INTER_CUBIC)\n x_test = np.transpose(x_test, (2, 0, 1))\n x_test = np.expand_dims(x_test, axis=0)\n y_test = [\n {\n \"boxes\": np.asarray([[6, 22, 413, 346], [0, 24, 406, 342]], dtype=np.float32),\n \"labels\": np.asarray([21, 18]),\n \"scores\": np.asarray([1, 1], dtype=np.float32),\n \"masks\": np.ones((1, 416, 416)) / 2,\n }\n ]\n\n yield x_test, y_test\n\n\n@pytest.fixture()\ndef get_pytorch_object_detector(get_pytorch_object_detector_data):\n \"\"\"\n This class tests the PyTorchObjectDetector object detector.\n \"\"\"\n import torch\n import torchvision\n\n from art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\n\n # Define object detector\n model = torchvision.models.detection.fasterrcnn_resnet50_fpn(\n pretrained=True, progress=True, num_classes=91, pretrained_backbone=True\n )\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.01)\n\n object_detector = PyTorchObjectDetector(\n model=model,\n input_shape=(3, 416, 416),\n optimizer=optimizer,\n clip_values=(0, 1),\n channels_first=True,\n attack_losses=[\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"],\n )\n\n x_test, y_test = get_pytorch_object_detector_data\n\n yield object_detector, x_test, y_test\n\n\n@pytest.fixture()\ndef get_pytorch_object_detector_mask(get_pytorch_object_detector_data):\n \"\"\"\n This class tests the PyTorchObjectDetector object detector.\n \"\"\"\n import torch\n import torchvision\n\n from art.estimators.object_detection.pytorch_object_detector import PyTorchObjectDetector\n\n # Define object detector\n model = torchvision.models.detection.maskrcnn_resnet50_fpn(\n pretrained=True, progress=True, num_classes=91, pretrained_backbone=True\n )\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.01)\n\n object_detector = PyTorchObjectDetector(\n model=model,\n input_shape=(3, 416, 416),\n optimizer=optimizer,\n clip_values=(0, 1),\n channels_first=True,\n attack_losses=[\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"],\n )\n\n x_test, y_test = get_pytorch_object_detector_data\n\n yield object_detector, x_test, y_test\n\n\n@pytest.fixture()\ndef get_pytorch_faster_rcnn(get_pytorch_object_detector_data):\n \"\"\"\n This class tests the PyTorchFasterRCNN object detector.\n \"\"\"\n import torch\n\n from art.estimators.object_detection.pytorch_faster_rcnn import PyTorchFasterRCNN\n\n # Define object detector\n object_detector = PyTorchFasterRCNN(\n input_shape=(3, 416, 416),\n clip_values=(0, 1),\n channels_first=True,\n attack_losses=[\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"],\n )\n params = [p for p in object_detector.model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.01)\n\n object_detector.set_params(optimizer=optimizer)\n\n x_test, y_test = get_pytorch_object_detector_data\n\n yield object_detector, x_test, y_test\n\n\n@pytest.fixture()\ndef get_pytorch_yolo(get_pytorch_object_detector_data):\n \"\"\"\n This class tests the PyTorchYolo object detector.\n \"\"\"\n import torch\n\n from pytorchyolo import models\n from pytorchyolo.utils.loss import compute_loss\n\n from art.estimators.object_detection.pytorch_yolo import PyTorchYolo\n\n model_path = \"/tmp/PyTorch-YOLOv3/config/yolov3.cfg\"\n weights_path = \"/tmp/PyTorch-YOLOv3/weights/yolov3.weights\"\n model = models.load_model(model_path=model_path, weights_path=weights_path)\n\n class YoloV3(torch.nn.Module):\n def __init__(self, model):\n super().__init__()\n self.model = model\n\n def forward(self, x, targets=None):\n if self.training:\n outputs = self.model(x)\n # loss is averaged over a batch. Thus, for patch generation use batch_size = 1\n loss, _ = compute_loss(outputs, targets, self.model)\n\n loss_components = {\"loss_total\": loss}\n\n return loss_components\n else:\n return self.model(x)\n\n model = YoloV3(model)\n\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.01)\n\n object_detector = PyTorchYolo(\n model=model,\n input_shape=(3, 416, 416),\n optimizer=optimizer,\n clip_values=(0, 1),\n channels_first=True,\n attack_losses=(\"loss_total\",),\n )\n\n x_test, y_test = get_pytorch_object_detector_data\n\n yield object_detector, x_test, y_test\n\n\n@pytest.fixture()\ndef get_pytorch_detr(get_pytorch_object_detector_data):\n \"\"\"\n This class tests the PyTorchDetectionTransformer object detector.\n \"\"\"\n import torch\n\n from art.estimators.object_detection.pytorch_detection_transformer import PyTorchDetectionTransformer\n\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n object_detector = PyTorchDetectionTransformer(\n input_shape=(3, 416, 416),\n clip_values=(0, 1),\n preprocessing=(mean, std),\n channels_first=True,\n attack_losses=(\"loss_ce\", \"loss_bbox\", \"loss_giou\"),\n )\n params = [p for p in object_detector.model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.01)\n\n object_detector.set_params(optimizer=optimizer)\n\n x_test, y_test = get_pytorch_object_detector_data\n\n yield object_detector, x_test, y_test\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_object_seeker_faster_rcnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.estimators.certification.object_seeker import PyTorchObjectSeeker\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_train(art_warning, get_pytorch_faster_rcnn):\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n object_seeker = PyTorchObjectSeeker(\n model=object_detector.model,\n input_shape=object_detector.input_shape,\n channels_first=object_detector.channels_first,\n optimizer=object_detector.optimizer,\n clip_values=object_detector.clip_values,\n attack_losses=object_detector.attack_losses,\n detector_type=\"Faster-RCNN\",\n num_lines=3,\n confidence_threshold=0.3,\n iou_threshold=0.4,\n prune_threshold=0.5,\n device_type=\"cpu\",\n )\n\n try:\n # Compute loss before training\n loss1 = object_seeker.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_seeker.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_seeker.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_predict(art_warning, get_pytorch_faster_rcnn):\n object_detector, x_test, _ = get_pytorch_faster_rcnn\n object_seeker = PyTorchObjectSeeker(\n model=object_detector.model,\n input_shape=object_detector.input_shape,\n channels_first=object_detector.channels_first,\n optimizer=object_detector.optimizer,\n clip_values=object_detector.clip_values,\n attack_losses=object_detector.attack_losses,\n detector_type=\"Faster-RCNN\",\n num_lines=3,\n confidence_threshold=0.3,\n iou_threshold=0.4,\n prune_threshold=0.5,\n device_type=\"cpu\",\n )\n\n try:\n result = object_seeker.predict(x=x_test)\n\n assert len(result) == len(x_test)\n assert list(result[0].keys()) == [\"boxes\", \"labels\", \"scores\"]\n assert np.all(result[0][\"scores\"] >= 0.3)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_certify(art_warning, get_pytorch_faster_rcnn):\n object_detector, x_test, _ = get_pytorch_faster_rcnn\n object_seeker = PyTorchObjectSeeker(\n model=object_detector.model,\n input_shape=object_detector.input_shape,\n channels_first=object_detector.channels_first,\n optimizer=object_detector.optimizer,\n clip_values=object_detector.clip_values,\n attack_losses=object_detector.attack_losses,\n detector_type=\"Faster-RCNN\",\n num_lines=3,\n confidence_threshold=0.3,\n iou_threshold=0.4,\n prune_threshold=0.5,\n device_type=\"cpu\",\n )\n\n try:\n result = object_seeker.certify(x=x_test, patch_size=0.01, offset=0.1)\n\n assert len(result) == len(x_test)\n assert np.any(result[0])\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_object_seeker_yolo.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.estimators.certification.object_seeker import PyTorchObjectSeeker\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_train(art_warning, get_pytorch_yolo):\n object_detector, x_test, y_test = get_pytorch_yolo\n object_seeker = PyTorchObjectSeeker(\n model=object_detector.model,\n input_shape=object_detector.input_shape,\n channels_first=object_detector.channels_first,\n optimizer=object_detector.optimizer,\n clip_values=object_detector.clip_values,\n attack_losses=object_detector.attack_losses,\n detector_type=\"YOLO\",\n num_lines=3,\n confidence_threshold=0.3,\n iou_threshold=0.4,\n prune_threshold=0.5,\n device_type=\"cpu\",\n )\n\n try:\n # Compute loss before training\n loss1 = object_seeker.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_seeker.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_seeker.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_predict(art_warning, get_pytorch_yolo):\n object_detector, x_test, _ = get_pytorch_yolo\n object_seeker = PyTorchObjectSeeker(\n model=object_detector.model,\n input_shape=object_detector.input_shape,\n channels_first=object_detector.channels_first,\n optimizer=object_detector.optimizer,\n clip_values=object_detector.clip_values,\n attack_losses=object_detector.attack_losses,\n detector_type=\"YOLO\",\n num_lines=3,\n confidence_threshold=0.3,\n iou_threshold=0.4,\n prune_threshold=0.5,\n device_type=\"cpu\",\n )\n\n try:\n result = object_seeker.predict(x=x_test)\n\n assert len(result) == len(x_test)\n assert list(result[0].keys()) == [\"boxes\", \"labels\", \"scores\"]\n assert np.all(result[0][\"scores\"] >= 0.3)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_certify(art_warning, get_pytorch_yolo):\n object_detector, x_test, _ = get_pytorch_yolo\n object_seeker = PyTorchObjectSeeker(\n model=object_detector.model,\n input_shape=object_detector.input_shape,\n channels_first=object_detector.channels_first,\n optimizer=object_detector.optimizer,\n clip_values=object_detector.clip_values,\n attack_losses=object_detector.attack_losses,\n detector_type=\"YOLO\",\n num_lines=3,\n confidence_threshold=0.3,\n iou_threshold=0.4,\n prune_threshold=0.5,\n device_type=\"cpu\",\n )\n\n try:\n result = object_seeker.certify(x=x_test, patch_size=0.01, offset=0.1)\n\n assert len(result) == len(x_test)\n assert np.any(result[0])\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_pytorch_detection_transformer.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_predict(art_warning, get_pytorch_detr):\n try:\n from art.utils import non_maximum_suppression\n\n object_detector, x_test, _ = get_pytorch_detr\n\n preds = object_detector.predict(x_test)\n result = non_maximum_suppression(preds[0], iou_threshold=0.4, confidence_threshold=0.3)\n assert list(result.keys()) == [\"boxes\", \"labels\", \"scores\"]\n\n assert result[\"boxes\"].shape == (3, 4)\n expected_detection_boxes = np.asarray(\n [\n [1.0126123, 25.658852, 412.70746, 379.12537],\n [-0.089400, 272.08664, 415.90994, 416.25930],\n [0.1522941, 75.882440, 99.139565, 335.11273],\n ]\n )\n np.testing.assert_array_almost_equal(result[\"boxes\"], expected_detection_boxes, decimal=3)\n\n assert result[\"scores\"].shape == (3,)\n expected_detection_scores = np.asarray([0.8424455, 0.7796526, 0.35387915])\n np.testing.assert_array_almost_equal(result[\"scores\"], expected_detection_scores, decimal=3)\n\n assert result[\"labels\"].shape == (3,)\n expected_detection_classes = np.asarray([17, 65, 17])\n np.testing.assert_array_equal(result[\"labels\"], expected_detection_classes)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_fit(art_warning, get_pytorch_detr):\n try:\n object_detector, x_test, y_test = get_pytorch_detr\n\n # Compute loss before training\n loss1 = object_detector.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_detector.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_loss_gradient(art_warning, get_pytorch_detr):\n try:\n object_detector, x_test, y_test = get_pytorch_detr\n\n grads = object_detector.loss_gradient(x=x_test, y=y_test)\n\n assert grads.shape == (1, 3, 416, 416)\n\n expected_gradients1 = np.asarray(\n [\n 0.02891439,\n 0.0055933,\n -0.00687808,\n 0.0095074,\n 0.00247894,\n 0.00122704,\n -0.00482378,\n -0.00924361,\n -0.02870164,\n -0.00683936,\n 0.00904205,\n -0.01315971,\n -0.0151937,\n -0.00156442,\n 0.00775309,\n 0.01946152,\n 0.00523211,\n -0.01682214,\n 0.00079588,\n 0.01627164,\n -0.01347653,\n -0.00512358,\n 0.00610363,\n 0.02831643,\n 0.00742467,\n 0.00293561,\n 0.01380033,\n 0.02112359,\n 0.01725711,\n -0.00431877,\n -0.01007722,\n -0.00526983,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 208, 192:224], expected_gradients1, decimal=2)\n\n expected_gradients2 = np.asarray(\n [\n -0.00549417,\n -0.01592844,\n -0.01073932,\n -0.00443333,\n -0.00780143,\n -0.02033146,\n -0.0191503,\n 0.01227987,\n 0.019971,\n 0.01034214,\n -0.00918145,\n -0.02458049,\n -0.00708776,\n -0.00826812,\n -0.01284431,\n -0.00195021,\n 0.00523211,\n 0.00661678,\n 0.00851441,\n 0.01157211,\n -0.00324841,\n -0.00395823,\n 0.00756641,\n 0.00405913,\n -0.00055517,\n 0.00221484,\n -0.02415526,\n -0.02096599,\n 0.00980014,\n 0.00174731,\n -0.01008899,\n 0.00305779,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 192:224, 208], expected_gradients2, decimal=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_errors(art_warning):\n try:\n from torch import hub\n\n from art.estimators.object_detection.pytorch_detection_transformer import PyTorchDetectionTransformer\n\n model = hub.load(\"facebookresearch/detr\", \"detr_resnet50\", pretrained=True)\n\n with pytest.raises(ValueError):\n PyTorchDetectionTransformer(\n model=model,\n clip_values=(1, 2),\n attack_losses=(\"loss_ce\", \"loss_bbox\", \"loss_giou\"),\n )\n\n with pytest.raises(ValueError):\n PyTorchDetectionTransformer(\n model=model,\n clip_values=(-1, 1),\n attack_losses=(\"loss_ce\", \"loss_bbox\", \"loss_giou\"),\n )\n\n from art.defences.postprocessor.rounded import Rounded\n\n post_def = Rounded()\n with pytest.raises(ValueError):\n PyTorchDetectionTransformer(\n model=model,\n clip_values=(0, 1),\n attack_losses=(\"loss_ce\", \"loss_bbox\", \"loss_giou\"),\n postprocessing_defences=post_def,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_preprocessing_defences(art_warning, get_pytorch_detr):\n try:\n object_detector, x_test, _ = get_pytorch_detr\n\n from art.defences.preprocessor.spatial_smoothing_pytorch import SpatialSmoothingPyTorch\n\n pre_def = SpatialSmoothingPyTorch()\n\n object_detector.set_params(preprocessing_defences=pre_def)\n\n # Create labels\n result = object_detector.predict(x=x_test)\n\n y = [\n {\n \"boxes\": result[0][\"boxes\"],\n \"labels\": result[0][\"labels\"],\n \"scores\": np.ones_like(result[0][\"labels\"]),\n }\n ]\n\n # Compute gradients\n grads = object_detector.loss_gradient(x=x_test, y=y)\n\n assert grads.shape == (1, 3, 416, 416)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_compute_losses(art_warning, get_pytorch_detr):\n try:\n object_detector, x_test, y_test = get_pytorch_detr\n losses = object_detector.compute_losses(x=x_test, y=y_test)\n assert len(losses) == 3\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_compute_loss(art_warning, get_pytorch_detr):\n try:\n object_detector, x_test, y_test = get_pytorch_detr\n\n # Compute loss\n loss = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert pytest.approx(2.172381, abs=0.1) == float(loss)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pgd(art_warning, get_pytorch_detr):\n try:\n from art.attacks.evasion import ProjectedGradientDescent\n\n object_detector, x_test, y_test = get_pytorch_detr\n\n attack = ProjectedGradientDescent(estimator=object_detector, max_iter=2)\n x_test_adv = attack.generate(x=x_test, y=y_test)\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, x_test_adv, x_test)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_pytorch_faster_rcnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_predict(art_warning, get_pytorch_faster_rcnn):\n try:\n from art.utils import non_maximum_suppression\n\n object_detector, x_test, _ = get_pytorch_faster_rcnn\n\n preds = object_detector.predict(x_test)\n result = non_maximum_suppression(preds[0], iou_threshold=0.4, confidence_threshold=0.3)\n assert list(result.keys()) == [\"boxes\", \"labels\", \"scores\"]\n\n assert result[\"boxes\"].shape == (2, 4)\n expected_detection_boxes = np.asarray(\n [\n [6.136914, 22.481018, 413.05814, 346.08746],\n [0.000000, 24.181173, 406.47644, 342.62213],\n ]\n )\n np.testing.assert_array_almost_equal(result[\"boxes\"], expected_detection_boxes, decimal=3)\n\n assert result[\"scores\"].shape == (2,)\n expected_detection_scores = np.asarray([0.4237412, 0.35696018])\n np.testing.assert_array_almost_equal(result[\"scores\"], expected_detection_scores, decimal=3)\n\n assert result[\"labels\"].shape == (2,)\n expected_detection_classes = np.asarray([21, 18])\n np.testing.assert_array_equal(result[\"labels\"], expected_detection_classes)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_fit(art_warning, get_pytorch_faster_rcnn):\n try:\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n\n # Compute loss before training\n loss1 = object_detector.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_detector.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_loss_gradient(art_warning, get_pytorch_faster_rcnn):\n try:\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n\n # Compute gradients\n grads = object_detector.loss_gradient(x_test, y_test)\n assert grads.shape == (1, 3, 416, 416)\n\n expected_gradients1 = np.asarray(\n [\n -7.2145270e-04,\n -3.9774503e-04,\n -5.5271841e-04,\n 2.5251633e-04,\n -4.1167819e-05,\n 1.2919735e-04,\n 1.1148686e-04,\n 4.9278833e-04,\n 9.6094189e-04,\n 1.1812975e-03,\n 2.7167992e-04,\n 9.7095188e-05,\n 1.4456113e-04,\n -8.8345587e-06,\n 4.7151549e-05,\n -1.3497710e-04,\n -2.3394797e-04,\n 1.3777621e-04,\n 3.2994794e-04,\n 3.7001527e-04,\n -2.5945838e-04,\n -8.3444244e-04,\n -6.9832127e-04,\n -3.0403296e-04,\n -5.4019055e-04,\n -3.4545487e-04,\n -5.6993403e-04,\n -2.9818740e-04,\n -9.8479632e-04,\n -4.1015903e-04,\n -6.2145875e-04,\n -1.1365353e-03,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 208, 192:224], expected_gradients1, decimal=2)\n\n expected_gradients2 = np.asarray(\n [\n 0.00015462,\n 0.00028882,\n -0.00018248,\n -0.00114344,\n -0.00160104,\n -0.00190151,\n -0.00183488,\n -0.00191787,\n -0.00018382,\n 0.00095297,\n 0.00042502,\n 0.00024631,\n 0.0002915,\n 0.00053676,\n 0.00028635,\n 0.00035274,\n -0.00023395,\n -0.00044685,\n -0.00016795,\n 0.00059767,\n 0.00060389,\n 0.00010305,\n 0.0011498,\n 0.00135104,\n 0.00095133,\n 0.00081004,\n 0.00061877,\n 0.00089056,\n 0.00056647,\n 0.00070012,\n 0.00016926,\n 0.00026042,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 192:224, 208], expected_gradients2, decimal=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_errors(art_warning):\n try:\n from art.estimators.object_detection.pytorch_faster_rcnn import PyTorchFasterRCNN\n\n with pytest.raises(ValueError):\n PyTorchFasterRCNN(\n clip_values=(1, 2),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n )\n\n with pytest.raises(ValueError):\n PyTorchFasterRCNN(\n clip_values=(-1, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n )\n\n from art.defences.postprocessor.rounded import Rounded\n\n post_def = Rounded()\n with pytest.raises(ValueError):\n PyTorchFasterRCNN(\n clip_values=(0, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n postprocessing_defences=post_def,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_preprocessing_defences(art_warning, get_pytorch_faster_rcnn):\n try:\n from art.defences.preprocessor.spatial_smoothing import SpatialSmoothing\n\n pre_def = SpatialSmoothing()\n\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n\n object_detector.set_params(preprocessing_defences=pre_def)\n\n # Compute gradients\n grads = object_detector.loss_gradient(x=x_test, y=y_test)\n\n assert grads.shape == (1, 3, 416, 416)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_compute_losses(art_warning, get_pytorch_faster_rcnn):\n try:\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n losses = object_detector.compute_losses(x=x_test, y=y_test)\n assert len(losses) == 4\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_compute_loss(art_warning, get_pytorch_faster_rcnn):\n try:\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n\n # Compute loss\n loss = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert pytest.approx(0.0995874, abs=0.05) == float(loss)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_pgd(art_warning, get_pytorch_faster_rcnn):\n try:\n from art.attacks.evasion import ProjectedGradientDescent\n\n object_detector, x_test, y_test = get_pytorch_faster_rcnn\n\n attack = ProjectedGradientDescent(estimator=object_detector, max_iter=2)\n x_test_adv = attack.generate(x=x_test, y=y_test)\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, x_test_adv, x_test)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_pytorch_object_detector.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_predict(art_warning, get_pytorch_object_detector):\n try:\n from art.utils import non_maximum_suppression\n\n object_detector, x_test, _ = get_pytorch_object_detector\n\n preds = object_detector.predict(x_test)\n result = non_maximum_suppression(preds[0], iou_threshold=0.4, confidence_threshold=0.3)\n assert list(result.keys()) == [\"boxes\", \"labels\", \"scores\"]\n\n assert result[\"boxes\"].shape == (2, 4)\n expected_detection_boxes = np.asarray(\n [\n [6.136914, 22.481018, 413.05814, 346.08746],\n [0.000000, 24.181173, 406.47644, 342.62213],\n ]\n )\n np.testing.assert_array_almost_equal(result[\"boxes\"], expected_detection_boxes, decimal=3)\n\n assert result[\"scores\"].shape == (2,)\n expected_detection_scores = np.asarray([0.4237412, 0.35696018])\n np.testing.assert_array_almost_equal(result[\"scores\"], expected_detection_scores, decimal=3)\n\n assert result[\"labels\"].shape == (2,)\n expected_detection_classes = np.asarray([21, 18])\n np.testing.assert_array_equal(result[\"labels\"], expected_detection_classes)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_predict_mask(art_warning, get_pytorch_object_detector_mask):\n try:\n from art.utils import non_maximum_suppression\n\n object_detector, x_test, _ = get_pytorch_object_detector_mask\n\n preds = object_detector.predict(x_test)\n result = non_maximum_suppression(preds[0], iou_threshold=0.4, confidence_threshold=0.3)\n assert list(result.keys()) == [\"boxes\", \"labels\", \"scores\"]\n\n assert result[\"boxes\"].shape == (2, 4)\n expected_detection_boxes = np.asarray(\n [\n [44.097942, 22.865257, 415.32070, 294.20483],\n [25.739365, 33.178577, 416.00000, 338.51460],\n ]\n )\n np.testing.assert_array_almost_equal(result[\"boxes\"], expected_detection_boxes, decimal=3)\n\n assert result[\"scores\"].shape == (2,)\n expected_detection_scores = np.asarray([0.67316836, 0.5686724])\n np.testing.assert_array_almost_equal(result[\"scores\"], expected_detection_scores, decimal=3)\n\n assert result[\"labels\"].shape == (2,)\n expected_detection_classes = np.asarray([18, 21])\n np.testing.assert_array_equal(result[\"labels\"], expected_detection_classes)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_fit(art_warning, get_pytorch_object_detector):\n try:\n object_detector, x_test, y_test = get_pytorch_object_detector\n\n # Compute loss before training\n loss1 = object_detector.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_detector.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_fit_mask(art_warning, get_pytorch_object_detector_mask):\n try:\n object_detector, x_test, y_test = get_pytorch_object_detector_mask\n\n # Compute loss before training\n loss1 = object_detector.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_detector.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_loss_gradient(art_warning, get_pytorch_object_detector):\n try:\n object_detector, x_test, y_test = get_pytorch_object_detector\n\n # Compute gradients\n grads = object_detector.loss_gradient(x_test, y_test)\n assert grads.shape == (1, 3, 416, 416)\n\n expected_gradients1 = np.asarray(\n [\n -7.2145270e-04,\n -3.9774503e-04,\n -5.5271841e-04,\n 2.5251633e-04,\n -4.1167819e-05,\n 1.2919735e-04,\n 1.1148686e-04,\n 4.9278833e-04,\n 9.6094189e-04,\n 1.1812975e-03,\n 2.7167992e-04,\n 9.7095188e-05,\n 1.4456113e-04,\n -8.8345587e-06,\n 4.7151549e-05,\n -1.3497710e-04,\n -2.3394797e-04,\n 1.3777621e-04,\n 3.2994794e-04,\n 3.7001527e-04,\n -2.5945838e-04,\n -8.3444244e-04,\n -6.9832127e-04,\n -3.0403296e-04,\n -5.4019055e-04,\n -3.4545487e-04,\n -5.6993403e-04,\n -2.9818740e-04,\n -9.8479632e-04,\n -4.1015903e-04,\n -6.2145875e-04,\n -1.1365353e-03,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 208, 192:224], expected_gradients1, decimal=2)\n\n expected_gradients2 = np.asarray(\n [\n 0.00015462,\n 0.00028882,\n -0.00018248,\n -0.00114344,\n -0.00160104,\n -0.00190151,\n -0.00183488,\n -0.00191787,\n -0.00018382,\n 0.00095297,\n 0.00042502,\n 0.00024631,\n 0.0002915,\n 0.00053676,\n 0.00028635,\n 0.00035274,\n -0.00023395,\n -0.00044685,\n -0.00016795,\n 0.00059767,\n 0.00060389,\n 0.00010305,\n 0.0011498,\n 0.00135104,\n 0.00095133,\n 0.00081004,\n 0.00061877,\n 0.00089056,\n 0.00056647,\n 0.00070012,\n 0.00016926,\n 0.00026042,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 192:224, 208], expected_gradients2, decimal=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_loss_gradient_mask(art_warning, get_pytorch_object_detector_mask):\n try:\n object_detector, x_test, y_test = get_pytorch_object_detector_mask\n\n # Compute gradients\n grads = object_detector.loss_gradient(x_test, y_test)\n assert grads.shape == (1, 3, 416, 416)\n\n expected_gradients1 = np.asarray(\n [\n -5.5341989e-05,\n -5.4428884e-04,\n 5.4366910e-04,\n 7.6082360e-04,\n -3.4690551e-05,\n -3.8355158e-04,\n 9.4802541e-05,\n -1.2973599e-03,\n -8.5583847e-04,\n -1.9041763e-03,\n -2.0476838e-03,\n 1.3446594e-04,\n 9.6042868e-04,\n 8.8853808e-04,\n 4.1893515e-04,\n 1.2266783e-04,\n 6.0996308e-04,\n 4.6253894e-04,\n -1.8787223e-03,\n -1.9494371e-03,\n -1.2018540e-03,\n -7.0822285e-04,\n 3.9439899e-04,\n -1.9463699e-03,\n -1.9617968e-03,\n -1.8740186e-04,\n -4.7003134e-04,\n -7.1175391e-04,\n -2.6479245e-03,\n -7.6713605e-04,\n -9.1007189e-04,\n -9.5907447e-04,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 208, 192:224], expected_gradients1, decimal=2)\n\n expected_gradients2 = np.asarray(\n [\n -0.00239724,\n -0.00271061,\n -0.0036578,\n -0.00504796,\n -0.0048536,\n -0.00433594,\n -0.00499022,\n -0.00401875,\n -0.00333852,\n -0.00060027,\n 0.00098555,\n 0.00249704,\n 0.00135383,\n 0.00277813,\n 0.00033104,\n 0.00016026,\n 0.00060996,\n 0.00010528,\n 0.00096368,\n 0.00230222,\n 0.00169831,\n 0.00172231,\n 0.00270932,\n 0.00224663,\n 0.00077922,\n 0.00174257,\n 0.00041644,\n -0.00126136,\n -0.00112533,\n -0.00110854,\n -0.00126751,\n -0.0014297,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 192:224, 208], expected_gradients2, decimal=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_pytorch_yolo.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_predict(art_warning, get_pytorch_yolo):\n try:\n from art.utils import non_maximum_suppression\n\n object_detector, x_test, _ = get_pytorch_yolo\n\n preds = object_detector.predict(x_test)\n result = non_maximum_suppression(preds[0], iou_threshold=0.4, confidence_threshold=0.3)\n assert list(result.keys()) == [\"boxes\", \"labels\", \"scores\"]\n\n assert result[\"boxes\"].shape == (1, 4)\n expected_detection_boxes = np.asarray([[19.709427, 39.02864, 402.08032, 383.65576]])\n np.testing.assert_array_almost_equal(result[\"boxes\"], expected_detection_boxes, decimal=3)\n\n assert result[\"scores\"].shape == (1,)\n expected_detection_scores = np.asarray([0.40862876])\n np.testing.assert_array_almost_equal(result[\"scores\"], expected_detection_scores, decimal=3)\n\n assert result[\"labels\"].shape == (1,)\n expected_detection_classes = np.asarray([23])\n np.testing.assert_array_equal(result[\"labels\"], expected_detection_classes)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_fit(art_warning, get_pytorch_yolo):\n try:\n object_detector, x_test, y_test = get_pytorch_yolo\n\n # Compute loss before training\n loss1 = object_detector.compute_loss(x=x_test, y=y_test)\n\n # Train for one epoch\n object_detector.fit(x_test, y_test, nb_epochs=1)\n\n # Compute loss after training\n loss2 = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert loss1 != loss2\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_loss_gradient(art_warning, get_pytorch_yolo):\n try:\n object_detector, x_test, y_test = get_pytorch_yolo\n\n grads = object_detector.loss_gradient(x=x_test, y=y_test)\n\n assert grads.shape == (1, 3, 416, 416)\n\n expected_gradients1 = np.asarray(\n [\n -7.8263599e-04,\n -3.2761338e-04,\n -1.7732104e-04,\n 5.0963718e-07,\n -1.2021367e-04,\n 1.5550642e-05,\n -1.2371356e-04,\n 6.0041926e-05,\n 7.2321229e-05,\n 2.8970995e-04,\n 3.2069255e-04,\n -9.7214943e-06,\n 4.1050217e-04,\n 3.4139317e-04,\n 3.2144223e-04,\n 8.0305658e-04,\n 1.0029323e-03,\n 5.4904580e-04,\n 3.4701737e-04,\n 9.2334412e-05,\n 4.5694585e-05,\n -4.1882982e-04,\n -1.1162873e-03,\n -1.2383220e-03,\n -1.2119032e-03,\n -1.3792568e-03,\n -1.0219158e-03,\n -1.7796915e-04,\n 1.6578102e-04,\n -4.0390861e-04,\n 5.0578610e-04,\n 3.2289932e-05,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 208, 192:224], expected_gradients1, decimal=2)\n\n expected_gradients2 = np.asarray(\n [\n 4.02656849e-04,\n 1.32368109e-03,\n 1.06753211e-03,\n 1.02746498e-03,\n 4.34952060e-04,\n 1.30278734e-03,\n 1.65620341e-03,\n 8.48031021e-04,\n 2.80185544e-04,\n 2.04326061e-04,\n -9.31014947e-05,\n -4.90375911e-04,\n -3.42604442e-04,\n 1.36689676e-04,\n 3.08552640e-04,\n 3.88148270e-04,\n 1.00293232e-03,\n -1.08163455e-04,\n -1.41605944e-03,\n -1.96112506e-03,\n -6.27453031e-04,\n -9.53144976e-04,\n -6.66696171e-04,\n -5.78872336e-04,\n -1.52492896e-04,\n -1.06580940e-03,\n 1.04899483e-03,\n 5.83183893e-04,\n 8.98627564e-04,\n 3.37607635e-04,\n 8.34865321e-04,\n 5.12865488e-04,\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, 192:224, 208], expected_gradients2, decimal=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_errors(art_warning):\n try:\n from pytorchyolo import models\n\n from art.estimators.object_detection.pytorch_yolo import PyTorchYolo\n\n model_path = \"/tmp/PyTorch-YOLOv3/config/yolov3.cfg\"\n weights_path = \"/tmp/PyTorch-YOLOv3/weights/yolov3.weights\"\n model = models.load_model(model_path=model_path, weights_path=weights_path)\n\n with pytest.raises(ValueError):\n PyTorchYolo(\n model=model,\n clip_values=(1, 2),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n )\n\n with pytest.raises(ValueError):\n PyTorchYolo(\n model=model,\n clip_values=(-1, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n )\n\n from art.defences.postprocessor.rounded import Rounded\n\n post_def = Rounded()\n with pytest.raises(ValueError):\n PyTorchYolo(\n model=model,\n clip_values=(0, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n postprocessing_defences=post_def,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_preprocessing_defences(art_warning, get_pytorch_yolo):\n try:\n from art.defences.preprocessor.spatial_smoothing import SpatialSmoothing\n\n pre_def = SpatialSmoothing()\n\n object_detector, x_test, y_test = get_pytorch_yolo\n\n object_detector.set_params(preprocessing_defences=pre_def)\n\n # Compute gradients\n grads = object_detector.loss_gradient(x=x_test, y=y_test)\n\n assert grads.shape == (1, 3, 416, 416)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_compute_losses(art_warning, get_pytorch_yolo):\n try:\n object_detector, x_test, y_test = get_pytorch_yolo\n losses = object_detector.compute_losses(x=x_test, y=y_test)\n assert len(losses) == 1\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_compute_loss(art_warning, get_pytorch_yolo):\n try:\n object_detector, x_test, y_test = get_pytorch_yolo\n\n # Compute loss\n loss = object_detector.compute_loss(x=x_test, y=y_test)\n\n assert pytest.approx(0.0920641, abs=0.05) == float(loss)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pgd(art_warning, get_pytorch_yolo):\n try:\n from art.attacks.evasion import ProjectedGradientDescent\n\n object_detector, x_test, y_test = get_pytorch_yolo\n\n attack = ProjectedGradientDescent(estimator=object_detector, max_iter=2)\n x_test_adv = attack.generate(x=x_test, y=y_test)\n np.testing.assert_raises(AssertionError, np.testing.assert_array_equal, x_test_adv, x_test)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_patch(art_warning, get_pytorch_yolo):\n try:\n\n from art.attacks.evasion import AdversarialPatchPyTorch\n\n rotation_max = 0.0\n scale_min = 0.1\n scale_max = 0.3\n distortion_scale_max = 0.0\n learning_rate = 1.99\n max_iter = 2\n batch_size = 16\n patch_shape = (3, 5, 5)\n patch_type = \"circle\"\n optimizer = \"pgd\"\n\n object_detector, x_test, y_test = get_pytorch_yolo\n\n ap = AdversarialPatchPyTorch(\n estimator=object_detector,\n rotation_max=rotation_max,\n scale_min=scale_min,\n scale_max=scale_max,\n optimizer=optimizer,\n distortion_scale_max=distortion_scale_max,\n learning_rate=learning_rate,\n max_iter=max_iter,\n batch_size=batch_size,\n patch_shape=patch_shape,\n patch_type=patch_type,\n verbose=True,\n targeted=False,\n )\n\n _, _ = ap.generate(x=x_test, y=y_test)\n\n patched_images = ap.apply_patch(x_test, scale=0.4)\n result = object_detector.predict(patched_images)\n\n assert result[0][\"scores\"].shape == (10647,)\n expected_detection_scores = np.asarray(\n [\n 2.0058684e-08,\n 8.2879878e-06,\n 1.5323505e-05,\n 8.5337388e-06,\n 1.5668766e-05,\n 3.7196922e-05,\n 4.5348370e-05,\n 6.9575308e-06,\n 4.2298670e-06,\n 1.0316832e-06,\n ]\n )\n np.testing.assert_allclose(result[0][\"scores\"][:10], expected_detection_scores, rtol=1e-5, atol=1e-8)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_import_pytorch_yolo_loss_wrapper():\n import torch\n from art.estimators.object_detection.pytorch_yolo_loss_wrapper import PyTorchYoloLossWrapper\n\n class DummyModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def loss(self, items):\n return (torch.tensor([1.0]), [torch.tensor(1.0), torch.tensor(2.0), torch.tensor(3.0)])\n\n test_model = DummyModel()\n # Patch ultralytics import in the wrapper\n import sys\n import types\n\n ultralytics_mock = types.SimpleNamespace(\n models=types.SimpleNamespace(\n yolo=types.SimpleNamespace(\n detect=types.SimpleNamespace(DetectionPredictor=lambda: types.SimpleNamespace(args=None))\n )\n ),\n utils=types.SimpleNamespace(\n loss=types.SimpleNamespace(v8DetectionLoss=lambda m: None, E2EDetectLoss=lambda m: None)\n ),\n )\n sys.modules[\"ultralytics\"] = ultralytics_mock\n sys.modules[\"ultralytics.models\"] = ultralytics_mock.models\n sys.modules[\"ultralytics.models.yolo\"] = ultralytics_mock.models.yolo\n sys.modules[\"ultralytics.models.yolo.detect\"] = ultralytics_mock.models.yolo.detect\n sys.modules[\"ultralytics.utils\"] = ultralytics_mock.utils\n sys.modules[\"ultralytics.utils.loss\"] = ultralytics_mock.utils.loss\n wrapper = PyTorchYoloLossWrapper(test_model, name=\"yolov8n\")\n assert isinstance(wrapper, PyTorchYoloLossWrapper)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_pytorch_yolo_loss_wrapper.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2025\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport pytest\nimport torch\nfrom ultralytics import YOLO\n\nfrom art.estimators.object_detection.pytorch_yolo_loss_wrapper import PyTorchYoloLossWrapper\n\nos.environ[\"TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD\"] = \"1\"\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_yolov8_loss_wrapper():\n \"\"\"Test the loss wrapper with YOLOv8 model.\"\"\"\n # Load YOLOv8 model\n model_path = \"/tmp/yolo_v8.3.0/yolov8n.pt\"\n model = YOLO(model_path).model\n\n # Create wrapper\n wrapper = PyTorchYoloLossWrapper(model, name=\"yolov8n\")\n wrapper.train()\n\n # Create sample input\n batch_size = 2\n x = torch.randn((batch_size, 3, 640, 640)) # YOLOv8 expects (B, 3, 640, 640)\n\n # Create targets\n \"\"\"targets = []\n for _ in range(batch_size):\n boxes = torch.tensor([[0.1, 0.1, 0.3, 0.3], [0.5, 0.5, 0.8, 0.8]]) # [x1, y1, x2, y2]\n labels = torch.zeros(2, dtype=torch.long) # Use class 0 for testing\n targets.append({\"boxes\": boxes, \"labels\": labels})\"\"\"\n targets = torch.tensor(\n [\n [0.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582],\n [0.0000, 20.0000, 0.2487, 0.4062, 0.4966, 0.5787],\n [0.0000, 20.0000, 0.5667, 0.2772, 0.0791, 0.2313],\n [0.0000, 20.0000, 0.1009, 0.1955, 0.2002, 0.0835],\n [1.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582],\n [1.0000, 20.0000, 0.2487, 0.4062, 0.4966, 0.5787],\n [1.0000, 20.0000, 0.5667, 0.2772, 0.0791, 0.2313],\n [1.0000, 20.0000, 0.1009, 0.1955, 0.2002, 0.0835],\n ]\n )\n\n # Test training mode\n losses = wrapper(x, targets)\n\n # Validate loss structure\n expected_loss_keys = {\"loss_total\", \"loss_box\", \"loss_cls\", \"loss_dfl\"}\n assert set(losses.keys()) == expected_loss_keys\n assert all(isinstance(v, torch.Tensor) for v in losses.values())\n assert all(not torch.isnan(v).any() for v in losses.values()), \"Loss values contain NaN\"\n assert all(not torch.isinf(v).any() for v in losses.values()), \"Loss values contain Inf\"\n\n # Test inference mode\n wrapper.eval()\n with torch.no_grad():\n predictions = wrapper(x)\n\n # Validate predictions\n assert isinstance(predictions, list)\n assert len(predictions) == batch_size\n for pred in predictions:\n assert set(pred.keys()) == {\"boxes\", \"scores\", \"labels\"}\n assert isinstance(pred[\"boxes\"], torch.Tensor)\n assert isinstance(pred[\"scores\"], torch.Tensor)\n assert isinstance(pred[\"labels\"], torch.Tensor)\n assert pred[\"boxes\"].ndim == 2 and pred[\"boxes\"].shape[1] == 4\n assert pred[\"scores\"].ndim == 1\n assert pred[\"labels\"].ndim == 1\n assert pred[\"scores\"].shape[0] == pred[\"labels\"].shape[0] == pred[\"boxes\"].shape[0]\n assert pred[\"boxes\"].dtype == torch.float32\n assert pred[\"labels\"].dtype in (torch.int32, torch.int64)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_yolov10_loss_wrapper():\n \"\"\"Test the loss wrapper with YOLOv10 model.\"\"\"\n # Load YOLOv10 model\n model_path = \"/tmp/yolo_v8.3.0/yolov10n.pt\"\n model = YOLO(model_path).model\n\n # Create wrapper\n wrapper = PyTorchYoloLossWrapper(model, name=\"yolov10n\")\n wrapper.train()\n\n # Create sample input\n batch_size = 2\n x = torch.randn((batch_size, 3, 640, 640)) # Standard YOLO input size\n\n # Create targets\n \"\"\"targets = []\n for _ in range(batch_size):\n boxes = torch.tensor([[0.1, 0.1, 0.3, 0.3], [0.5, 0.5, 0.8, 0.8]]) # [x1, y1, x2, y2]\n labels = torch.zeros(2, dtype=torch.long) # Use class 0 for testing\n targets.append({\"boxes\": boxes, \"labels\": labels})\"\"\"\n targets = torch.tensor(\n [\n [0.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582],\n [0.0000, 20.0000, 0.2487, 0.4062, 0.4966, 0.5787],\n [0.0000, 20.0000, 0.5667, 0.2772, 0.0791, 0.2313],\n [0.0000, 20.0000, 0.1009, 0.1955, 0.2002, 0.0835],\n [1.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582],\n [1.0000, 20.0000, 0.2487, 0.4062, 0.4966, 0.5787],\n [1.0000, 20.0000, 0.5667, 0.2772, 0.0791, 0.2313],\n [1.0000, 20.0000, 0.1009, 0.1955, 0.2002, 0.0835],\n ]\n )\n\n # Test training mode\n losses = wrapper(x, targets)\n\n # Validate loss structure\n expected_loss_keys = {\"loss_total\", \"loss_box\", \"loss_cls\", \"loss_dfl\"}\n assert set(losses.keys()) == expected_loss_keys\n assert all(isinstance(v, torch.Tensor) for v in losses.values())\n assert all(not torch.isnan(v).any() for v in losses.values()), \"Loss values contain NaN\"\n assert all(not torch.isinf(v).any() for v in losses.values()), \"Loss values contain Inf\"\n assert all(v.item() >= 0 for v in losses.values()), \"Loss values should be non-negative\"\n assert losses[\"loss_total\"].item() > 0, \"Total loss should be positive\"\n\n # Test inference mode\n wrapper.eval()\n with torch.no_grad():\n predictions = wrapper(x)\n\n # Validate predictions\n assert isinstance(predictions, list)\n assert len(predictions) == batch_size\n for pred in predictions:\n assert set(pred.keys()) == {\"boxes\", \"scores\", \"labels\"}\n assert isinstance(pred[\"boxes\"], torch.Tensor)\n assert isinstance(pred[\"scores\"], torch.Tensor)\n assert isinstance(pred[\"labels\"], torch.Tensor)\n assert pred[\"boxes\"].ndim == 2 and pred[\"boxes\"].shape[1] == 4\n assert pred[\"scores\"].ndim == 1\n assert pred[\"labels\"].ndim == 1\n assert pred[\"scores\"].shape[0] == pred[\"labels\"].shape[0] == pred[\"boxes\"].shape[0]\n assert pred[\"boxes\"].dtype == torch.float32\n assert pred[\"labels\"].dtype in (torch.int32, torch.int64)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_translate_predictions_yolov8_format():\n import torch\n import numpy as np\n from art.estimators.object_detection.pytorch_yolo import PyTorchYolo\n\n # Create a dummy PyTorchYolo instance (model is not used for this test)\n class DummyModel(torch.nn.Module):\n def forward(self, x):\n return x\n\n test_model = DummyModel()\n yolo = PyTorchYolo(\n model=test_model,\n input_shape=(3, 416, 416),\n optimizer=None,\n clip_values=(0, 1),\n channels_first=True,\n attack_losses=(\"loss_total\",),\n )\n\n # Mock YOLO v8+ style predictions: list of dicts with torch tensors\n pred_boxes = torch.tensor([[10.0, 20.0, 30.0, 40.0]], dtype=torch.float32)\n pred_labels = torch.tensor([5], dtype=torch.int64)\n pred_scores = torch.tensor([0.9], dtype=torch.float32)\n predictions = [\n {\n \"boxes\": pred_boxes,\n \"labels\": pred_labels,\n \"scores\": pred_scores,\n }\n ]\n\n # Call the translation method\n translated = yolo._translate_predictions(predictions)\n\n # Check output type and values\n assert isinstance(translated, list)\n assert isinstance(translated[0], dict)\n assert isinstance(translated[0][\"boxes\"], np.ndarray)\n assert isinstance(translated[0][\"labels\"], np.ndarray)\n assert isinstance(translated[0][\"scores\"], np.ndarray)\n np.testing.assert_array_equal(translated[0][\"boxes\"], pred_boxes.numpy())\n np.testing.assert_array_equal(translated[0][\"labels\"], pred_labels.numpy())\n np.testing.assert_array_equal(translated[0][\"scores\"], pred_scores.numpy())\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_pytorch_yolo_loss_wrapper_additional_losses():\n import torch\n\n # Dummy model with a .loss() method\n class DummyModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def loss(self, items):\n # Return (loss, [loss_box, loss_cls, loss_dfl])\n return (torch.tensor([1.0, 2.0, 3.0]), [torch.tensor(1.0), torch.tensor(2.0), torch.tensor(3.0)])\n\n test_model = DummyModel()\n # Patch ultralytics import in the wrapper\n import sys\n import types\n\n ultralytics_mock = types.SimpleNamespace(\n models=types.SimpleNamespace(\n yolo=types.SimpleNamespace(\n detect=types.SimpleNamespace(DetectionPredictor=lambda: types.SimpleNamespace(args=None))\n )\n ),\n utils=types.SimpleNamespace(\n loss=types.SimpleNamespace(v8DetectionLoss=lambda m: None, E2EDetectLoss=lambda m: None)\n ),\n )\n sys.modules[\"ultralytics\"] = ultralytics_mock\n sys.modules[\"ultralytics.models\"] = ultralytics_mock.models\n sys.modules[\"ultralytics.models.yolo\"] = ultralytics_mock.models.yolo\n sys.modules[\"ultralytics.models.yolo.detect\"] = ultralytics_mock.models.yolo.detect\n sys.modules[\"ultralytics.utils\"] = ultralytics_mock.utils\n sys.modules[\"ultralytics.utils.loss\"] = ultralytics_mock.utils.loss\n\n wrapper = PyTorchYoloLossWrapper(test_model, name=\"yolov8n\")\n wrapper.train()\n # Dummy input and targets\n x = torch.zeros((1, 3, 416, 416))\n targets = torch.tensor([[0.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582]])\n losses = wrapper(x, targets)\n assert set(losses.keys()) == {\"loss_total\", \"loss_box\", \"loss_cls\", \"loss_dfl\"}\n assert losses[\"loss_total\"].item() == 6.0 # sum([1.0, 2.0, 3.0])\n assert losses[\"loss_box\"].item() == 1.0\n assert losses[\"loss_cls\"].item() == 2.0\n assert losses[\"loss_dfl\"].item() == 3.0\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_loss_wrapper_outputs_all_losses():\n # Dummy model with a .loss() method\n class DummyModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def loss(self, items):\n # Return (loss, [loss_box, loss_cls, loss_dfl])\n return (torch.tensor([1.0, 2.0, 3.0]), [torch.tensor(1.0), torch.tensor(2.0), torch.tensor(3.0)])\n\n test_model = DummyModel()\n # Patch ultralytics import in the wrapper\n import sys\n import types\n\n ultralytics_mock = types.SimpleNamespace(\n models=types.SimpleNamespace(\n yolo=types.SimpleNamespace(\n detect=types.SimpleNamespace(DetectionPredictor=lambda: types.SimpleNamespace(args=None))\n )\n ),\n utils=types.SimpleNamespace(\n loss=types.SimpleNamespace(v8DetectionLoss=lambda m: None, E2EDetectLoss=lambda m: None)\n ),\n )\n sys.modules[\"ultralytics\"] = ultralytics_mock\n sys.modules[\"ultralytics.models\"] = ultralytics_mock.models\n sys.modules[\"ultralytics.models.yolo\"] = ultralytics_mock.models.yolo\n sys.modules[\"ultralytics.models.yolo.detect\"] = ultralytics_mock.models.yolo.detect\n sys.modules[\"ultralytics.utils\"] = ultralytics_mock.utils\n sys.modules[\"ultralytics.utils.loss\"] = ultralytics_mock.utils.loss\n\n wrapper = PyTorchYoloLossWrapper(test_model, name=\"yolov8n\")\n wrapper.train()\n x = torch.zeros((1, 3, 416, 416))\n targets = torch.tensor([[0.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582]])\n losses = wrapper(x, targets)\n assert set(losses.keys()) == {\"loss_total\", \"loss_box\", \"loss_cls\", \"loss_dfl\"}\n assert losses[\"loss_total\"].item() == 6.0\n assert losses[\"loss_box\"].item() == 1.0\n assert losses[\"loss_cls\"].item() == 2.0\n assert losses[\"loss_dfl\"].item() == 3.0\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_yolov8_vs_yolov10_loss_functions():\n import torch\n\n # Dummy model that will be wrapped\n class DummyModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.criterion = None # Will be set by wrapper\n\n def loss(self, items):\n # Return different loss components based on model version\n return (torch.tensor([1.0, 2.0, 3.0]), [torch.tensor(1.0), torch.tensor(2.0), torch.tensor(3.0)])\n\n # Mock ultralytics imports\n import sys\n import types\n\n def create_mock_imports():\n return types.SimpleNamespace(\n models=types.SimpleNamespace(\n yolo=types.SimpleNamespace(\n detect=types.SimpleNamespace(DetectionPredictor=lambda: types.SimpleNamespace(args=None))\n )\n ),\n utils=types.SimpleNamespace(\n loss=types.SimpleNamespace(v8DetectionLoss=lambda m: \"v8_loss\", E2EDetectLoss=lambda m: \"v10_loss\")\n ),\n )\n\n # Test YOLOv8\n ultralytics_mock = create_mock_imports()\n sys.modules[\"ultralytics\"] = ultralytics_mock\n sys.modules[\"ultralytics.models\"] = ultralytics_mock.models\n sys.modules[\"ultralytics.models.yolo\"] = ultralytics_mock.models.yolo\n sys.modules[\"ultralytics.models.yolo.detect\"] = ultralytics_mock.models.yolo.detect\n sys.modules[\"ultralytics.utils\"] = ultralytics_mock.utils\n sys.modules[\"ultralytics.utils.loss\"] = ultralytics_mock.utils.loss\n\n model_v8 = DummyModel()\n wrapper_v8 = PyTorchYoloLossWrapper(model_v8, name=\"yolov8n\")\n assert wrapper_v8.model.criterion == \"v8_loss\"\n\n # Test YOLOv10\n model_v10 = DummyModel()\n wrapper_v10 = PyTorchYoloLossWrapper(model_v10, name=\"yolov10n\")\n assert wrapper_v10.model.criterion == \"v10_loss\"\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_yolov8_inference_mode():\n import torch\n import numpy as np\n\n # Dummy model that mimics YOLO v8+ inference behavior\n class DummyYoloV8Model(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n # Return format matching YOLO v8+ output structure\n return [{\"boxes\": torch.ones(1, 4), \"scores\": torch.ones(1), \"labels\": torch.zeros(1)}]\n\n # Mock ultralytics imports\n import sys\n import types\n\n ultralytics_mock = types.SimpleNamespace(\n models=types.SimpleNamespace(\n yolo=types.SimpleNamespace(\n detect=types.SimpleNamespace(\n DetectionPredictor=lambda: types.SimpleNamespace(\n args=None,\n model=None,\n batch=None,\n postprocess=lambda preds, *args: [\n types.SimpleNamespace(\n boxes=types.SimpleNamespace(\n xyxy=torch.tensor([[1.0, 2.0, 3.0, 4.0]]),\n conf=torch.tensor([0.95]),\n cls=torch.tensor([1]),\n )\n )\n ],\n )\n )\n )\n ),\n utils=types.SimpleNamespace(\n loss=types.SimpleNamespace(v8DetectionLoss=lambda m: None, E2EDetectLoss=lambda m: None)\n ),\n )\n sys.modules[\"ultralytics\"] = ultralytics_mock\n sys.modules[\"ultralytics.models\"] = ultralytics_mock.models\n sys.modules[\"ultralytics.models.yolo\"] = ultralytics_mock.models.yolo\n sys.modules[\"ultralytics.models.yolo.detect\"] = ultralytics_mock.models.yolo.detect\n sys.modules[\"ultralytics.utils\"] = ultralytics_mock.utils\n sys.modules[\"ultralytics.utils.loss\"] = ultralytics_mock.utils.loss\n\n model = DummyYoloV8Model()\n wrapper = PyTorchYoloLossWrapper(model, name=\"yolov8n\")\n wrapper.eval() # Set to inference mode\n\n # Test inference\n x = torch.zeros((1, 3, 416, 416))\n predictions = wrapper(x)\n\n assert isinstance(predictions, list)\n assert len(predictions) == 1\n assert set(predictions[0].keys()) == {\"boxes\", \"scores\", \"labels\"}\n assert isinstance(predictions[0][\"boxes\"], torch.Tensor)\n assert isinstance(predictions[0][\"scores\"], torch.Tensor)\n assert isinstance(predictions[0][\"labels\"], torch.Tensor)\n np.testing.assert_array_equal(predictions[0][\"boxes\"].numpy(), np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32))\n np.testing.assert_array_equal(predictions[0][\"scores\"].numpy(), np.array([0.95], dtype=np.float32))\n np.testing.assert_array_equal(predictions[0][\"labels\"].numpy(), np.array([1], dtype=np.int64))\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_yolov8_training_data_format():\n import torch\n\n class DummyModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def loss(self, items):\n # Validate input format matches expected YOLO v8+ training format\n assert \"bboxes\" in items\n assert \"cls\" in items\n assert \"batch_idx\" in items\n assert \"img\" in items\n return torch.tensor([1.0]), [torch.tensor(1.0), torch.tensor(1.0), torch.tensor(1.0)]\n\n # Setup mock imports\n import sys\n import types\n\n ultralytics_mock = types.SimpleNamespace(\n models=types.SimpleNamespace(\n yolo=types.SimpleNamespace(\n detect=types.SimpleNamespace(DetectionPredictor=lambda: types.SimpleNamespace(args=None))\n )\n ),\n utils=types.SimpleNamespace(\n loss=types.SimpleNamespace(v8DetectionLoss=lambda m: None, E2EDetectLoss=lambda m: None)\n ),\n )\n sys.modules[\"ultralytics\"] = ultralytics_mock\n sys.modules[\"ultralytics.models\"] = ultralytics_mock.models\n sys.modules[\"ultralytics.models.yolo\"] = ultralytics_mock.models.yolo\n sys.modules[\"ultralytics.models.yolo.detect\"] = ultralytics_mock.models.yolo.detect\n sys.modules[\"ultralytics.utils\"] = ultralytics_mock.utils\n sys.modules[\"ultralytics.utils.loss\"] = ultralytics_mock.utils.loss\n\n model = DummyModel()\n wrapper = PyTorchYoloLossWrapper(model, name=\"yolov8n\")\n wrapper.train()\n\n # Test with different batch sizes and box counts\n batch_sizes = [1, 2]\n box_counts = [1, 3]\n\n for batch_size in batch_sizes:\n for box_count in box_counts:\n x = torch.zeros((batch_size, 3, 416, 416))\n targets = torch.tensor([[0.0000, 20.0000, 0.7738, 0.3919, 0.4525, 0.7582]] * batch_size)\n losses = wrapper(x, targets)\n\n # Verify loss structure\n assert set(losses.keys()) == {\"loss_total\", \"loss_box\", \"loss_cls\", \"loss_dfl\"}\n assert all(isinstance(v, torch.Tensor) for v in losses.values())\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_detection/test_tensorflow_v2_faster_rcnn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.utils import load_dataset\n\nfrom tests.utils import ARTTestException, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_module(\"object_detection\")\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_tf_faster_rcnn(art_warning):\n try:\n master_seed(seed=1234, set_tensorflow=True)\n\n # Only import if object detection module is available\n from art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\n\n # Get test data\n (_, _), (x_test, _), _, _ = load_dataset(\"cifar10\")\n x_test = x_test[:1]\n input_shape = tuple(x_test.shape[1:])\n\n obj_dec = TensorFlowV2FasterRCNN(input_shape=input_shape)\n\n # First test predict\n result = obj_dec.predict(x_test)\n\n assert list(result[0].keys()) == [\"boxes\", \"labels\", \"scores\"]\n\n assert result[0][\"boxes\"].shape == (300, 4)\n expected_detection_boxes = np.asarray([0.11661448, 0.46441936, 0.868652, 0.99897605])\n np.testing.assert_array_almost_equal(result[0][\"boxes\"][2, :], expected_detection_boxes, decimal=3)\n\n assert result[0][\"scores\"].shape == (300,)\n expected_detection_scores = np.asarray(\n [\n 0.09375852,\n 0.04189522,\n 0.03094958,\n 0.01798256,\n 0.01198419,\n 0.00832632,\n 0.0076474,\n 0.00762132,\n 0.00662233,\n 0.00605294,\n ]\n )\n np.testing.assert_array_almost_equal(result[0][\"scores\"][:10], expected_detection_scores, decimal=3)\n\n assert result[0][\"labels\"].shape == (300,)\n expected_detection_classes = np.asarray([84, 84, 84, 84, 54, 84, 0, 84, 84, 46])\n np.testing.assert_array_almost_equal(result[0][\"labels\"][:10], expected_detection_classes)\n\n # Then test loss gradient\n # Create labels\n y = [{\"boxes\": result[0][\"boxes\"], \"labels\": result[0][\"labels\"], \"scores\": np.ones_like(result[0][\"labels\"])}]\n\n # Compute gradients\n grads = obj_dec.loss_gradient(x_test[:1], y)\n\n assert grads.shape == (1, 32, 32, 3)\n\n expected_gradients = np.asarray(\n [\n [4.71095882e-05, 8.39344830e-06, 5.82142093e-06],\n [-1.08160377e-04, 2.27618133e-04, -5.05365351e-05],\n [-3.99912205e-05, 4.34129965e-04, 5.15039403e-07],\n [-1.41627097e-04, 5.76516759e-05, 8.09017874e-05],\n [6.20874243e-06, 2.76702020e-04, -2.28589524e-05],\n [4.32882962e-06, -4.03481281e-05, -7.62806958e-05],\n [-8.37679690e-05, -2.18129950e-04, -9.04274712e-05],\n [-3.67438624e-05, -2.10944389e-04, -9.05940469e-05],\n [-1.75537971e-05, -3.48282600e-04, -8.23857263e-05],\n [5.30820471e-05, -2.86138180e-04, -7.48635794e-05],\n [8.23858354e-05, -1.13339869e-04, -3.49664515e-05],\n [1.59092160e-04, 6.47279012e-05, -1.79400049e-05],\n [-1.63149289e-05, 3.31735782e-06, -4.67280151e-05],\n [-1.98027137e-05, 7.51307743e-05, 2.54857914e-05],\n [6.82972241e-05, 5.97215876e-05, 1.28419619e-04],\n [2.36609863e-04, 2.10922881e-04, 3.50106740e-04],\n [1.47960993e-04, -7.82240568e-06, 2.49002245e-04],\n [7.26436410e-05, -2.87787785e-04, 2.79000669e-04],\n [3.83440783e-05, -2.70720484e-04, 2.26368575e-04],\n [9.61775513e-05, -6.31674193e-05, 2.45212781e-04],\n [1.52097986e-04, -1.31431938e-04, 2.59597989e-04],\n [4.55492234e-04, -8.12296203e-05, 2.45009316e-04],\n [8.83234490e-04, 7.50507315e-05, 3.66395630e-04],\n [1.27273344e-03, 5.82617824e-04, 3.64959065e-04],\n [1.28024910e-03, 5.57218504e-04, 5.37421904e-04],\n [1.23637193e-03, 8.37092637e-04, 4.96422348e-04],\n [7.82434945e-04, 6.26019435e-04, 2.94824480e-04],\n [2.37986183e-04, 1.05056606e-04, 6.55481563e-05],\n [-2.00339942e-04, -1.20437835e-04, -1.66682788e-04],\n [-5.84452318e-05, -1.35937284e-04, -1.51533968e-04],\n [-4.77294707e-05, -2.31526021e-04, -1.24137907e-04],\n [-1.15175018e-04, -1.65152203e-04, -7.45802899e-05],\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, :, :], expected_gradients, decimal=2)\n\n # Test the predictions and gradients constant for multiple calls of same input\n result_dup = obj_dec.predict(x_test)\n np.testing.assert_array_almost_equal(result[0][\"boxes\"][2, :], result_dup[0][\"boxes\"][2, :], decimal=3)\n np.testing.assert_array_almost_equal(result[0][\"scores\"][:10], result_dup[0][\"scores\"][:10], decimal=3)\n np.testing.assert_array_almost_equal(result[0][\"labels\"][:10], result_dup[0][\"labels\"][:10])\n\n y_dup = [\n {\n \"boxes\": result_dup[0][\"boxes\"],\n \"labels\": result_dup[0][\"labels\"],\n \"scores\": np.ones_like(result_dup[0][\"labels\"]),\n }\n ]\n grads_dup = obj_dec.loss_gradient(x_test[:1], y_dup)\n np.testing.assert_array_almost_equal(grads[0, 0, :, :], grads_dup[0, 0, :, :], decimal=2)\n\n # Then test loss gradient with standard format\n # Create labels\n result_tf = obj_dec.predict(x_test, standardise_output=False)\n result = obj_dec.predict(x_test, standardise_output=True)\n\n from art.estimators.object_detection.utils import convert_tf_to_pt\n\n result_pt = convert_tf_to_pt(y=result_tf, height=x_test.shape[1], width=x_test.shape[2])\n\n np.testing.assert_array_equal(result[0][\"boxes\"], result_pt[0][\"boxes\"])\n np.testing.assert_array_equal(result[0][\"labels\"], result_pt[0][\"labels\"])\n np.testing.assert_array_equal(result[0][\"scores\"], result_pt[0][\"scores\"])\n\n y = [{\"boxes\": result[0][\"boxes\"], \"labels\": result[0][\"labels\"], \"scores\": np.ones_like(result[0][\"labels\"])}]\n\n # Compute gradients\n grads = obj_dec.loss_gradient(x_test[:1], y, standardise_output=True)\n\n assert grads.shape == (1, 32, 32, 3)\n\n expected_gradients = np.asarray(\n [\n [3.20258296e-05, 1.18448479e-04, 5.11901126e-05],\n [5.20282541e-04, 4.31609747e-04, -2.20944603e-05],\n [8.58511135e-04, -3.65446263e-04, 1.36029223e-04],\n [3.47276509e-05, -8.23178736e-04, -2.23043782e-04],\n [1.37017007e-04, -5.57144347e-04, -1.98563328e-04],\n [7.77723617e-05, -3.10823030e-04, -4.05157916e-04],\n [-1.72378772e-04, -3.07416456e-04, -4.87639132e-04],\n [-8.86716807e-05, -4.24879254e-04, -7.27561070e-04],\n [-1.00905372e-05, -1.06700277e-03, -6.71751099e-04],\n [-3.24819557e-04, -1.03535608e-03, -8.76112608e-04],\n [-4.44697944e-04, -2.94831785e-04, -1.28169032e-03],\n [-2.53191713e-04, 7.62609925e-05, -1.11494109e-03],\n [-3.77789664e-04, -7.78697427e-07, -9.06005735e-04],\n [-1.37880095e-04, 2.21254071e-04, -7.10642664e-04],\n [-1.49297048e-04, -2.67961295e-04, -5.52246522e-04],\n [-3.48978385e-04, -7.13465444e-04, -7.76897825e-04],\n [-6.15608995e-04, -1.12241239e-03, -1.01537013e-03],\n [-6.28621201e-04, -1.58125453e-03, -9.77508142e-04],\n [-3.45328706e-04, -1.32934854e-03, -8.63111869e-04],\n [-2.70117362e-05, -8.22714996e-04, -4.30601096e-04],\n [1.72943372e-04, -1.61864562e-04, -2.35522675e-04],\n [2.82775087e-04, -1.11206624e-04, -2.37867673e-04],\n [2.06765530e-04, -2.46381125e-04, -2.45586620e-04],\n [1.34378410e-04, -3.13195225e-04, -4.79331560e-04],\n [3.81465390e-04, -4.43120458e-04, -3.82220693e-04],\n [8.27364449e-04, 6.86867425e-05, -1.02168444e-04],\n [4.70337487e-04, 1.94208715e-05, -1.88505583e-04],\n [1.42172328e-04, 1.59842341e-04, -1.30101529e-04],\n [3.61582970e-05, -1.23159880e-05, -2.09606616e-04],\n [2.71195429e-04, 1.06499057e-04, -7.41584881e-05],\n [1.49051149e-04, -5.21843147e-04, -2.40127789e-04],\n [1.46682723e-04, -2.08231620e-04, -2.79343774e-04],\n ]\n )\n np.testing.assert_array_almost_equal(grads[0, 0, :, :], expected_gradients, decimal=2)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_errors(art_warning):\n try:\n from art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\n\n (_, _), (x_test, _), _, _ = load_dataset(\"cifar10\")\n input_shape = tuple(x_test.shape[1:])\n\n with pytest.raises(ValueError):\n obj_det = TensorFlowV2FasterRCNN(\n input_shape=input_shape,\n clip_values=(1, 2),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n )\n obj_det.predict(x_test[:1])\n\n with pytest.raises(ValueError):\n TensorFlowV2FasterRCNN(\n input_shape=input_shape,\n clip_values=(-1, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n )\n obj_det.predict(x_test[:1])\n\n from art.defences.postprocessor.rounded import Rounded\n\n post_def = Rounded()\n with pytest.raises(ValueError):\n TensorFlowV2FasterRCNN(\n input_shape=input_shape,\n clip_values=(0, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n postprocessing_defences=post_def,\n )\n obj_det.predict(x_test[:1])\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_preprocessing_defences(art_warning):\n try:\n from art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\n from art.defences.preprocessor.spatial_smoothing import SpatialSmoothing\n\n (_, _), (x_test, _), _, _ = load_dataset(\"cifar10\")\n input_shape = tuple(x_test.shape[1:])\n\n pre_def = SpatialSmoothing()\n\n with pytest.raises(ValueError):\n _ = TensorFlowV2FasterRCNN(\n input_shape=input_shape,\n clip_values=(0, 1),\n attack_losses=(\"loss_classifier\", \"loss_box_reg\", \"loss_objectness\", \"loss_rpn_box_reg\"),\n preprocessing_defences=pre_def,\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_compute_losses(art_warning):\n try:\n from art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\n\n # Get test data\n (_, _), (x_test, _), _, _ = load_dataset(\"cifar10\")\n input_shape = tuple(x_test.shape[1:])\n\n frcnn = TensorFlowV2FasterRCNN(\n input_shape=input_shape,\n clip_values=(0, 255),\n attack_losses=(\n \"Loss/RPNLoss/localization_loss\",\n \"Loss/RPNLoss/objectness_loss\",\n \"Loss/BoxClassifierLoss/localization_loss\",\n \"Loss/BoxClassifierLoss/classification_loss\",\n ),\n )\n\n # Create labels\n result = frcnn.predict(x_test[:2])\n\n y = [\n {\n \"boxes\": result[0][\"boxes\"],\n \"labels\": result[0][\"labels\"],\n \"scores\": np.ones_like(result[0][\"labels\"]),\n },\n {\n \"boxes\": result[1][\"boxes\"],\n \"labels\": result[1][\"labels\"],\n \"scores\": np.ones_like(result[1][\"labels\"]),\n },\n ]\n\n # Compute losses\n losses = frcnn.compute_losses(x_test[:2], y)\n\n assert len(losses) == 4\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_compute_loss(art_warning):\n try:\n from art.estimators.object_detection.tensorflow_v2_faster_rcnn import TensorFlowV2FasterRCNN\n\n # Get test data\n (_, _), (x_test, _), _, _ = load_dataset(\"cifar10\")\n input_shape = tuple(x_test.shape[1:])\n\n frcnn = TensorFlowV2FasterRCNN(\n input_shape=input_shape,\n clip_values=(0, 255),\n attack_losses=(\n \"Loss/RPNLoss/localization_loss\",\n \"Loss/RPNLoss/objectness_loss\",\n \"Loss/BoxClassifierLoss/localization_loss\",\n \"Loss/BoxClassifierLoss/classification_loss\",\n ),\n )\n\n # Create labels\n result = frcnn.predict(x_test[:2])\n\n y = [\n {\n \"boxes\": result[0][\"boxes\"],\n \"labels\": result[0][\"labels\"],\n \"scores\": np.ones_like(result[0][\"labels\"]),\n },\n {\n \"boxes\": result[1][\"boxes\"],\n \"labels\": result[1][\"labels\"],\n \"scores\": np.ones_like(result[1][\"labels\"]),\n },\n ]\n\n # Compute loss\n loss = frcnn.compute_loss(x_test[:2], y)[0]\n\n assert float(loss) == pytest.approx(11.245838, abs=0.5)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/object_tracking/test_pytorch_goturn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport os\nimport numpy as np\nimport pytest\n\nfrom art.estimators.object_tracking import PyTorchGoturn\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_pytorch_goturn(art_warning):\n try:\n import torch\n from scripts.train import GoturnTrain\n from pathlib import Path\n\n _device = \"cpu\"\n\n goturn_path = os.path.join(os.sep, \"tmp\", \"goturn-pytorch\")\n\n model_dir = Path(os.path.join(goturn_path, \"src\", \"goturn\", \"models\"))\n ckpt_dir = model_dir.joinpath(\"checkpoints\")\n ckpt_path = next(ckpt_dir.glob(\"*.ckpt\"))\n\n ckpt_mod = torch.load(\n os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"),\n map_location=_device,\n )\n ckpt_mod[\"hparams\"][\"pretrained_model\"] = os.path.join(\n goturn_path, \"src\", \"goturn\", \"models\", \"pretrained\", \"caffenet_weights.npy\"\n )\n torch.save(ckpt_mod, os.path.join(goturn_path, \"src\", \"goturn\", \"models\", \"checkpoints\", \"_ckpt_epoch_3.ckpt\"))\n\n model = GoturnTrain.load_from_checkpoint(ckpt_path)\n\n pgt = PyTorchGoturn(\n model=model,\n input_shape=(3, 227, 227),\n clip_values=(0, 255),\n preprocessing=(np.array([104.0, 117.0, 123.0]), np.array([1.0, 1.0, 1.0])),\n device_type=_device,\n )\n\n y_init = np.array([[48, 79, 80, 110], [48, 79, 80, 110]])\n x_list = list()\n for i in range(2):\n x_list.append(np.random.random_integers(0, 255, size=(4 + i, 277, 277, 3)).astype(float))\n\n x = np.asarray(x_list, dtype=object)\n\n y_pred = pgt.predict(x=x, y_init=y_init)\n\n assert len(y_pred) == 2\n np.testing.assert_almost_equal(\n y_pred[0][\"boxes\"],\n np.array(\n [\n [48.0, 79.0, 80.0, 110.0],\n [43.470764, 82.5287, 76.76668, 113.04108],\n [41.73817, 83.22243, 75.68121, 114.028885],\n [37.701916, 86.00661, 73.45953, 116.56588],\n ]\n ),\n decimal=4,\n )\n\n gradients = pgt.loss_gradient(x=x, y=y_pred)\n\n assert len(gradients) == 2\n assert pytest.approx(np.max(gradients[0]), 0.037566885, abs=0.0001)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/regression/test_blackbox.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\nimport numpy as np\n\nfrom art.estimators.regression import BlackBoxRegressor\nfrom art.config import ART_NUMPY_DTYPE\nfrom tests.utils import ARTTestException\n\n\ndef mean_absolute_error(y_true, y_pred):\n return np.abs(y_pred - y_true)\n\n\ndef test_blackbox_existing_predictions(art_warning, get_diabetes_dataset):\n try:\n (x_train, _), (x_test, y_test) = get_diabetes_dataset\n\n bb = BlackBoxRegressor(\n (x_test.astype(ART_NUMPY_DTYPE), y_test),\n (10,),\n )\n pred = bb.predict(x_test.astype(ART_NUMPY_DTYPE))\n assert np.array_equal(pred, y_test.astype(ART_NUMPY_DTYPE))\n assert np.count_nonzero(bb.compute_loss(x_test, y_test)) == 0\n assert np.count_nonzero(bb.compute_loss_from_predictions(pred, y_test)) == 0\n\n with pytest.raises(ValueError):\n bb.predict(x_train)\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_existing_predictions_fuzzy(art_warning):\n try:\n x = np.array([0, 3])\n fuzzy_x = np.array([0, 3.00001])\n y = np.array([2.1, 1.8])\n bb = BlackBoxRegressor((x, y), (1,), fuzzy_float_compare=True)\n assert np.array_equal(bb.predict(fuzzy_x), y.astype(ART_NUMPY_DTYPE))\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_existing_predictions_custom_loss(art_warning, get_diabetes_dataset):\n try:\n (_, _), (x_test, y_test) = get_diabetes_dataset\n\n bb = BlackBoxRegressor((x_test.astype(ART_NUMPY_DTYPE), y_test), (10,), loss_fn=mean_absolute_error)\n pred = bb.predict(x_test.astype(ART_NUMPY_DTYPE))\n assert np.array_equal(pred, y_test.astype(ART_NUMPY_DTYPE))\n assert np.count_nonzero(bb.compute_loss(x_test, y_test)) == 0\n assert np.count_nonzero(bb.compute_loss_from_predictions(pred, y_test)) == 0\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_predict_fn(art_warning, get_diabetes_dataset):\n try:\n from sklearn import linear_model\n\n (x_train, y_train), (x_test, y_test) = get_diabetes_dataset\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train, y_train)\n\n bb = BlackBoxRegressor(regr_model.predict, (10,))\n pred = bb.predict(x_test)\n assert abs(y_test[0] - pred[0]) < 50\n assert abs(bb.compute_loss(x_test, y_test)[0] - 2000) < 100\n assert abs(bb.compute_loss_from_predictions(pred, y_test)[0] - 2000) < 100\n\n bbc = bb.get_classifier([50, 100, 200])\n pred_c = bbc.predict(x_test)\n assert pred_c.shape[1] == 4\n\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_blackbox_predict_fn_custom_loss(art_warning, get_diabetes_dataset):\n try:\n from sklearn import linear_model\n\n (x_train, y_train), (x_test, y_test) = get_diabetes_dataset\n regr_model = linear_model.LinearRegression()\n regr_model.fit(x_train, y_train)\n\n bb = BlackBoxRegressor(regr_model.predict, (10,), loss_fn=mean_absolute_error)\n pred = bb.predict(x_test)\n assert abs(y_test[0] - pred[0]) < 50\n assert abs(bb.compute_loss(x_test, y_test)[0] - 45) < 5\n assert abs(bb.compute_loss_from_predictions(pred, y_test)[0] - 45) < 5\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/regression/test_keras_regression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\nimport numpy as np\n\nfrom art.estimators.regression.keras import KerasRegressor\n\nfrom tests.utils import TestBase, master_seed, get_tabular_regressor_kr\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestKerasRegressor(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUpClass()\n cls.art_model = get_tabular_regressor_kr()\n\n def test_type(self):\n with self.assertRaises(TypeError):\n KerasRegressor(model=\"model\")\n\n def test_predict(self):\n y_predicted = self.art_model.predict(self.x_test_diabetes[:4])\n y_expected = np.asarray([[24.9], [52.7], [30.4], [68.1]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=1)\n\n def test_save(self):\n self.art_model.save(filename=\"test.file\", path=None)\n self.art_model.save(filename=\"test.file\", path=\"./\")\n\n def test_input_shape(self):\n np.testing.assert_equal(self.art_model.input_shape, (10,))\n\n def test_input_layer(self):\n np.testing.assert_equal(isinstance(self.art_model.input_layer, int), True)\n\n def test_output_layer(self):\n np.testing.assert_equal(isinstance(self.art_model.output_layer, int), True)\n\n def test_compute_loss(self):\n test_loss = self.art_model.compute_loss(self.x_test_diabetes[:4], self.y_test_diabetes[:4])\n loss_expected = [6089.8, 2746.3, 5306.8, 1554.9]\n np.testing.assert_array_almost_equal(test_loss, loss_expected, decimal=1)\n\n def test_loss_gradient(self):\n grad = self.art_model.loss_gradient(self.x_test_diabetes[:4], self.y_test_diabetes[:4])\n grad_expected = [-333.9, 586.4, -1190.9, -123.9, -1206.2, -883.7, 295.9, -830.5, -1333.1, -553.8]\n np.testing.assert_array_almost_equal(grad[0], grad_expected, decimal=1)\n\n def test_get_activations(self):\n act = self.art_model.get_activations(self.x_test_diabetes[:4], 1)\n act_expected = [0, 0, 0, 7.8, 8.5, 0, 5.6, 0, 6.6, 5.8]\n np.testing.assert_array_almost_equal(act[0], act_expected, decimal=1)\n\n\nclass TestKerasRegressorClass(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUpClass()\n\n import tensorflow as tf\n import tensorflow.keras as keras\n\n class TestModel(tf.keras.Model):\n def __init__(self):\n super().__init__()\n self.dense1 = keras.layers.Dense(10, activation=tf.nn.relu)\n self.dense2 = keras.layers.Dense(100, activation=tf.nn.relu)\n self.dense3 = keras.layers.Dense(10, activation=tf.nn.relu)\n self.dense4 = keras.layers.Dense(1)\n\n def call(self, inputs):\n x = self.dense1(inputs)\n return self.dense4(self.dense3(self.dense2(x)))\n\n cls.keras_model = TestModel()\n cls.keras_model.compile(\n loss=keras.losses.CosineSimilarity(axis=-1, reduction=\"auto\", name=\"cosine_similarity\"),\n optimizer=keras.optimizers.Adam(learning_rate=0.01),\n metrics=[\"accuracy\"],\n )\n cls.keras_model.fit(cls.x_train_diabetes, cls.y_train_diabetes)\n\n cls.art_model = KerasRegressor(model=cls.keras_model)\n\n def test_type(self):\n with self.assertRaises(TypeError):\n KerasRegressor(model=\"model\")\n\n def test_predict(self):\n y_predicted = self.art_model.predict(self.x_test_diabetes[:4])\n np.testing.assert_equal(len(np.unique(y_predicted)), 4)\n\n def test_save(self):\n self.art_model.save(filename=\"test.file\", path=None)\n self.art_model.save(filename=\"test.file\", path=\"./\")\n\n def test_input_shape(self):\n np.testing.assert_equal(self.art_model.input_shape, (10,))\n\n def test_input_layer(self):\n np.testing.assert_equal(isinstance(self.art_model.input_layer, int), True)\n\n def test_output_layer(self):\n np.testing.assert_equal(isinstance(self.art_model.output_layer, int), True)\n\n def test_compute_loss(self):\n test_loss = self.art_model.compute_loss(self.x_test_diabetes[:4], self.y_test_diabetes[:4].astype(np.float32))\n # cosine similarity works on vectors, so it returns the same value for each sample\n np.testing.assert_equal(len(np.unique(test_loss)), 1)\n\n def test_loss_gradient(self):\n grad = self.art_model.loss_gradient(self.x_test_diabetes[:4], self.y_test_diabetes[:4])\n for row in grad:\n if not np.all((row == 0)):\n np.testing.assert_equal(len(np.unique(row)), 10)\n\n\nclass TestKerasRegressorFunctional(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_tensorflow=True)\n super().setUpClass()\n\n import tensorflow as tf\n import keras\n from keras.models import Model\n\n def functional():\n in_layer = keras.layers.Input(shape=(10,))\n layer = keras.layers.Dense(100, activation=tf.nn.relu)(in_layer)\n layer = keras.layers.Dense(10, activation=tf.nn.relu)(layer)\n out_layer = keras.layers.Dense(1)(layer)\n\n model = Model(inputs=[in_layer], outputs=[out_layer])\n\n model.compile(\n loss=keras.losses.MeanAbsoluteError(),\n optimizer=keras.optimizers.Adam(learning_rate=0.01),\n metrics=[\"accuracy\"],\n )\n\n return model\n\n cls.keras_model = functional()\n cls.keras_model.fit(cls.x_train_diabetes, cls.y_train_diabetes)\n\n cls.art_model = KerasRegressor(model=cls.keras_model)\n\n def test_type(self):\n with self.assertRaises(TypeError):\n KerasRegressor(model=\"model\")\n\n def test_predict(self):\n y_predicted = self.art_model.predict(self.x_test_diabetes[:4])\n np.testing.assert_equal(len(np.unique(y_predicted)), 4)\n\n def test_save(self):\n self.art_model.save(filename=\"test.file\", path=None)\n self.art_model.save(filename=\"test.file\", path=\"./\")\n\n def test_input_shape(self):\n np.testing.assert_equal(self.art_model.input_shape, (10,))\n\n def test_input_layer(self):\n np.testing.assert_equal(isinstance(self.art_model.input_layer, int), True)\n\n def test_output_layer(self):\n np.testing.assert_equal(isinstance(self.art_model.output_layer, int), True)\n\n def test_compute_loss(self):\n test_loss = self.art_model.compute_loss(self.x_test_diabetes[:4], self.y_test_diabetes[:4].astype(np.float32))\n np.testing.assert_equal(len(np.unique(test_loss)), 4)\n\n def test_loss_gradient(self):\n grad = self.art_model.loss_gradient(self.x_test_diabetes[:4], self.y_test_diabetes[:4])\n np.testing.assert_equal(len(np.unique(grad[0])), 10)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/regression/test_pytorch_regression.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\nimport numpy as np\n\nfrom torch import nn, optim\n\nfrom art.estimators.regression.pytorch import PyTorchRegressor\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestPytorchRegressor(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234, set_torch=True)\n super().setUpClass()\n\n class TestModel(nn.Module):\n def __init__(self):\n super().__init__()\n\n self.features = nn.Sequential(\n nn.Linear(10, 100),\n nn.ReLU(),\n nn.Linear(100, 10),\n nn.ReLU(),\n )\n\n self.output = nn.Linear(10, 1)\n\n def forward(self, x):\n return self.output(self.features(x))\n\n cls.pytorch_model = TestModel()\n\n cls.art_model = PyTorchRegressor(\n model=cls.pytorch_model,\n loss=nn.modules.loss.MSELoss(),\n input_shape=(10,),\n optimizer=optim.Adam(cls.pytorch_model.parameters(), lr=0.01),\n )\n cls.art_model.fit(cls.x_train_diabetes.astype(np.float32), cls.y_train_diabetes.astype(np.float32))\n\n def test_type(self):\n self.assertIsInstance(\n self.art_model,\n type(\n PyTorchRegressor(\n model=self.pytorch_model,\n loss=nn.modules.loss.MSELoss(),\n input_shape=(10,),\n optimizer=optim.Adam(self.pytorch_model.parameters(), lr=0.01),\n )\n ),\n )\n with self.assertRaises(TypeError):\n PyTorchRegressor(\n model=\"model\",\n loss=nn.modules.loss.MSELoss,\n input_shape=(10,),\n optimizer=optim.Adam(self.pytorch_model.parameters(), lr=0.01),\n )\n\n def test_predict(self):\n y_predicted = self.art_model.predict(self.x_test_diabetes[:4].astype(np.float32))\n y_expected = np.array([[19.2], [31.8], [13.8], [42.1]])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=1)\n\n def test_save(self):\n self.art_model.save(filename=\"test.file\", path=None)\n self.art_model.save(filename=\"test.file\", path=\"./\")\n\n def test_input_shape(self):\n np.testing.assert_equal(self.art_model.input_shape, (10,))\n\n def test_compute_loss(self):\n test_loss = self.art_model.compute_loss(\n self.x_test_diabetes[:4].astype(np.float32), self.y_test_diabetes[:4].astype(np.float32)\n )\n loss_expected = [3461.6, 5214.4, 3994.9, 9003.6]\n np.testing.assert_array_almost_equal(test_loss, loss_expected, decimal=1)\n\n def test_loss_gradient(self):\n grad = self.art_model.loss_gradient(\n self.x_test_diabetes[:4].astype(np.float32), self.y_test_diabetes[:4].astype(np.float32)\n )\n # grads are same shape as x (i.e., (10,4)), we are looking only at the first row\n grad_expected = [-49.4, 129.9, -170.1, -116.6, -225.2, -171.9, 174.6, -166.8, -223.9, -154.4]\n np.testing.assert_array_almost_equal(grad[0], grad_expected, decimal=1)\n\n def test_get_activations(self):\n act = self.art_model.get_activations(self.x_test_diabetes[:4].astype(np.float32), 1)\n act_expected = np.array([[19.2], [31.8], [13.8], [42.1]])\n np.testing.assert_array_almost_equal(act, act_expected, decimal=1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/regression/test_scikitlearn.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\nimport numpy as np\n\nfrom sklearn.tree import DecisionTreeRegressor\n\nfrom art.estimators.regression.scikitlearn import ScikitlearnDecisionTreeRegressor\nfrom art.estimators.regression.scikitlearn import ScikitlearnRegressor\n\nfrom tests.utils import TestBase, master_seed\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestScikitlearnDecisionTreeRegressor(TestBase):\n @classmethod\n def setUpClass(cls):\n master_seed(seed=1234)\n super().setUpClass()\n\n cls.sklearn_model = DecisionTreeRegressor()\n cls.classifier = ScikitlearnDecisionTreeRegressor(model=cls.sklearn_model)\n cls.classifier.fit(x=cls.x_train_diabetes, y=cls.y_train_diabetes)\n\n def test_type(self):\n self.assertIsInstance(self.classifier, type(ScikitlearnRegressor(model=self.sklearn_model)))\n with self.assertRaises(TypeError):\n ScikitlearnDecisionTreeRegressor(model=\"sklearn_model\")\n\n def test_predict(self):\n y_predicted = self.classifier.predict(self.x_test_diabetes[:4])\n y_expected = np.asarray([69.0, 81.0, 68.0, 68.0])\n np.testing.assert_array_almost_equal(y_predicted, y_expected, decimal=1)\n\n def test_save(self):\n self.classifier.save(filename=\"test.file\", path=None)\n self.classifier.save(filename=\"test.file\", path=\"./\")\n\n def test_clone_for_refitting(self):\n _ = self.classifier.clone_for_refitting()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/speech_recognition/conftest.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\nimport pytest\n\n\n@pytest.fixture\ndef audio_data():\n \"\"\"\n Create audio fixtures of shape (nb_samples=3,) with elements of variable length.\n \"\"\"\n sample_rate = 16000\n test_input = np.array(\n [\n np.zeros(sample_rate),\n np.ones(sample_rate * 2) * 2e3,\n np.ones(sample_rate * 3) * 3e3,\n np.ones(sample_rate * 3) * 3e3,\n ],\n dtype=object,\n )\n return test_input\n\n\n@pytest.fixture\ndef audio_batch_padded():\n \"\"\"\n Create audio fixtures of shape (batch_size=2,) with elements of variable length.\n \"\"\"\n sample_rate = 16000\n frequency_length = (sample_rate // 2 + 1) // 240 * 3\n test_input = np.zeros((2, sample_rate))\n test_mask_frequency = np.ones((2, frequency_length, 80))\n return test_input, test_mask_frequency\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/speech_recognition/test_pytorch_deep_speech.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_pytorch_deep_speech[cpu-False]\": {\n \"x_1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x_2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x_3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n \"expected_sizes\": [\n 5,\n 5,\n 5\n ],\n \"expected_transcriptions_1\": [\n \"\",\n \"\",\n \"\"\n ],\n \"expected_transcriptions_2\": [\n \"\"\n ],\n \"expected_probs\": {\n \"v2\": [\n 1.0,\n 7.0154901e-14,\n 1.9170589e-13,\n 8.2194836e-13,\n 8.9967915e-13,\n 1.8518193e-12,\n 1.7883164e-10,\n 1.8951663e-12,\n 1.8818237e-13,\n 3.2806991e-12,\n 3.5664666e-16,\n 3.3147299e-14,\n 2.3439516e-13,\n 8.4845603e-12,\n 1.2017718e-13,\n 1.1180213e-12,\n 6.5572378e-15,\n 3.0194697e-12,\n 4.9065188e-15,\n 1.9765363e-13,\n 4.1670646e-11,\n 2.6884213e-12,\n 1.1436632e-13,\n 7.1931783e-15,\n 2.8135227e-11,\n 4.5599673e-14,\n 6.4587983e-13,\n 2.4159567e-15,\n 4.6668241e-13\n ],\n \"v3\": [\n 4.3231237e-01,\n 9.3365299e-05,\n 1.0878629e-01,\n 7.9091638e-03,\n 3.6059748e-03,\n 5.5831848e-03,\n 2.8087096e-02,\n 3.0162700e-03,\n 3.8522705e-03,\n 1.6105857e-01,\n 6.8382420e-02,\n 7.1456854e-04,\n 1.6094667e-03,\n 2.7614702e-02,\n 1.2125540e-02,\n 1.1442531e-02,\n 3.7315700e-02,\n 2.1599031e-03,\n 2.0267154e-04,\n 2.2302734e-02,\n 1.0788176e-02,\n 2.3048868e-02,\n 1.3910943e-02,\n 1.6170385e-03,\n 5.8020870e-03,\n 1.6773106e-04,\n 5.0454037e-03,\n 8.1572085e-05,\n 1.3634346e-03\n ]\n },\n \"expected_gradients_1\": {\n \"v2\": [\n 11.193785,\n -178.84323,\n -133.64279,\n -58.76684,\n 18.947964,\n 166.79495,\n -190.89116,\n -410.17804,\n -287.00235,\n -89.101746,\n 14.428745,\n 294.6465,\n 273.6012,\n -86.5161,\n -101.78099,\n -27.561146,\n 224.98627,\n 164.8558,\n 510.2224,\n 217.21165\n ],\n \"v3\": [\n -27.321625,\n 86.563065,\n -43.04197,\n -14.569629,\n 9.134926,\n -51.950085,\n 47.590294,\n -39.38962,\n 37.42696,\n -38.787342,\n 11.109728,\n 38.85981,\n -74.76193,\n 27.399368,\n -16.732548,\n -19.602125,\n 26.666662,\n 38.150375,\n 28.138512,\n 44.626198\n ]\n },\n \"expected_gradients_2\": {\n \"v2\": [\n 312.857,\n 398.04456,\n -777.24536,\n -528.18286,\n -982.3347,\n -949.54297,\n 678.4746,\n 428.30353,\n -2063.8625,\n -331.0251,\n -1473.6401,\n -2278.636,\n -283.26733,\n 735.51855,\n 959.20764,\n 403.40045,\n 1881.7563,\n 919.7072,\n -358.60263,\n 146.7742\n ],\n \"v3\": [\n -123.504265,\n 258.04965,\n -284.5161,\n -345.35703,\n -61.765545,\n -257.90338,\n -177.54489,\n -105.25926,\n -12.075447,\n -35.941578,\n 112.01139,\n -94.004364,\n -92.55763,\n 616.5608,\n -276.42224,\n 174.28311,\n -129.62082,\n 34.121708,\n 131.9381,\n 94.4453\n ]\n },\n \"expected_gradients_3\": {\n \"v2\": [\n 280.516,\n 608.26324,\n -33.13816,\n -1913.7281,\n -1355.9631,\n 170.70584,\n -1496.659,\n -481.76575,\n -971.2877,\n -943.00305,\n -1864.1355,\n -2126.0085,\n -430.51877,\n -2018.3965,\n -1901.1837,\n 1102.4495,\n 2399.1104,\n 1467.0935,\n 1616.0001,\n 1611.2112\n ],\n \"v3\": [\n -524.2962,\n -260.02936,\n 578.2185,\n -158.79018,\n -37.202496,\n -311.07156,\n -3.984712,\n 166.36012,\n -15.264099,\n 199.08426,\n 72.971436,\n 175.62677,\n -404.36395,\n -171.99176,\n 370.83533,\n -220.93425,\n -1.2995263,\n 146.4521,\n -381.7052,\n -69.52321\n ]\n }\n },\n \"test_pytorch_deep_speech[cpu-True]\": {\n \"x_1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x_2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x_3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n \"expected_sizes\": [\n 5,\n 5,\n 5\n ],\n \"expected_transcriptions_1\": [\n \"\",\n \"\",\n \"\"\n ],\n \"expected_transcriptions_2\": [\n \"\"\n ],\n \"expected_probs\": {\n \"v2\": [\n 1.0,\n 7.0154901e-14,\n 1.9170589e-13,\n 8.2194836e-13,\n 8.9967915e-13,\n 1.8518193e-12,\n 1.7883164e-10,\n 1.8951663e-12,\n 1.8818237e-13,\n 3.2806991e-12,\n 3.5664666e-16,\n 3.3147299e-14,\n 2.3439516e-13,\n 8.4845603e-12,\n 1.2017718e-13,\n 1.1180213e-12,\n 6.5572378e-15,\n 3.0194697e-12,\n 4.9065188e-15,\n 1.9765363e-13,\n 4.1670646e-11,\n 2.6884213e-12,\n 1.1436632e-13,\n 7.1931783e-15,\n 2.8135227e-11,\n 4.5599673e-14,\n 6.4587983e-13,\n 2.4159567e-15,\n 4.6668241e-13\n ],\n \"v3\": [\n 4.3231237e-01,\n 9.3365299e-05,\n 1.0878629e-01,\n 7.9091638e-03,\n 3.6059748e-03,\n 5.5831848e-03,\n 2.8087096e-02,\n 3.0162700e-03,\n 3.8522705e-03,\n 1.6105857e-01,\n 6.8382420e-02,\n 7.1456854e-04,\n 1.6094667e-03,\n 2.7614702e-02,\n 1.2125540e-02,\n 1.1442531e-02,\n 3.7315700e-02,\n 2.1599031e-03,\n 2.0267154e-04,\n 2.2302734e-02,\n 1.0788176e-02,\n 2.3048868e-02,\n 1.3910943e-02,\n 1.6170385e-03,\n 5.8020870e-03,\n 1.6773106e-04,\n 5.0454037e-03,\n 8.1572085e-05,\n 1.3634346e-03\n ]\n },\n \"expected_gradients_1\": {\n \"v2\": [\n 11.193785,\n -178.84323,\n -133.64279,\n -58.76684,\n 18.947964,\n 166.79495,\n -190.89116,\n -410.17804,\n -287.00235,\n -89.101746,\n 14.428745,\n 294.6465,\n 273.6012,\n -86.5161,\n -101.78099,\n -27.561146,\n 224.98627,\n 164.8558,\n 510.2224,\n 217.21165\n ],\n \"v3\": [\n -27.321625,\n 86.563065,\n -43.04197,\n -14.569629,\n 9.134926,\n -51.950085,\n 47.590294,\n -39.38962,\n 37.42696,\n -38.787342,\n 11.109728,\n 38.85981,\n -74.76193,\n 27.399368,\n -16.732548,\n -19.602125,\n 26.666662,\n 38.150375,\n 28.138512,\n 44.626198\n ]\n },\n \"expected_gradients_2\": {\n \"v2\": [\n 312.857,\n 398.04456,\n -777.24536,\n -528.18286,\n -982.3347,\n -949.54297,\n 678.4746,\n 428.30353,\n -2063.8625,\n -331.0251,\n -1473.6401,\n -2278.636,\n -283.26733,\n 735.51855,\n 959.20764,\n 403.40045,\n 1881.7563,\n 919.7072,\n -358.60263,\n 146.7742\n ],\n \"v3\": [\n -123.504265,\n 258.04965,\n -284.5161,\n -345.35703,\n -61.765545,\n -257.90338,\n -177.54489,\n -105.25926,\n -12.075447,\n -35.941578,\n 112.01139,\n -94.004364,\n -92.55763,\n 616.5608,\n -276.42224,\n 174.28311,\n -129.62082,\n 34.121708,\n 131.9381,\n 94.4453\n ]\n },\n \"expected_gradients_3\": {\n \"v2\": [\n 280.516,\n 608.26324,\n -33.13816,\n -1913.7281,\n -1355.9631,\n 170.70584,\n -1496.659,\n -481.76575,\n -971.2877,\n -943.00305,\n -1864.1355,\n -2126.0085,\n -430.51877,\n -2018.3965,\n -1901.1837,\n 1102.4495,\n 2399.1104,\n 1467.0935,\n 1616.0001,\n 1611.2112\n ],\n \"v3\": [\n -524.2962,\n -260.02936,\n 578.2185,\n -158.79018,\n -37.202496,\n -311.07156,\n -3.984712,\n 166.36012,\n -15.264099,\n 199.08426,\n 72.971436,\n 175.62677,\n -404.36395,\n -171.99176,\n 370.83533,\n -220.93425,\n -1.2995263,\n 146.4521,\n -381.7052,\n -69.52321\n ]\n }\n },\n \"test_pytorch_deep_speech[gpu-False]\": {\n \"x_1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x_2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x_3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n \"expected_sizes\": [\n 5,\n 5,\n 5\n ],\n \"expected_transcriptions_1\": [\n \"\",\n \"\",\n \"\"\n ],\n \"expected_transcriptions_2\": [\n \"\"\n ],\n \"expected_probs\": {\n \"v2\": [\n 1.0,\n 7.0154901e-14,\n 1.9170589e-13,\n 8.2194836e-13,\n 8.9967915e-13,\n 1.8518193e-12,\n 1.7883164e-10,\n 1.8951663e-12,\n 1.8818237e-13,\n 3.2806991e-12,\n 3.5664666e-16,\n 3.3147299e-14,\n 2.3439516e-13,\n 8.4845603e-12,\n 1.2017718e-13,\n 1.1180213e-12,\n 6.5572378e-15,\n 3.0194697e-12,\n 4.9065188e-15,\n 1.9765363e-13,\n 4.1670646e-11,\n 2.6884213e-12,\n 1.1436632e-13,\n 7.1931783e-15,\n 2.8135227e-11,\n 4.5599673e-14,\n 6.4587983e-13,\n 2.4159567e-15,\n 4.6668241e-13\n ],\n \"v3\": [\n 4.3231237e-01,\n 9.3365299e-05,\n 1.0878629e-01,\n 7.9091638e-03,\n 3.6059748e-03,\n 5.5831848e-03,\n 2.8087096e-02,\n 3.0162700e-03,\n 3.8522705e-03,\n 1.6105857e-01,\n 6.8382420e-02,\n 7.1456854e-04,\n 1.6094667e-03,\n 2.7614702e-02,\n 1.2125540e-02,\n 1.1442531e-02,\n 3.7315700e-02,\n 2.1599031e-03,\n 2.0267154e-04,\n 2.2302734e-02,\n 1.0788176e-02,\n 2.3048868e-02,\n 1.3910943e-02,\n 1.6170385e-03,\n 5.8020870e-03,\n 1.6773106e-04,\n 5.0454037e-03,\n 8.1572085e-05,\n 1.3634346e-03\n ]\n },\n \"expected_gradients_1\": {\n \"v2\": [\n 11.193785,\n -178.84323,\n -133.64279,\n -58.76684,\n 18.947964,\n 166.79495,\n -190.89116,\n -410.17804,\n -287.00235,\n -89.101746,\n 14.428745,\n 294.6465,\n 273.6012,\n -86.5161,\n -101.78099,\n -27.561146,\n 224.98627,\n 164.8558,\n 510.2224,\n 217.21165\n ],\n \"v3\": [\n -27.321625,\n 86.563065,\n -43.04197,\n -14.569629,\n 9.134926,\n -51.950085,\n 47.590294,\n -39.38962,\n 37.42696,\n -38.787342,\n 11.109728,\n 38.85981,\n -74.76193,\n 27.399368,\n -16.732548,\n -19.602125,\n 26.666662,\n 38.150375,\n 28.138512,\n 44.626198\n ]\n },\n \"expected_gradients_2\": {\n \"v2\": [\n 312.857,\n 398.04456,\n -777.24536,\n -528.18286,\n -982.3347,\n -949.54297,\n 678.4746,\n 428.30353,\n -2063.8625,\n -331.0251,\n -1473.6401,\n -2278.636,\n -283.26733,\n 735.51855,\n 959.20764,\n 403.40045,\n 1881.7563,\n 919.7072,\n -358.60263,\n 146.7742\n ],\n \"v3\": [\n -123.504265,\n 258.04965,\n -284.5161,\n -345.35703,\n -61.765545,\n -257.90338,\n -177.54489,\n -105.25926,\n -12.075447,\n -35.941578,\n 112.01139,\n -94.004364,\n -92.55763,\n 616.5608,\n -276.42224,\n 174.28311,\n -129.62082,\n 34.121708,\n 131.9381,\n 94.4453\n ]\n },\n \"expected_gradients_3\": {\n \"v2\": [\n 280.516,\n 608.26324,\n -33.13816,\n -1913.7281,\n -1355.9631,\n 170.70584,\n -1496.659,\n -481.76575,\n -971.2877,\n -943.00305,\n -1864.1355,\n -2126.0085,\n -430.51877,\n -2018.3965,\n -1901.1837,\n 1102.4495,\n 2399.1104,\n 1467.0935,\n 1616.0001,\n 1611.2112\n ],\n \"v3\": [\n -524.2962,\n -260.02936,\n 578.2185,\n -158.79018,\n -37.202496,\n -311.07156,\n -3.984712,\n 166.36012,\n -15.264099,\n 199.08426,\n 72.971436,\n 175.62677,\n -404.36395,\n -171.99176,\n 370.83533,\n -220.93425,\n -1.2995263,\n 146.4521,\n -381.7052,\n -69.52321\n ]\n }\n },\n \"test_pytorch_deep_speech[gpu-True]\": {\n \"x_1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x_2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x_3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n \"expected_sizes\": [\n 5,\n 5,\n 5\n ],\n \"expected_transcriptions_1\": [\n \"\",\n \"\",\n \"\"\n ],\n \"expected_transcriptions_2\": [\n \"\"\n ],\n \"expected_probs\": {\n \"v2\": [\n 1.0,\n 7.0154901e-14,\n 1.9170589e-13,\n 8.2194836e-13,\n 8.9967915e-13,\n 1.8518193e-12,\n 1.7883164e-10,\n 1.8951663e-12,\n 1.8818237e-13,\n 3.2806991e-12,\n 3.5664666e-16,\n 3.3147299e-14,\n 2.3439516e-13,\n 8.4845603e-12,\n 1.2017718e-13,\n 1.1180213e-12,\n 6.5572378e-15,\n 3.0194697e-12,\n 4.9065188e-15,\n 1.9765363e-13,\n 4.1670646e-11,\n 2.6884213e-12,\n 1.1436632e-13,\n 7.1931783e-15,\n 2.8135227e-11,\n 4.5599673e-14,\n 6.4587983e-13,\n 2.4159567e-15,\n 4.6668241e-13\n ],\n \"v3\": [\n 4.31849748e-01,\n 9.35347416e-05,\n 1.08975664e-01,\n 7.90960435e-03,\n 3.60716227e-03,\n 5.58688259e-03,\n 2.81534549e-02,\n 3.01978947e-03,\n 3.85483308e-03,\n 1.60898402e-01,\n 6.85290247e-02,\n 7.14466500e-04,\n 1.61322288e-03,\n 2.76215579e-02,\n 1.21315811e-02,\n 1.14523489e-02,\n 3.73952836e-02,\n 2.16236548e-03,\n 2.02708805e-04,\n 2.23324671e-02,\n 1.08058695e-02,\n 2.30554454e-02,\n 1.39429262e-02,\n 1.61953690e-03,\n 5.80376806e-03,\n 1.68051498e-04,\n 5.05225966e-03,\n 8.15824533e-05,\n 1.36645301e-03\n ]\n },\n \"expected_gradients_1\": {\n \"v2\": [\n 11.056438,\n -178.2597,\n -132.52388,\n -58.433487,\n 19.08565,\n 167.6223,\n -190.60515,\n -410.422,\n -287.01892,\n -89.92315,\n 14.178708,\n 294.23502,\n 273.01614,\n -85.66795,\n -100.98799,\n -27.604164,\n 224.84123,\n 165.1312,\n 510.0185,\n 216.94879\n ],\n \"v3\": [\n -27.41558,\n 86.82488,\n -42.92517,\n -14.499531,\n 9.173909,\n -51.967667,\n 47.691452,\n -39.498512,\n 37.547874,\n -38.860317,\n 11.294006,\n 38.831482,\n -75.20324,\n 27.462997,\n -16.556395,\n -19.65487,\n 26.613054,\n 38.15976,\n 28.17775,\n 44.72055\n ]\n },\n \"expected_gradients_2\": {\n \"v2\": [\n 307.86743,\n 396.0844,\n -779.52893,\n -530.1992,\n -982.2849,\n -951.45667,\n 676.9315,\n 425.4591,\n -2065.4749,\n -329.677,\n -1471.921,\n -2276.9023,\n -281.53204,\n 735.0884,\n 959.46954,\n 403.35968,\n 1883.3346,\n 921.14856,\n -356.79807,\n 148.01099\n ],\n \"v3\": [\n -125.786644,\n 260.95422,\n -280.8551,\n -350.66766,\n -60.616417,\n -250.97084,\n -183.044,\n -109.02098,\n -4.8704944,\n -37.471966,\n 106.340744,\n -88.50845,\n -91.449646,\n 611.4572,\n -273.33817,\n 175.95021,\n -133.59329,\n 34.80343,\n 137.05263,\n 89.33247\n ]\n },\n \"expected_gradients_3\": {\n \"v2\": [\n 281.69296,\n 607.7366,\n -38.60257,\n -1904.9764,\n -1357.509,\n 175.64902,\n -1494.0803,\n -482.81104,\n -965.03406,\n -940.4876,\n -1859.8589,\n -2127.368,\n -430.112,\n -2018.3772,\n -1899.3477,\n 1105.3877,\n 2399.3855,\n 1462.6914,\n 1617.7285,\n 1608.8623\n ],\n \"v3\": [\n -525.10785,\n -260.36594,\n 579.0835,\n -158.32376,\n -36.87236,\n -311.53796,\n -4.4533834,\n 166.2576,\n -15.367881,\n 199.66483,\n 73.20894,\n 175.20691,\n -405.43243,\n -172.34337,\n 371.65414,\n -220.92719,\n -1.3879476,\n 146.13953,\n -382.72717,\n -69.50905\n ]\n }\n },\n \"test_pytorch_deep_speech_preprocessor\": {\n \"x_preprocessor_1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x_preprocessor_2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x_preprocessor_3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n \"expected_sizes_preprocessor\": [\n 5,\n 5,\n 5\n ],\n \"expected_transcriptions_preprocessor_1\": [\n \"\",\n \"\",\n \"\"\n ],\n \"expected_transcriptions_preprocessor_2\": [\n \"\"\n ],\n \"expected_probs_preprocessor\": {\n \"v2\": [\n 1.0,\n 7.0154901e-14,\n 1.9170589e-13,\n 8.2194836e-13,\n 8.9967915e-13,\n 1.8518193e-12,\n 1.7883164e-10,\n 1.8951663e-12,\n 1.8818237e-13,\n 3.2806991e-12,\n 3.5664666e-16,\n 3.3147299e-14,\n 2.3439516e-13,\n 8.4845603e-12,\n 1.2017718e-13,\n 1.1180213e-12,\n 6.5572378e-15,\n 3.0194697e-12,\n 4.9065188e-15,\n 1.9765363e-13,\n 4.1670646e-11,\n 2.6884213e-12,\n 1.1436632e-13,\n 7.1931783e-15,\n 2.8135227e-11,\n 4.5599673e-14,\n 6.4587983e-13,\n 2.4159567e-15,\n 4.6668241e-13\n ],\n \"v3\": [\n 6.8474430e-01,\n 6.7634406e-05,\n 3.0033341e-02,\n 2.2176523e-02,\n 7.3014279e-03,\n 1.0147078e-02,\n 5.1646042e-03,\n 5.5127372e-03,\n 7.5150388e-03,\n 3.2920036e-02,\n 1.6504159e-02,\n 1.9369723e-03,\n 1.9920601e-03,\n 1.9050783e-02,\n 1.8956853e-02,\n 1.5115841e-02,\n 1.2019396e-02,\n 3.3244377e-03,\n 6.1001343e-04,\n 1.0310450e-02,\n 1.9294998e-02,\n 4.2981599e-02,\n 4.7596693e-03,\n 1.9079226e-03,\n 2.1830756e-02,\n 2.9975444e-04,\n 2.8619647e-03,\n 1.3841648e-04,\n 5.2122335e-04\n ]\n },\n \"expected_gradients_preprocessor_1\": {\n \"v2\": [\n 270.2276,\n -138.41716,\n -20.38734,\n -164.91763,\n 82.91873,\n -13.095243,\n -61.538025,\n -122.81699,\n -257.90247,\n -186.93079,\n -113.66026,\n 400.3171,\n 206.73738,\n 193.09584,\n -68.902695,\n 97.74199,\n 117.32596,\n 245.96143,\n 225.67722,\n 59.330414\n ],\n \"v3\": [\n -52.107204,\n 80.12434,\n 0.1422075,\n -16.747665,\n 5.482609,\n -73.00292,\n 4.8389072,\n -68.28195,\n 31.532806,\n 32.751762,\n 29.901394,\n 6.7506924,\n -8.392263,\n -9.66983,\n -47.149708,\n 17.356539,\n -21.253674,\n 30.251003,\n 45.01815,\n 24.449715\n ]\n },\n \"expected_gradients_preprocessor_2\": {\n \"v2\": [\n 173.41707,\n -85.850555,\n -66.11275,\n 23.569967,\n 38.66584,\n 116.66356,\n 84.216805,\n -261.81558,\n -202.7013,\n -234.30713,\n -138.39798,\n 189.55074,\n 90.5094,\n 156.47551,\n 136.05484,\n 168.8523,\n 106.98416,\n 78.54337,\n -10.29669,\n 21.173508\n ],\n \"v3\": [\n -3.0621164,\n -24.822927,\n 4.329992,\n 23.721256,\n 22.204624,\n -7.0020237,\n -14.920893,\n 11.819107,\n -4.6338096,\n -21.96893,\n -9.85806,\n 1.978956,\n -18.523891,\n -10.621268,\n 32.286957,\n 27.502445,\n -29.073832,\n -21.147717,\n -10.401826,\n -5.8815036\n ]\n },\n \"expected_gradients_preprocessor_3\": {\n \"v2\": [\n 587.5851,\n 1.935164,\n 18.201942,\n 127.65872,\n 227.94571,\n -112.70435,\n -10.846907,\n -484.52908,\n -1024.9589,\n -1100.1394,\n -391.4168,\n 438.13324,\n 197.09824,\n 537.3054,\n 766.1222,\n 512.6279,\n 196.47073,\n 592.95514,\n 334.2837,\n 106.87009\n ],\n \"v3\": [\n -320.31787,\n 458.37903,\n 166.74754,\n -60.69311,\n -110.62456,\n -219.13577,\n 73.11543,\n -242.01416,\n 133.31516,\n 112.652115,\n 60.64424,\n -216.93463,\n 92.05547,\n 89.600334,\n -168.58362,\n 3.0452464,\n 144.53711,\n 299.63873,\n 124.885254,\n 56.88322\n ]\n }\n }\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/speech_recognition/test_pytorch_deep_speech.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_module(\"deepspeech_pytorch\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"use_amp\", [False, True])\n@pytest.mark.parametrize(\"device_type\", [\"cpu\", \"gpu\"])\ndef test_pytorch_deep_speech(art_warning, expected_values, use_amp, device_type):\n # Only import if deepspeech_pytorch module is available\n import torch\n\n from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\n\n try:\n # Skip test if gpu is not available and use_amp is true\n if use_amp and not torch.cuda.is_available():\n return\n\n # Initialize a speech recognizer\n speech_recognizer = PyTorchDeepSpeech(pretrained_model=\"librispeech\", device_type=device_type, use_amp=use_amp)\n\n # Get version of DeepSpeech\n version = \"v{}\".format(speech_recognizer._version)\n\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[\"x_1\"]\n x2 = expected_data[\"x_2\"]\n x3 = expected_data[\"x_3\"]\n expected_sizes = expected_data[\"expected_sizes\"]\n expected_transcriptions1 = expected_data[\"expected_transcriptions_1\"]\n expected_transcriptions2 = expected_data[\"expected_transcriptions_2\"]\n expected_probs = expected_data[\"expected_probs\"][version]\n expected_gradients1 = expected_data[\"expected_gradients_1\"][version]\n expected_gradients2 = expected_data[\"expected_gradients_2\"][version]\n expected_gradients3 = expected_data[\"expected_gradients_3\"][version]\n\n # Create signal data\n x = np.array(\n [\n np.array(x1 * 100, dtype=ART_NUMPY_DTYPE),\n np.array(x2 * 100, dtype=ART_NUMPY_DTYPE),\n np.array(x3 * 100, dtype=ART_NUMPY_DTYPE),\n ]\n )\n\n # Create labels\n y = np.array([\"SIX\", \"HI\", \"GOOD\"])\n\n # Test probability outputs\n probs, sizes = speech_recognizer.predict(x, batch_size=2, transcription_output=False)\n\n np.testing.assert_array_almost_equal(probs[1][1], expected_probs, decimal=3)\n np.testing.assert_array_almost_equal(sizes, expected_sizes)\n\n # Test transcription outputs\n transcriptions = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n assert (expected_transcriptions1 == transcriptions).all()\n\n # Test transcription outputs, corner case\n transcriptions = speech_recognizer.predict(np.array([x[0]]), batch_size=2, transcription_output=True)\n\n assert (expected_transcriptions2 == transcriptions).all()\n\n # Now test loss gradients\n # Compute gradients\n grads = speech_recognizer.loss_gradient(x, y)\n\n assert grads[0].shape == (1300,)\n assert grads[1].shape == (1500,)\n assert grads[2].shape == (1400,)\n\n np.testing.assert_array_almost_equal(grads[0][:20], expected_gradients1, decimal=-2)\n np.testing.assert_array_almost_equal(grads[1][:20], expected_gradients2, decimal=-2)\n np.testing.assert_array_almost_equal(grads[2][:20], expected_gradients3, decimal=-2)\n\n # Now test fit function\n # Create the optimizer\n parameters = speech_recognizer.model.parameters()\n speech_recognizer._optimizer = torch.optim.SGD(parameters, lr=0.01)\n\n # Before train\n transcriptions1 = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n # Train the estimator\n speech_recognizer.fit(x=x, y=y, batch_size=2, nb_epochs=5)\n\n # After train\n transcriptions2 = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n assert not ((transcriptions1 == transcriptions2).all())\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"deepspeech_pytorch\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_pytorch_deep_speech_preprocessor(\n art_warning,\n expected_values,\n):\n # Only import if deepspeech_pytorch module is available\n import torch\n\n from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech\n from art.defences.preprocessor.mp3_compression_pytorch import Mp3CompressionPyTorch\n\n try:\n # Create Mp3-preprocessor\n defense = Mp3CompressionPyTorch(sample_rate=16000, channels_first=True)\n\n # Initialize a speech recognizer\n speech_recognizer = PyTorchDeepSpeech(\n pretrained_model=\"librispeech\", preprocessing_defences=[defense], device_type=\"cpu\", use_amp=False\n )\n\n # Get version of DeepSpeech\n version = \"v{}\".format(speech_recognizer._version)\n\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[\"x_preprocessor_1\"]\n # x2 = expected_data[\"x_preprocessor_2\"]\n # x3 = expected_data[\"x_preprocessor_3\"]\n expected_sizes = expected_data[\"expected_sizes_preprocessor\"]\n expected_transcriptions1 = expected_data[\"expected_transcriptions_preprocessor_1\"]\n expected_transcriptions2 = expected_data[\"expected_transcriptions_preprocessor_2\"]\n expected_probs = expected_data[\"expected_probs_preprocessor\"][version]\n expected_gradients1 = expected_data[\"expected_gradients_preprocessor_1\"][version]\n expected_gradients2 = expected_data[\"expected_gradients_preprocessor_2\"][version]\n expected_gradients3 = expected_data[\"expected_gradients_preprocessor_3\"][version]\n\n # Create signal data\n x = np.array([x1 * 100, x1 * 100, x1 * 100], dtype=ART_NUMPY_DTYPE)\n\n # Create labels\n y = np.array([\"SIX\", \"HI\", \"GOOD\"])\n\n # Test probability outputs\n probs, sizes = speech_recognizer.predict(x, batch_size=1, transcription_output=False)\n\n np.testing.assert_array_almost_equal(probs[1][1], expected_probs, decimal=2)\n np.testing.assert_array_almost_equal(sizes, expected_sizes)\n\n # Test transcription outputs\n transcriptions = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n assert (expected_transcriptions1 == transcriptions).all()\n\n # Test transcription outputs, corner case\n transcriptions = speech_recognizer.predict(x[[0]], batch_size=1, transcription_output=True)\n\n assert (expected_transcriptions2 == transcriptions).all()\n\n # Now test loss gradients\n # Compute gradients\n grads = speech_recognizer.loss_gradient(x, y)\n\n assert grads[0].shape == (1300,)\n assert grads[1].shape == (1300,)\n assert grads[2].shape == (1300,)\n\n np.testing.assert_array_almost_equal(grads[0][:20], expected_gradients1, decimal=-2)\n np.testing.assert_array_almost_equal(grads[1][:20], expected_gradients2, decimal=-2)\n np.testing.assert_array_almost_equal(grads[2][:20], expected_gradients3, decimal=-2)\n\n # Now test fit function\n # Create the optimizer\n parameters = speech_recognizer.model.parameters()\n speech_recognizer._optimizer = torch.optim.SGD(parameters, lr=0.01)\n\n # Before train\n _ = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n # Train the estimator\n speech_recognizer.fit(x=x, y=y, batch_size=2, nb_epochs=10)\n\n # After train\n _ = speech_recognizer.predict(x, batch_size=2, transcription_output=True)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/speech_recognition/test_pytorch_espresso.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_pytorch_espresso[cpu]\": {\n \"x1\": [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n \"x2\": [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n \"x3\": [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n \"expected_sizes\": [\n 5,\n 5,\n 5\n ],\n \"expected_transcriptions1\": [\n \"HUH\",\n \"HUH\",\n \"HUH\"\n ],\n \"expected_transcriptions2\": [\n \"HUH\"\n ],\n \"expected_probs\": [\n 1.0,\n 7.0154901e-14,\n 1.9170589e-13,\n 8.2194836e-13,\n 8.9967915e-13,\n 1.8518193e-12,\n 1.7883164e-10,\n 1.8951663e-12,\n 1.8818237e-13,\n 3.2806991e-12,\n 3.5664666e-16,\n 3.3147299e-14,\n 2.3439516e-13,\n 8.4845603e-12,\n 1.2017718e-13,\n 1.1180213e-12,\n 6.5572378e-15,\n 3.0194697e-12,\n 4.9065188e-15,\n 1.9765363e-13,\n 4.1670646e-11,\n 2.6884213e-12,\n 1.1436632e-13,\n 7.1931783e-15,\n 2.8135227e-11,\n 4.5599673e-14,\n 6.4587983e-13,\n 2.4159567e-15,\n 4.6668241e-13\n ],\n \"expected_gradients1\": [\n -1.13756158e-07,\n 1.07015055e-07,\n -8.80476705e-08,\n -1.39331959e-07,\n 1.48917906e-07,\n -3.53058113e-07,\n 2.01485719e-07,\n -2.79461574e-07,\n 1.67964316e-07,\n -2.58871239e-07,\n -1.16557302e-07,\n 3.25986946e-07,\n -4.43552551e-07,\n 2.93529524e-07,\n -2.66194320e-07,\n -1.01649420e-07,\n -9.87961855e-08,\n 2.45819422e-07,\n -2.83475146e-07,\n 6.32509654e-08\n ],\n \"expected_gradients2\": [\n 2.7441195e-07,\n 2.8862604e-07,\n -7.4647232e-08,\n -6.4834711e-07,\n -8.4257761e-07,\n -1.1230835e-07,\n 6.7842427e-07,\n 6.7134647e-07,\n 7.1186412e-07,\n 2.7874319e-07,\n -9.8120859e-07,\n -4.3811957e-07,\n -4.4953012e-07,\n -2.6851848e-07,\n 6.8712029e-07,\n 4.9712889e-07,\n -4.2997634e-08,\n 5.2269604e-07,\n -5.1312998e-07,\n -6.4236167e-07\n ],\n \"expected_gradients3\": [\n 5.2914279e-06,\n 8.7815624e-06,\n -1.3057038e-06,\n -1.4622340e-06,\n 7.2348661e-07,\n 1.3124122e-06,\n -3.6126103e-06,\n -1.1720208e-05,\n -8.5992979e-06,\n 1.1973816e-06,\n 3.2738412e-06,\n -3.8435182e-06,\n -5.4568354e-06,\n 5.4038110e-06,\n 1.2560678e-05,\n 8.1075650e-06,\n -3.8110704e-07,\n -2.7100255e-06,\n 5.8066132e-07,\n 3.4623240e-06\n ]\n }\n}\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/estimators/speech_recognition/test_pytorch_espresso.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_module(\"espresso\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"device_type\", [\"cpu\"])\ndef test_pytorch_espresso(art_warning, expected_values, device_type):\n import torch\n\n from art.estimators.speech_recognition.pytorch_espresso import PyTorchEspresso\n\n try:\n # Initialize a speech recognizer\n speech_recognizer = PyTorchEspresso(\n model=\"librispeech_transformer\", espresso_config_filepath=None, device_type=device_type\n )\n\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[\"x1\"]\n x2 = expected_data[\"x2\"]\n x3 = expected_data[\"x3\"]\n # expected_sizes = expected_data[\"expected_sizes\"]\n expected_transcriptions1 = expected_data[\"expected_transcriptions1\"]\n expected_transcriptions2 = expected_data[\"expected_transcriptions2\"]\n # expected_probs = expected_data[\"expected_probs\"]\n expected_gradients1 = expected_data[\"expected_gradients1\"]\n expected_gradients2 = expected_data[\"expected_gradients2\"]\n expected_gradients3 = expected_data[\"expected_gradients3\"]\n\n # Create signal data\n x = np.array(\n [\n np.array(x1 * 100, dtype=ART_NUMPY_DTYPE),\n np.array(x2 * 100, dtype=ART_NUMPY_DTYPE),\n np.array(x3 * 100, dtype=ART_NUMPY_DTYPE),\n ]\n )\n\n # Create labels\n y = np.array([\"SIX\", \"HI\", \"GOOD\"])\n\n # Test probability outputs\n # probs, sizes = speech_recognizer.predict(x, batch_size=2,)\n #\n # np.testing.assert_array_almost_equal(probs[1][1], expected_probs, decimal=3)\n # np.testing.assert_array_almost_equal(sizes, expected_sizes)\n\n # Test transcription outputs\n _ = speech_recognizer.predict(x[[0]], batch_size=2)\n\n # Test transcription outputs\n transcriptions = speech_recognizer.predict(x, batch_size=2)\n\n assert (expected_transcriptions1 == transcriptions).all()\n\n # Test transcription outputs, corner case\n transcriptions = speech_recognizer.predict(np.array([x[0]]), batch_size=2)\n\n assert (expected_transcriptions2 == transcriptions).all()\n\n # Now test loss gradients\n # Compute gradients\n grads = speech_recognizer.loss_gradient(x, y)\n\n assert grads[0].shape == (1300,)\n assert grads[1].shape == (1500,)\n assert grads[2].shape == (1400,)\n\n np.testing.assert_array_almost_equal(grads[0][:20], expected_gradients1, decimal=-2)\n np.testing.assert_array_almost_equal(grads[1][:20], expected_gradients2, decimal=-2)\n np.testing.assert_array_almost_equal(grads[2][:20], expected_gradients3, decimal=-2)\n\n # Train the estimator\n with pytest.raises(NotImplementedError):\n speech_recognizer.fit(x=x, y=y, batch_size=2, nb_epochs=5)\n\n # Compute local shape\n local_batch_size = len(x)\n real_lengths = np.array([x_.shape[0] for x_ in x])\n local_max_length = np.max(real_lengths)\n\n # Reformat input\n input_mask = np.zeros([local_batch_size, local_max_length], dtype=np.float64)\n original_input = np.zeros([local_batch_size, local_max_length], dtype=np.float64)\n\n for local_batch_size_idx in range(local_batch_size):\n input_mask[local_batch_size_idx, : len(x[local_batch_size_idx])] = 1\n original_input[local_batch_size_idx, : len(x[local_batch_size_idx])] = x[local_batch_size_idx]\n\n # compute_loss_and_decoded_output\n loss, decoded_output = speech_recognizer.compute_loss_and_decoded_output(\n masked_adv_input=torch.tensor(original_input), original_output=y\n )\n\n assert loss.detach().numpy() == pytest.approx(46.3156, abs=20.0)\n assert all(decoded_output == [\"EH\", \"EH\", \"EH\"])\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/evaluations/test_great_score.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport pytest\n\nfrom art.evaluations.great_score import GreatScorePyTorch\n\nfrom tests.utils import ARTTestException\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_great_score(art_warning, image_dl_estimator, get_mnist_dataset):\n try:\n classifier, _ = image_dl_estimator(from_logits=False)\n (_, _), (x_test, y_test) = get_mnist_dataset\n\n great_score = GreatScorePyTorch(classifier=classifier)\n score, accuracy = great_score.evaluate(x=x_test, y=y_test)\n assert score == pytest.approx(0.03501499, rel=1e-6)\n assert accuracy == pytest.approx(0.2487, rel=1e-4)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/evaluations/test_security_curve.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport pytest\n\nfrom art.evaluations.security_curve import SecurityCurve\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 100\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.framework_agnostic\ndef test_generate_default(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n\n sec = SecurityCurve(eps=3)\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n eps_list, accuracy_adv_list, accuracy = sec.evaluate(classifier=classifier, x=x_train_mnist, y=y_train_mnist)\n\n assert eps_list == [0.3333333333333333, 0.6666666666666666, 1.0]\n assert accuracy_adv_list == [0.0, 0.0, 0.0]\n assert accuracy == 0.27\n assert sec.detected_obfuscating_gradients is False\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_generate_list(art_warning, fix_get_mnist_subset, image_dl_estimator):\n try:\n classifier, _ = image_dl_estimator(from_logits=True)\n\n sec = SecurityCurve(eps=[0.3333333333333333, 0.6666666666666666, 1.0])\n\n (x_train_mnist, y_train_mnist, x_test_mnist, y_test_mnist) = fix_get_mnist_subset\n\n eps_list, accuracy_adv_list, accuracy = sec.evaluate(classifier=classifier, x=x_train_mnist, y=y_train_mnist)\n\n assert eps_list == [0.3333333333333333, 0.6666666666666666, 1.0]\n assert accuracy_adv_list == [0.0, 0.0, 0.0]\n assert accuracy == 0.27\n assert sec.detected_obfuscating_gradients is False\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_repr(art_warning):\n try:\n sec = SecurityCurve(eps=3)\n\n assert repr(sec) == \"art.evaluations.security_curve.security_curve.SecurityCurve(eps=3)\"\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/metrics/test_gradient_check.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\n\nfrom art.metrics.gradient_check import loss_gradient_check\nfrom art.utils import load_mnist\n\nfrom tests.utils import TestBase, master_seed, get_image_classifier_kr\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 100\nNB_TEST = 100\n\n\nclass TestGradientCheck(TestBase):\n def setUp(self):\n master_seed(seed=42)\n super().setUp()\n\n def test_loss_gradient_check(self):\n (x_train, y_train), (x_test, y_test), _, _ = load_mnist()\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n x_test, y_test = x_test[:NB_TEST], y_test[:NB_TEST]\n\n # Get classifier and train like normal\n classifier = get_image_classifier_kr()\n classifier.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epochs=2)\n\n # Now check that the function detects bad gradients\n # Set the weights of the convolution layer to zero\n weights = classifier._model.layers[0].get_weights()\n new_weights = [np.zeros(w.shape) for w in weights]\n classifier._model.layers[0].set_weights(new_weights)\n is_bad = loss_gradient_check(classifier, x_test, y_test, verbose=False)\n\n self.assertTrue(np.all(np.any(is_bad, 1)))\n\n # Set the weights of the convolution layer to nan\n weights = classifier._model.layers[0].get_weights()\n new_weights = [np.empty(w.shape) for w in weights]\n for i in range(len(new_weights)):\n new_weights[i][:] = np.nan\n classifier._model.layers[0].set_weights(new_weights)\n is_bad = loss_gradient_check(classifier, x_test, y_test, verbose=False)\n\n self.assertTrue(np.all(np.any(is_bad, 1)))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/metrics/test_metrics.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\nimport torch.nn as nn\nimport torch.nn.functional as f\nimport torch.optim as optim\nfrom art.attacks.evasion.hop_skip_jump import HopSkipJump\n\nfrom art.estimators.classification.keras import KerasClassifier\nfrom art.estimators.classification.pytorch import PyTorchClassifier\nfrom art.metrics.metrics import (\n adversarial_accuracy,\n empirical_robustness,\n clever_t,\n clever_u,\n clever,\n loss_sensitivity,\n wasserstein_distance,\n)\nfrom art.utils import load_mnist\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\nBATCH_SIZE = 10\nNB_TRAIN = 100\nNB_TEST = 100\n\nR_L1 = 40\nR_L2 = 2\nR_LI = 0.1\n\n\nclass TestMetrics(unittest.TestCase):\n def setUp(self):\n master_seed(seed=42)\n\n def test_emp_robustness_mnist(self):\n (x_train, y_train), (_, _), _, _ = load_mnist()\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n\n # Get classifier\n classifier = self._cnn_mnist_k([28, 28, 1])\n classifier.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epochs=2, verbose=0)\n\n # Compute minimal perturbations\n params = {\"eps_step\": 1.0, \"eps\": 1.0}\n emp_robust = empirical_robustness(classifier, x_train, str(\"fgsm\"), params)\n self.assertAlmostEqual(emp_robust, 1.000369094488189, 3)\n\n params = {\"eps_step\": 0.1, \"eps\": 0.2}\n emp_robust = empirical_robustness(classifier, x_train, str(\"fgsm\"), params)\n self.assertLessEqual(emp_robust, 0.65)\n\n def test_adv_acc_mnist(self):\n (x_train, y_train), (_, _), _, _ = load_mnist()\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n\n # Get classifier\n classifier = self._cnn_mnist_k([28, 28, 1])\n classifier.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epochs=2, verbose=0)\n\n # Compute adversarial accuracies\n params = {\"eps_step\": 1.0, \"eps\": 1.0}\n adv_acc = adversarial_accuracy(classifier, x_train, attack_name=str(\"fgsm\"), attack_params=params)\n self.assertAlmostEqual(adv_acc, 0)\n\n params = {\"eps_step\": 1.0, \"eps\": 1.0}\n adv_acc = adversarial_accuracy(classifier, x_train, y_train, attack_name=str(\"fgsm\"), attack_params=params)\n self.assertAlmostEqual(adv_acc, 0)\n\n params = {\"max_iter\": 10, \"max_eval\": 100, \"init_eval\": 10, \"init_size\": 10}\n adv_crafter = HopSkipJump(classifier, **params)\n adv_acc = adversarial_accuracy(classifier, x_train, attack_crafter=adv_crafter)\n self.assertLess(adv_acc, 0.2)\n\n def test_loss_sensitivity(self):\n (x_train, y_train), (_, _), _, _ = load_mnist()\n x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n\n # Get classifier\n classifier = self._cnn_mnist_k([28, 28, 1])\n classifier.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epochs=2, verbose=0)\n\n sensitivity = loss_sensitivity(classifier, x_train, y_train)\n self.assertGreaterEqual(sensitivity, 0)\n\n # def testNearestNeighborDist(self):\n # # Get MNIST\n # (x_train, y_train), (_, _), _, _ = load_mnist()\n # x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]\n #\n # # Get classifier.\n # classifier = self._cnn_mnist_k([28, 28, 1])\n # classifier.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epochs=2)\n #\n # dist = nearest_neighbour_dist(classifier, x_train, x_train, str('fgsm'))\n # self.assertGreaterEqual(dist, 0)\n\n @staticmethod\n def _cnn_mnist_k(input_shape):\n from tensorflow import keras\n from tensorflow.keras.models import Sequential\n from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\n\n # Create simple CNN\n model = Sequential()\n model.add(Conv2D(4, kernel_size=(5, 5), activation=\"relu\", input_shape=input_shape))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n model.add(Dense(10, activation=\"softmax\"))\n\n model.compile(\n loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adam(learning_rate=0.01),\n metrics=[\"accuracy\"],\n )\n\n classifier = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)\n return classifier\n\n @staticmethod\n def _create_krclassifier():\n \"\"\"\n To create a simple KerasClassifier for testing.\n :return:\n \"\"\"\n from tensorflow import keras\n from tensorflow.keras.models import Sequential\n from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\n\n # Create simple CNN\n model = Sequential()\n model.add(Conv2D(4, kernel_size=(5, 5), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n model.add(Dense(10, activation=\"softmax\"))\n\n model.compile(\n loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adam(learning_rate=0.01),\n metrics=[\"accuracy\"],\n )\n\n # Get the classifier\n krc = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)\n\n return krc\n\n @staticmethod\n def _create_ptclassifier():\n \"\"\"\n To create a simple PyTorchClassifier for testing.\n :return:\n \"\"\"\n\n class Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.conv = nn.Conv2d(1, 16, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.fc = nn.Linear(2304, 10)\n\n def forward(self, x):\n x = self.pool(f.relu(self.conv(x)))\n x = x.view(-1, 2304)\n logit_output = self.fc(x)\n\n return logit_output\n\n # Define the network\n model = Model()\n\n # Define a loss function and optimizer\n loss_fn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.01)\n\n # Get classifier\n ptc = PyTorchClassifier(\n model=model, loss=loss_fn, optimizer=optimizer, input_shape=(1, 28, 28), nb_classes=10, clip_values=(0, 1)\n )\n\n return ptc\n\n def test_clever_kr(self):\n \"\"\"\n Test with keras.\n :return:\n \"\"\"\n # Get MNIST\n batch_size, nb_train, nb_test = 100, 1000, 10\n (x_train, y_train), (x_test, y_test), _, _ = load_mnist()\n x_train, y_train = x_train[:nb_train], y_train[:nb_train]\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n\n # Get the classifier\n krc = self._create_krclassifier()\n krc.fit(x_train, y_train, batch_size=batch_size, nb_epochs=1, verbose=0)\n\n # Test targeted clever\n res0 = clever_t(krc, x_test[-1], 2, 10, 5, R_L1, norm=1, pool_factor=3)\n res1 = clever_t(krc, x_test[-1], 2, 10, 5, R_L2, norm=2, pool_factor=3)\n res2 = clever_t(krc, x_test[-1], 2, 10, 5, R_LI, norm=np.inf, pool_factor=3)\n logger.info(\"Targeted Keras: %f %f %f\", res0, res1, res2)\n self.assertNotEqual(res0, res1)\n self.assertNotEqual(res1, res2)\n self.assertNotEqual(res2, res0)\n\n # Test untargeted clever\n res0 = clever_u(krc, x_test[-1], 10, 5, R_L1, norm=1, pool_factor=3, verbose=False)\n res1 = clever_u(krc, x_test[-1], 10, 5, R_L2, norm=2, pool_factor=3, verbose=False)\n res2 = clever_u(krc, x_test[-1], 10, 5, R_LI, norm=np.inf, pool_factor=3, verbose=False)\n logger.info(\"Untargeted Keras: %f %f %f\", res0, res1, res2)\n self.assertNotEqual(res0, res1)\n self.assertNotEqual(res1, res2)\n self.assertNotEqual(res2, res0)\n\n def test_3_clever_pt(self):\n \"\"\"\n Test with pytorch.\n :return:\n \"\"\"\n # Get MNIST\n batch_size, nb_train, nb_test = 100, 1000, 10\n (x_train, y_train), (x_test, y_test), _, _ = load_mnist()\n x_train, y_train = x_train[:nb_train], y_train[:nb_train]\n x_test, y_test = x_test[:nb_test], y_test[:nb_test]\n x_train = np.swapaxes(x_train, 1, 3).astype(np.float32)\n x_test = np.swapaxes(x_test, 1, 3).astype(np.float32)\n\n # Get the classifier\n ptc = self._create_ptclassifier()\n ptc.fit(x_train, y_train, batch_size=batch_size, nb_epochs=1)\n\n # Test targeted clever\n res0 = clever_t(ptc, x_test[-1], 2, 10, 5, R_L1, norm=1, pool_factor=3)\n res1 = clever_t(ptc, x_test[-1], 2, 10, 5, R_L2, norm=2, pool_factor=3)\n res2 = clever_t(ptc, x_test[-1], 2, 10, 5, R_LI, norm=np.inf, pool_factor=3)\n logger.info(\"Targeted PyTorch: %f %f %f\", res0, res1, res2)\n self.assertNotEqual(res0, res1)\n self.assertNotEqual(res1, res2)\n self.assertNotEqual(res2, res0)\n\n # Test untargeted clever\n res0 = clever_u(ptc, x_test[-1], 10, 5, R_L1, norm=1, pool_factor=3, verbose=False)\n res1 = clever_u(ptc, x_test[-1], 10, 5, R_L2, norm=2, pool_factor=3, verbose=False)\n res2 = clever_u(ptc, x_test[-1], 10, 5, R_LI, norm=np.inf, pool_factor=3, verbose=False)\n logger.info(\"Untargeted PyTorch: %f %f %f\", res0, res1, res2)\n self.assertNotEqual(res0, res1)\n self.assertNotEqual(res1, res2)\n self.assertNotEqual(res2, res0)\n\n def test_clever_l2_no_target(self):\n batch_size = 100\n (x_train, y_train), (x_test, _), _, _ = load_mnist()\n\n # Get the classifier\n krc = self._create_krclassifier()\n krc.fit(x_train, y_train, batch_size=batch_size, nb_epochs=2, verbose=0)\n\n scores = clever(krc, x_test[0], 5, 5, 3, 2, target=None, c_init=1, pool_factor=10, verbose=False)\n logger.info(\"Clever scores for n-1 classes: %s %s\", str(scores), str(scores.shape))\n self.assertEqual(scores.shape, (krc.nb_classes - 1,))\n\n def test_clever_l2_no_target_sorted(self):\n batch_size = 100\n (x_train, y_train), (x_test, _), _, _ = load_mnist()\n\n # Get the classifier\n krc = self._create_krclassifier()\n krc.fit(x_train, y_train, batch_size=batch_size, nb_epochs=2, verbose=0)\n\n scores = clever(\n krc, x_test[0], 5, 5, 3, 2, target=None, target_sort=True, c_init=1, pool_factor=10, verbose=False\n )\n logger.info(\"Clever scores for n-1 classes: %s %s\", str(scores), str(scores.shape))\n # Should approx. be in decreasing value\n self.assertEqual(scores.shape, (krc.nb_classes - 1,))\n\n def test_clever_l2_same_target(self):\n batch_size = 100\n (x_train, y_train), (x_test, _), _, _ = load_mnist()\n\n # Get the classifier\n krc = self._create_krclassifier()\n krc.fit(x_train, y_train, batch_size=batch_size, nb_epochs=2, verbose=0)\n\n scores = clever(\n krc,\n x_test[0],\n 5,\n 5,\n 3,\n 2,\n target=np.argmax(krc.predict(x_test[:1])),\n c_init=1,\n pool_factor=10,\n verbose=False,\n )\n self.assertIsNone(scores[0], msg=\"Clever scores for the predicted class should be `None`.\")\n\n def test_1_wasserstein_distance(self):\n nb_train = 1000\n nb_test = 100\n batch_size = 3\n (x_train, y_train), (x_test, y_test), _, _ = load_mnist()\n\n x_train = x_train[0:nb_train]\n x_test = x_test[0:nb_test]\n weights = np.ones_like(x_train)\n\n wd_0 = wasserstein_distance(x_train[:batch_size], x_train[:batch_size])\n wd_1 = wasserstein_distance(x_train[:batch_size], x_test[:batch_size])\n wd_2 = wasserstein_distance(\n x_train[:batch_size], x_train[:batch_size], weights[:batch_size], weights[:batch_size]\n )\n\n np.testing.assert_array_equal(wd_0, np.asarray([0.0, 0.0, 0.0]))\n np.testing.assert_array_almost_equal(wd_1, np.asarray([0.04564, 0.01235, 0.04787]), decimal=4)\n\n np.testing.assert_array_equal(x_train.shape, np.asarray([nb_train, 28, 28, 1]))\n np.testing.assert_array_equal(x_test.shape, np.asarray([nb_test, 28, 28, 1]))\n\n np.testing.assert_array_equal(wd_2, np.asarray([0.0, 0.0, 0.0]))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/metrics/test_verification_decision_trees.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport unittest\n\nfrom xgboost import XGBClassifier\nimport lightgbm\nimport numpy as np\nfrom sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, GradientBoostingClassifier\n\nfrom art.estimators.classification.xgboost import XGBoostClassifier\nfrom art.estimators.classification.lightgbm import LightGBMClassifier\nfrom art.estimators.classification.scikitlearn import SklearnClassifier\nfrom art.utils import load_dataset\nfrom art.metrics.verification_decisions_trees import RobustnessVerificationTreeModelsCliqueMethod\n\nfrom tests.utils import master_seed\n\nlogger = logging.getLogger(__name__)\n\nNB_TRAIN = 100\nNB_TEST = 100\n\n\nclass TestMetricsTrees(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n (x_train, y_train), (x_test, y_test), _, _ = load_dataset(\"mnist\")\n\n cls.n_classes = 10\n cls.n_features = 28 * 28\n n_train = x_train.shape[0]\n n_test = x_test.shape[0]\n x_train = x_train.reshape((n_train, cls.n_features))\n x_test = x_test.reshape((n_test, cls.n_features))\n\n cls.x_train = x_train[:NB_TRAIN]\n cls.y_train = y_train[:NB_TRAIN]\n cls.x_test = x_test[:NB_TEST]\n cls.y_test = y_test[:NB_TEST]\n\n @classmethod\n def setUp(cls):\n master_seed(seed=42)\n\n def test_XGBoost(self):\n model = XGBClassifier(n_estimators=4, max_depth=6, objective=\"multi:softprob\", eval_metric=\"merror\")\n model.fit(self.x_train, np.argmax(self.y_train, axis=1))\n\n classifier = XGBoostClassifier(model=model, nb_features=self.n_features, nb_classes=self.n_classes)\n\n rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier, verbose=False)\n average_bound, verified_error = rt.verify(\n x=self.x_test, y=self.y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, max_level=2\n )\n\n self.assertAlmostEqual(average_bound, second=0.03335742187499999, places=6)\n self.assertEqual(verified_error, second=0.99)\n\n def test_LightGBM(self):\n train_data = lightgbm.Dataset(self.x_train, label=np.argmax(self.y_train, axis=1))\n test_data = lightgbm.Dataset(self.x_test, label=np.argmax(self.y_test, axis=1))\n\n parameters = {\n \"objective\": \"multiclass\",\n \"num_class\": self.n_classes,\n \"metric\": \"multi_logloss\",\n \"is_unbalance\": \"true\",\n \"boosting\": \"gbdt\",\n \"num_leaves\": 5,\n \"feature_fraction\": 0.5,\n \"bagging_fraction\": 0.5,\n \"bagging_freq\": 0,\n \"learning_rate\": 0.05,\n \"verbose\": 0,\n }\n\n model = lightgbm.train(parameters, train_data, valid_sets=test_data, num_boost_round=2)\n\n classifier = LightGBMClassifier(model=model)\n\n rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier, verbose=False)\n average_bound, verified_error = rt.verify(\n x=self.x_test, y=self.y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, max_level=2\n )\n\n self.assertEqual(average_bound, 0.047742187500000005)\n self.assertEqual(verified_error, 0.94)\n\n def test_GradientBoosting(self):\n model = GradientBoostingClassifier(n_estimators=4, max_depth=6)\n model.fit(self.x_train, np.argmax(self.y_train, axis=1))\n\n classifier = SklearnClassifier(model=model)\n\n rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier, verbose=False)\n average_bound, verified_error = rt.verify(\n x=self.x_test, y=self.y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, max_level=2\n )\n\n self.assertAlmostEqual(average_bound, 0.009, delta=0.0002)\n self.assertEqual(verified_error, 1.0)\n\n def test_RandomForest(self):\n model = RandomForestClassifier(n_estimators=4, max_depth=6)\n model.fit(self.x_train, np.argmax(self.y_train, axis=1))\n\n classifier = SklearnClassifier(model=model)\n\n rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier, verbose=False)\n average_bound, verified_error = rt.verify(\n x=self.x_test, y=self.y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, max_level=2\n )\n\n self.assertEqual(average_bound, 0.016482421874999993)\n self.assertEqual(verified_error, 1.0)\n\n def test_ExtraTrees(self):\n model = ExtraTreesClassifier(n_estimators=4, max_depth=6)\n model.fit(self.x_train, np.argmax(self.y_train, axis=1))\n\n classifier = SklearnClassifier(model=model)\n\n rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier, verbose=False)\n average_bound, verified_error = rt.verify(\n x=self.x_test, y=self.y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, max_level=2\n )\n\n self.assertEqual(average_bound, 0.05406445312499999)\n self.assertEqual(verified_error, 0.96)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/metrics/privacy/test_membership_leakage.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport pytest\nimport numpy as np\nimport random\n\nfrom art.metrics import PDTP, SHAPr, ComparisonType\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_membership_leakage_shapr_decision_tree(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n leakage = SHAPr(classifier, x_train, y_train, x_test, y_test)\n logger.info(\"Average SHAPr leakage: %.2f\", (np.average(leakage)))\n logger.info(\"Max SHAPr leakage: %.2f\", (np.max(leakage)))\n logger.info(\"Min SHAPr leakage: %.2f\", (np.min(leakage)))\n assert leakage.shape[0] == x_train.shape[0]\n assert len(leakage.shape) == 1\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_membership_leakage_shapr_tabular(art_warning, tabular_dl_estimator, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator()\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n leakage = SHAPr(classifier, x_train, y_train, x_test, y_test)\n logger.info(\"Average SHAPr leakage: %.2f\", (np.average(leakage)))\n logger.info(\"Max SHAPr leakage: %.2f\", (np.max(leakage)))\n logger.info(\"Min SHAPr leakage: %.2f\", (np.min(leakage)))\n assert leakage.shape[0] == x_train.shape[0]\n assert len(leakage.shape) == 1\n except ARTTestException as e:\n art_warning(e)\n\n\ndef test_membership_leakage_shapr_image(art_warning, image_dl_estimator, get_default_mnist_subset):\n try:\n classifier, _ = image_dl_estimator()\n (x_train, y_train), (x_test, y_test) = get_default_mnist_subset\n leakage = SHAPr(classifier, x_train, y_train, x_test, y_test)\n logger.info(\"Average SHAPr leakage: %.2f\", (np.average(leakage)))\n logger.info(\"Max SHAPr leakage: %.2f\", (np.max(leakage)))\n logger.info(\"Min SHAPr leakage: %.2f\", (np.min(leakage)))\n assert leakage.shape[0] == x_train.shape[0]\n assert len(leakage.shape) == 1\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_membership_leakage_decision_tree(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n extra_classifier = decision_tree_estimator()\n (x_train, y_train), _ = get_iris_dataset\n prev = classifier.model.tree_\n avg_leakage, worse_leakage, std_dev = PDTP(classifier, extra_classifier, x_train, y_train)\n logger.info(\"Average PDTP leakage: %.2f\", (np.average(avg_leakage)))\n logger.info(\"Max PDTP leakage: %.2f\", (np.max(avg_leakage)))\n logger.info(\"Min PDTP leakage: %.2f\", (np.min(avg_leakage)))\n assert classifier.model.tree_ == prev\n assert np.all(avg_leakage >= 1.0)\n assert np.all(np.around(worse_leakage, decimals=10) >= np.around(avg_leakage, decimals=10))\n assert len(avg_leakage.shape) == 1\n assert len(worse_leakage.shape) == 1\n assert len(std_dev.shape) == 1\n assert avg_leakage.shape[0] == x_train.shape[0]\n assert worse_leakage.shape[0] == x_train.shape[0]\n assert std_dev.shape[0] == x_train.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"keras\",\n \"kerastf\",\n)\ndef test_membership_leakage_tabular(art_warning, tabular_dl_estimator, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator()\n extra_classifier = tabular_dl_estimator()\n (x_train, y_train), _ = get_iris_dataset\n avg_leakage, worse_leakage, std_dev = PDTP(classifier, extra_classifier, x_train, y_train)\n logger.info(\"Average PDTP leakage: %.2f\", (np.average(avg_leakage)))\n logger.info(\"Max PDTP leakage: %.2f\", (np.max(avg_leakage)))\n logger.info(\"Min PDTP leakage: %.2f\", (np.min(avg_leakage)))\n assert np.all(avg_leakage >= 1.0)\n assert np.all(np.around(worse_leakage, decimals=10) >= np.around(avg_leakage, decimals=10))\n assert len(avg_leakage.shape) == 1\n assert len(worse_leakage.shape) == 1\n assert len(std_dev.shape) == 1\n assert avg_leakage.shape[0] == x_train.shape[0]\n assert worse_leakage.shape[0] == x_train.shape[0]\n assert std_dev.shape[0] == x_train.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"scikitlearn\",\n \"keras\",\n \"kerastf\",\n)\ndef test_membership_leakage_image(art_warning, image_dl_estimator, get_default_mnist_subset):\n try:\n classifier, _ = image_dl_estimator()\n extra_classifier, _ = image_dl_estimator()\n (x_train, y_train), _ = get_default_mnist_subset\n indexes = np.array(random.sample(range(x_train.shape[0]), 100))\n avg_leakage, worse_leakage, std_dev = PDTP(\n classifier, extra_classifier, x_train, y_train, indexes=indexes, num_iter=1\n )\n logger.info(\"Average PDTP leakage: %.2f\", (np.average(avg_leakage)))\n logger.info(\"Max PDTP leakage: %.2f\", (np.max(avg_leakage)))\n logger.info(\"Min PDTP leakage: %.2f\", (np.min(avg_leakage)))\n assert np.all(avg_leakage >= 1.0)\n assert np.all(np.around(worse_leakage, decimals=10) >= np.around(avg_leakage, decimals=10))\n assert len(avg_leakage.shape) == 1\n assert len(worse_leakage.shape) == 1\n assert len(std_dev.shape) == 1\n assert avg_leakage.shape[0] == 100\n assert worse_leakage.shape[0] == 100\n assert std_dev.shape[0] == 100\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"dl_frameworks\")\ndef test_membership_leakage_decision_tree_diff(art_warning, decision_tree_estimator, get_iris_dataset):\n try:\n classifier = decision_tree_estimator()\n extra_classifier = decision_tree_estimator()\n (x_train, y_train), _ = get_iris_dataset\n prev = classifier.model.tree_\n avg_leakage, worse_leakage, std_dev = PDTP(\n classifier, extra_classifier, x_train, y_train, comparison_type=ComparisonType.DIFFERENCE\n )\n logger.info(\"Average PDTP leakage: %.2f\", (np.average(avg_leakage)))\n logger.info(\"Max PDTP leakage: %.2f\", (np.max(avg_leakage)))\n logger.info(\"Min PDTP leakage: %.2f\", (np.min(avg_leakage)))\n assert classifier.model.tree_ == prev\n assert np.all(avg_leakage >= 0.0)\n assert np.all(avg_leakage <= 1.0)\n assert np.all(np.around(worse_leakage, decimals=10) >= np.around(avg_leakage, decimals=10))\n assert len(avg_leakage.shape) == 1\n assert len(worse_leakage.shape) == 1\n assert len(std_dev.shape) == 1\n assert avg_leakage.shape[0] == x_train.shape[0]\n assert worse_leakage.shape[0] == x_train.shape[0]\n assert std_dev.shape[0] == x_train.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"keras\",\n \"kerastf\",\n)\ndef test_membership_leakage_tabular_diff(art_warning, tabular_dl_estimator, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator()\n extra_classifier = tabular_dl_estimator()\n (x_train, y_train), _ = get_iris_dataset\n avg_leakage, worse_leakage, std_dev = PDTP(\n classifier, extra_classifier, x_train, y_train, comparison_type=ComparisonType.DIFFERENCE\n )\n logger.info(\"Average PDTP leakage: %.2f\", (np.average(avg_leakage)))\n logger.info(\"Max PDTP leakage: %.2f\", (np.max(avg_leakage)))\n logger.info(\"Min PDTP leakage: %.2f\", (np.min(avg_leakage)))\n assert np.all(avg_leakage >= 0.0)\n assert np.all(avg_leakage <= 1.0)\n assert np.all(np.around(worse_leakage, decimals=10) >= np.around(avg_leakage, decimals=10))\n assert len(avg_leakage.shape) == 1\n assert len(worse_leakage.shape) == 1\n assert len(std_dev.shape) == 1\n assert avg_leakage.shape[0] == x_train.shape[0]\n assert worse_leakage.shape[0] == x_train.shape[0]\n assert std_dev.shape[0] == x_train.shape[0]\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"keras\",\n \"kerastf\",\n)\ndef test_membership_leakage_image_diff(art_warning, image_dl_estimator, get_default_mnist_subset):\n try:\n classifier, _ = image_dl_estimator()\n extra_classifier, _ = image_dl_estimator()\n (x_train, y_train), _ = get_default_mnist_subset\n indexes = np.array(random.sample(range(x_train.shape[0]), 100))\n avg_leakage, worse_leakage, std_dev = PDTP(\n classifier,\n extra_classifier,\n x_train,\n y_train,\n indexes=indexes,\n num_iter=1,\n comparison_type=ComparisonType.DIFFERENCE,\n )\n logger.info(\"Average PDTP leakage: %.2f\", (np.average(avg_leakage)))\n logger.info(\"Max PDTP leakage: %.2f\", (np.max(avg_leakage)))\n logger.info(\"Min PDTP leakage: %.2f\", (np.min(avg_leakage)))\n assert np.all(avg_leakage >= 0.0)\n assert np.all(avg_leakage <= 1.0)\n assert np.all(np.around(worse_leakage, decimals=10) >= np.around(avg_leakage, decimals=10))\n assert len(avg_leakage.shape) == 1\n assert len(worse_leakage.shape) == 1\n assert len(std_dev.shape) == 1\n assert avg_leakage.shape[0] == len(indexes)\n assert worse_leakage.shape[0] == len(indexes)\n assert std_dev.shape[0] == len(indexes)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\n \"scikitlearn\",\n \"keras\",\n \"kerastf\",\n)\ndef test_errors(art_warning, tabular_dl_estimator, get_iris_dataset, image_data_generator):\n try:\n classifier = tabular_dl_estimator()\n not_classifier = image_data_generator()\n (x_train, y_train), (x_test, y_test) = get_iris_dataset\n with pytest.raises(ValueError):\n PDTP(not_classifier, classifier, x_train, y_train)\n with pytest.raises(ValueError):\n PDTP(classifier, not_classifier, x_train, y_train)\n with pytest.raises(ValueError):\n PDTP(classifier, classifier, np.delete(x_train, 1, 1), y_train)\n with pytest.raises(ValueError):\n PDTP(classifier, classifier, x_train, y_test)\n with pytest.raises(ValueError):\n PDTP(classifier, classifier, x_train, y_train, comparison_type=\"a\")\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"pytorch\", \"tensorflow\", \"scikitlearn\")\ndef test_not_implemented(art_warning, tabular_dl_estimator, get_iris_dataset):\n try:\n classifier = tabular_dl_estimator()\n (x_train, y_train), _ = get_iris_dataset\n with pytest.raises(ValueError):\n PDTP(classifier, classifier, x_train, y_train)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/metrics/privacy/test_worst_case_mia_score.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.metrics.privacy import get_roc_for_fpr, get_roc_for_multi_fprs\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\ndef test_worst_case_accuracy(art_warning):\n try:\n tpr = 1.0\n thr = 0.33\n fpr = 0.0\n y_true = np.array([1, 0, 1, 1])\n y_proba = np.array([0.35, 0.3, 0.33, 0.6])\n res = get_roc_for_fpr(attack_proba=y_proba, attack_true=y_true)[0]\n\n assert res[0] == fpr\n assert res[1] == tpr\n assert res[2] == thr\n print(res)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_worst_case_targeted_fpr_1(art_warning):\n try:\n tpr = 1.0\n thr = 0.32\n fpr = 0.5\n y_true = np.array([1, 0, 1, 1, 1, 0])\n y_proba = np.array([0.35, 0.33, 0.32, 0.6, 0.6, 0.2])\n res = get_roc_for_fpr(attack_proba=y_proba, attack_true=y_true, targeted_fpr=0.5)[0]\n assert res[0] == fpr\n assert res[1] == tpr\n assert res[2] == thr\n print(res)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_worst_case_targeted_fpr_2(art_warning):\n try:\n tpr = 0.75\n thr = 0.35\n fpr = 0.0\n y_true = np.array([1, 0, 1, 1, 1, 0])\n y_proba = np.array([0.35, 0.33, 0.32, 0.6, 0.6, 0.2])\n res = get_roc_for_fpr(attack_proba=y_proba, attack_true=y_true, targeted_fpr=0.0)[0]\n assert res[0] == fpr\n assert res[1] == tpr\n assert res[2] == thr\n print(res)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_worst_case_multiple_targeted_fpr(art_warning):\n try:\n\n y_true = np.array([1, 0, 1, 1, 1, 0])\n y_proba = np.array([0.35, 0.33, 0.32, 0.6, 0.6, 0.2])\n res = get_roc_for_multi_fprs(attack_proba=y_proba, attack_true=y_true, targeted_fprs=[0.0, 0.5])\n assert res[0][0] == 0.0\n assert res[1][0] == 0.75\n assert res[2][0] == 0.35\n\n assert res[0][1] == 0.5\n assert res[1][1] == 1.0\n assert res[2][1] == 0.32\n\n print(res)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_worst_case_score_per_class(art_warning):\n try:\n\n y_true = np.array([1, 0, 1, 1, 1, 0, 1, 0])\n y_proba = np.array([0.35, 0.33, 0.32, 0.6, 0.6, 0.2, 0.9, 0.1])\n target_model_labels = np.array([1, 1, 1, 1, 2, 1, 2, 2])\n res = get_roc_for_fpr(attack_proba=y_proba, attack_true=y_true, target_model_labels=target_model_labels)\n print(res)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/test_standardisation_mean_std.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.preprocessing.standardisation_mean_std import (\n StandardisationMeanStd,\n StandardisationMeanStdPyTorch,\n StandardisationMeanStdTensorFlow,\n)\nfrom art.preprocessing.standardisation_mean_std.utils import broadcastable_mean_std\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(params=[True, False], ids=[\"channels_first\", \"channels_last\"])\ndef image_batch(request):\n \"\"\"\n Create image fixture of shape NFHWC and NCFHW.\n \"\"\"\n channels_first = request.param\n test_input = np.ones((2, 3, 32, 32))\n if not channels_first:\n test_input = np.transpose(test_input, (0, 2, 3, 1))\n test_mean = [0] * 3\n test_std = [1] * 3\n test_output = test_input.copy()\n return test_input, test_output, test_mean, test_std\n\n\n@pytest.mark.framework_agnostic\ndef test_broadcastable_mean_std(art_warning):\n try:\n mean, std = broadcastable_mean_std(np.ones((1, 3, 20, 20)), np.ones(3), np.ones(3))\n assert mean.shape == std.shape == (1, 3, 1, 1)\n\n mean, std = broadcastable_mean_std(np.ones((1, 3, 20, 20)), np.ones((1, 3, 1, 1)), np.ones((1, 3, 1, 1)))\n assert mean.shape == std.shape == (1, 3, 1, 1)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_standardisation_mean_std(art_warning, image_batch):\n try:\n x, x_expected, mean, std = image_batch\n standard = StandardisationMeanStd(mean=mean, std=std)\n\n x_preprocessed, _ = standard(x=x, y=None)\n np.testing.assert_array_equal(x_preprocessed, x_expected)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_standardisation_mean_std_pytorch(art_warning, image_batch):\n try:\n x, x_expected, mean, std = image_batch\n standard = StandardisationMeanStdPyTorch(mean=mean, std=std)\n\n x_preprocessed, _ = standard(x=x, y=None)\n np.testing.assert_array_equal(x_preprocessed, x_expected)\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_standardisation_mean_std_tensorflow_v2(art_warning, image_batch):\n try:\n x, x_expected, mean, std = image_batch\n standard = StandardisationMeanStdTensorFlow(mean=mean, std=std)\n\n x_preprocessed, _ = standard(x=x, y=None)\n np.testing.assert_array_equal(x_preprocessed, x_expected)\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/audio/test_l_filter.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_audio_filter[False]\": [\n [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n [\n -0.000103762934,\n -0.000303964334,\n -0.000158207942,\n 0.000130204164,\n 0.000140768461,\n 4.04138154e-06,\n -0.000100820056,\n -6.26970723e-05,\n 2.87954499e-05,\n 5.93094592e-05,\n 2.27166784e-05,\n -1.3271565e-05,\n 4.35872198e-06,\n 4.02366786e-05,\n -9.17821035e-06,\n -4.9518876e-05,\n -2.67004216e-05,\n 5.93773893e-06,\n 2.11202023e-05,\n 6.83116525e-07,\n -2.4038749e-05,\n -1.23528616e-05,\n 1.12255238e-05,\n 2.44062358e-05,\n 1.74439847e-05,\n 2.00138729e-05\n ],\n [\n -1.8311106e-05,\n -4.6998506e-05,\n -2.0142215e-06,\n 5.8247628e-05,\n 4.7149268e-05,\n -3.0724209e-06,\n -4.3240292e-05,\n -2.5821355e-05,\n 1.9835043e-05,\n 3.8318274e-05,\n 4.0220264e-05,\n 4.3689197e-05,\n 3.8430262e-05,\n 2.1895425e-05,\n -6.7816509e-05,\n -0.00020132199,\n -9.0355054e-05,\n 0.00012097351,\n 0.00013216017,\n 2.0204312e-05,\n -7.1746785e-05,\n -5.7854388e-05,\n 7.0203455e-06,\n 4.8404847e-05,\n 3.145442e-05,\n 1.9199029e-05,\n 3.6422553e-05,\n 4.820884e-05,\n 3.1506053e-05,\n -6.8804489e-05\n ],\n [\n -8.23999726e-05,\n -0.000226752527,\n -6.55232361e-05,\n 0.000189938044,\n 0.000164608602,\n 4.64848699e-06,\n -8.00448834e-05,\n 5.36849875e-05,\n 0.000260933652,\n 0.000154619047,\n -9.38530357e-05,\n -0.000113907212,\n -3.98988004e-06,\n -1.33394606e-05,\n -0.00027235056,\n -0.000321181869,\n 3.67591638e-05,\n 0.000284018839,\n 0.000162287542,\n -6.42566083e-05,\n -0.000110090376,\n 7.82894858e-05,\n 0.000295048871,\n 0.000155844362,\n -0.000114051938,\n -0.000125901017,\n 2.77904201e-06,\n -2.33865194e-06\n ]\n ],\n \"test_audio_filter[True]\": [\n [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n [\n -0.00010376293,\n -0.00031434064,\n -0.00021973327,\n -1.8311101e-05,\n -1.5259249e-05,\n -6.1036999e-06,\n -6.1037099e-06,\n -1.525928e-05,\n -6.1037199e-06,\n 3.0518599e-06,\n 1.220743e-05,\n 1.8311121e-05,\n 3.3570352e-05,\n 4.5777753e-05,\n -9.1555521e-06,\n -3.6622205e-05,\n -1.8311101e-05,\n -1.5259249e-05,\n -6.1036999e-06,\n -6.1037099e-06,\n -1.525928e-05,\n -6.1037199e-06,\n 3.0518599e-06,\n 1.220743e-05,\n 1.8311121e-05,\n 3.3570352e-05\n ],\n [\n -1.8311106e-05,\n -4.8829617e-05,\n -1.2207404e-05,\n 3.6622212e-05,\n 3.3570363e-05,\n 1.8311106e-05,\n -6.1037017e-06,\n -1.2207403e-05,\n 3.0518509e-06,\n 1.5259255e-05,\n 3.9674062e-05,\n 6.7140718e-05,\n 7.0192567e-05,\n 5.4933316e-05,\n -3.6622212e-05,\n -0.00018616291,\n -0.00012207404,\n 2.4414809e-05,\n 3.6622212e-05,\n 3.3570363e-05,\n 1.8311106e-05,\n -6.1037017e-06,\n -1.2207403e-05,\n 3.0518509e-06,\n 1.5259255e-05,\n 3.9674062e-05,\n 6.7140718e-05,\n 7.0192567e-05,\n 5.4933316e-05,\n -3.6622212e-05\n ],\n [\n -8.2399973e-05,\n -0.00023499252,\n -0.00011291848,\n 8.239998e-05,\n 7.3244424e-05,\n 5.1881467e-05,\n 4.5777761e-05,\n 0.00011291848,\n 0.00024414808,\n 0.00016479995,\n 2.1362957e-05,\n 2.7466658e-05,\n 1.8311106e-05,\n -8.5451829e-05,\n -0.00032044435,\n -0.00035401472,\n -8.2399973e-05,\n 8.239998e-05,\n 7.3244424e-05,\n 5.1881467e-05,\n 4.5777761e-05,\n 0.00011291848,\n 0.00024414808,\n 0.00016479995,\n 2.1362957e-05,\n 2.7466658e-05,\n 1.8311106e-05,\n -8.5451829e-05\n ]\n ],\n \"test_estimate_gradient[False]\": [\n [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n [\n -0.000103762934,\n -0.000303964334,\n -0.000158207942,\n 0.000130204164,\n 0.000140768461,\n 4.04138154e-06,\n -0.000100820056,\n -6.26970723e-05,\n 2.87954499e-05,\n 5.93094592e-05,\n 2.27166784e-05,\n -1.3271565e-05,\n 4.35872198e-06,\n 4.02366786e-05,\n -9.17821035e-06,\n -4.9518876e-05,\n -2.67004216e-05,\n 5.93773893e-06,\n 2.11202023e-05,\n 6.83116525e-07,\n -2.4038749e-05,\n -1.23528616e-05,\n 1.12255238e-05,\n 2.44062358e-05,\n 1.74439847e-05,\n 2.00138729e-05\n ],\n [\n -1.8311106e-05,\n -4.6998506e-05,\n -2.0142215e-06,\n 5.8247628e-05,\n 4.7149268e-05,\n -3.0724209e-06,\n -4.3240292e-05,\n -2.5821355e-05,\n 1.9835043e-05,\n 3.8318274e-05,\n 4.0220264e-05,\n 4.3689197e-05,\n 3.8430262e-05,\n 2.1895425e-05,\n -6.7816509e-05,\n -0.00020132199,\n -9.0355054e-05,\n 0.00012097351,\n 0.00013216017,\n 2.0204312e-05,\n -7.1746785e-05,\n -5.7854388e-05,\n 7.0203455e-06,\n 4.8404847e-05,\n 3.145442e-05,\n 1.9199029e-05,\n 3.6422553e-05,\n 4.820884e-05,\n 3.1506053e-05,\n -6.8804489e-05\n ],\n [\n -8.23999726e-05,\n -0.000226752527,\n -6.55232361e-05,\n 0.000189938044,\n 0.000164608602,\n 4.64848699e-06,\n -8.00448834e-05,\n 5.36849875e-05,\n 0.000260933652,\n 0.000154619047,\n -9.38530357e-05,\n -0.000113907212,\n -3.98988004e-06,\n -1.33394606e-05,\n -0.00027235056,\n -0.000321181869,\n 3.67591638e-05,\n 0.000284018839,\n 0.000162287542,\n -6.42566083e-05,\n -0.000110090376,\n 7.82894858e-05,\n 0.000295048871,\n 0.000155844362,\n -0.000114051938,\n -0.000125901017,\n 2.77904201e-06,\n -2.33865194e-06\n ],\n [\n -1.03762934e-04,\n -3.03964334e-04,\n -1.58207942e-04,\n 1.30204164e-04,\n 1.40768461e-04,\n 4.04138154e-06,\n -1.00820056e-04,\n -6.26970723e-05,\n 2.87954499e-05,\n 5.93094592e-05,\n 2.27166784e-05,\n -1.32715650e-05,\n 4.35872198e-06,\n 4.02366786e-05,\n -9.17821035e-06,\n -4.95188760e-05,\n -2.67004216e-05,\n 5.93773893e-06,\n 2.11202023e-05,\n 6.83116525e-07,\n -2.40387490e-05,\n -1.23528616e-05,\n 1.12255238e-05,\n 2.44062358e-05,\n 1.74439847e-05,\n 2.00138729e-05\n ],\n [\n -1.8311106e-05,\n -4.6998506e-05,\n -2.0142215e-06,\n 5.8247628e-05,\n 4.7149268e-05,\n -3.0724209e-06,\n -4.3240292e-05,\n -2.5821355e-05,\n 1.9835043e-05,\n 3.8318274e-05,\n 4.0220264e-05,\n 4.3689197e-05,\n 3.8430262e-05,\n 2.1895425e-05,\n -6.7816509e-05,\n -2.0132199e-04,\n -9.0355054e-05,\n 1.2097351e-04,\n 1.3216017e-04,\n 2.0204312e-05,\n -7.1746785e-05,\n -5.7854388e-05,\n 7.0203455e-06,\n 4.8404847e-05,\n 3.1454420e-05,\n 1.9199029e-05,\n 3.6422553e-05,\n 4.8208840e-05,\n 3.1506053e-05,\n -6.8804489e-05\n ],\n [\n -8.23999726e-05,\n -0.000226752527,\n -6.55232361e-05,\n 0.000189938044,\n 0.000164608602,\n 4.64848699e-06,\n -8.00448834e-05,\n 5.36849875e-05,\n 0.000260933652,\n 0.000154619047,\n -9.38530357e-05,\n -0.000113907212,\n -3.98988004e-06,\n -1.33394606e-05,\n -0.00027235056,\n -0.000321181869,\n 3.67591638e-05,\n 0.000284018839,\n 0.000162287542,\n -6.42566083e-05,\n -0.000110090376,\n 7.82894858e-05,\n 0.000295048871,\n 0.000155844362,\n -0.000114051938,\n -0.000125901017,\n 2.77904201e-06,\n -2.33865194e-06\n ]\n ],\n \"test_estimate_gradient[True]\": [\n [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n [\n -0.00010376293,\n -0.00031434064,\n -0.00021973327,\n -1.8311101e-05,\n -1.5259249e-05,\n -6.1036999e-06,\n -6.1037099e-06,\n -1.525928e-05,\n -6.1037199e-06,\n 3.0518599e-06,\n 1.220743e-05,\n 1.8311121e-05,\n 3.3570352e-05,\n 4.5777753e-05,\n -9.1555521e-06,\n -3.6622205e-05,\n -1.8311101e-05,\n -1.5259249e-05,\n -6.1036999e-06,\n -6.1037099e-06,\n -1.525928e-05,\n -6.1037199e-06,\n 3.0518599e-06,\n 1.220743e-05,\n 1.8311121e-05,\n 3.3570352e-05\n ],\n [\n -1.8311106e-05,\n -4.8829617e-05,\n -1.2207404e-05,\n 3.6622212e-05,\n 3.3570363e-05,\n 1.8311106e-05,\n -6.1037017e-06,\n -1.2207403e-05,\n 3.0518509e-06,\n 1.5259255e-05,\n 3.9674062e-05,\n 6.7140718e-05,\n 7.0192567e-05,\n 5.4933316e-05,\n -3.6622212e-05,\n -0.00018616291,\n -0.00012207404,\n 2.4414809e-05,\n 3.6622212e-05,\n 3.3570363e-05,\n 1.8311106e-05,\n -6.1037017e-06,\n -1.2207403e-05,\n 3.0518509e-06,\n 1.5259255e-05,\n 3.9674062e-05,\n 6.7140718e-05,\n 7.0192567e-05,\n 5.4933316e-05,\n -3.6622212e-05\n ],\n [\n -8.2399973e-05,\n -0.00023499252,\n -0.00011291848,\n 8.239998e-05,\n 7.3244424e-05,\n 5.1881467e-05,\n 4.5777761e-05,\n 0.00011291848,\n 0.00024414808,\n 0.00016479995,\n 2.1362957e-05,\n 2.7466658e-05,\n 1.8311106e-05,\n -8.5451829e-05,\n -0.00032044435,\n -0.00035401472,\n -8.2399973e-05,\n 8.239998e-05,\n 7.3244424e-05,\n 5.1881467e-05,\n 4.5777761e-05,\n 0.00011291848,\n 0.00024414808,\n 0.00016479995,\n 2.1362957e-05,\n 2.7466658e-05,\n 1.8311106e-05,\n -8.5451829e-05\n ],\n [\n -4.76088745e-05,\n -7.04977592e-05,\n -2.28888827e-05,\n -3.05184798e-06,\n 9.15562124e-07,\n 9.15560024e-07,\n -3.66222703e-06,\n -5.49334405e-06,\n -4.88296728e-06,\n -5.79851060e-06,\n -7.62961871e-06,\n 5.79851771e-06,\n 2.07525823e-05,\n 1.00711057e-05,\n -3.35703636e-06,\n -4.57777589e-06,\n -3.05184798e-06,\n 9.15562124e-07,\n 9.15560024e-07,\n -3.66222703e-06,\n -5.49334405e-06,\n -4.88296728e-06,\n -5.79851060e-06,\n 1.52593202e-06,\n 8.54518263e-06,\n 3.35703525e-06\n ],\n [\n -1.77007363e-05,\n -1.77007366e-05,\n -9.15555514e-07,\n 9.76592369e-06,\n 1.00711084e-05,\n 1.22074040e-06,\n -6.40888696e-06,\n -1.00711082e-05,\n -1.40385139e-05,\n -1.12918475e-05,\n -6.10370109e-07,\n 2.25836963e-05,\n 5.89007240e-05,\n 4.11999888e-05,\n -3.35703615e-05,\n -5.27970231e-05,\n -1.77007363e-05,\n 2.74666584e-06,\n 9.76592369e-06,\n 1.00711084e-05,\n 1.22074040e-06,\n -6.40888696e-06,\n -1.00711082e-05,\n -1.40385139e-05,\n -1.12918475e-05,\n -6.10370109e-07,\n 2.25836963e-05,\n 2.16681414e-05,\n -1.83111083e-06,\n -3.66222125e-06\n ],\n [\n -6.04266502e-05,\n -6.89718318e-05,\n -1.25125880e-05,\n 8.54518403e-06,\n -9.46073644e-06,\n -4.57777658e-05,\n -3.02133264e-05,\n 3.93688782e-05,\n 4.97451714e-05,\n 1.43436996e-05,\n 2.28888828e-05,\n 7.90429411e-05,\n 8.75881251e-05,\n -2.07525866e-05,\n -1.11087379e-04,\n -7.47703505e-05,\n -9.46073724e-06,\n 8.54518403e-06,\n -9.46073644e-06,\n -4.57777658e-05,\n -3.02133264e-05,\n 3.93688782e-05,\n 4.97451714e-05,\n 1.43436996e-05,\n 2.28888828e-05,\n 1.49540701e-05,\n -1.52592554e-05,\n -8.54518303e-06\n ]\n ]\n}\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/audio/test_l_filter.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.preprocessing.audio import LFilter\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"fir_filter\", [False, True])\ndef test_audio_filter(fir_filter, art_warning, expected_values):\n try:\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[0]\n x2 = expected_data[1]\n x3 = expected_data[2]\n result_0 = expected_data[3]\n result_1 = expected_data[4]\n result_2 = expected_data[5]\n\n # Create signal data\n x = np.array([np.array(x1 * 2), np.array(x2 * 2), np.array(x3 * 2)], dtype=object)\n\n # Filter params\n numerator_coef = np.array([0.1, 0.2, -0.1, -0.2])\n\n if fir_filter:\n denominator_coef = np.array([1.0])\n else:\n denominator_coef = np.array([1.0, 0.1, 0.3, 0.4])\n\n # Create filter\n audio_filter = LFilter(numerator_coef=numerator_coef, denominator_coef=denominator_coef)\n\n # Apply filter\n result = audio_filter(x)\n\n # Test\n assert result[1] is None\n np.testing.assert_array_almost_equal(result_0, result[0][0], decimal=0)\n np.testing.assert_array_almost_equal(result_1, result[0][1], decimal=0)\n np.testing.assert_array_almost_equal(result_2, result[0][2], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_default(art_warning):\n try:\n # Small data for testing\n x = np.array([[0.37, 0.68, 0.63, 0.48, 0.48, 0.18, 0.19]])\n\n # Create filter\n audio_filter = LFilter()\n\n # Apply filter\n result = audio_filter(x)\n\n # Test\n assert result[1] is None\n np.testing.assert_array_almost_equal(x, result[0], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test__clip_Values(art_warning):\n try:\n # Small data for testing\n x = np.array([[0.37, 0.68, 0.63, 0.48, 0.48, 0.18, 0.19]])\n\n # Create filter\n audio_filter = LFilter(clip_values=(0, 1))\n\n # Apply filter\n result = audio_filter(x)\n\n # Test\n assert result[1] is None\n np.testing.assert_array_almost_equal(x, result[0], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_triple_clip_values_error(art_warning):\n try:\n exc_msg = \"`clip_values` should be a tuple of 2 floats containing the allowed data range.\"\n with pytest.raises(ValueError, match=exc_msg):\n LFilter(\n numerator_coef=np.array([0.1, 0.2, 0.3]),\n denominator_coef=np.array([0.1, 0.2, 0.3]),\n clip_values=(0, 1, 2),\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_relation_clip_values_error(art_warning):\n try:\n exc_msg = \"Invalid `clip_values`: min >= max.\"\n with pytest.raises(ValueError, match=exc_msg):\n LFilter(\n numerator_coef=np.array([0.1, 0.2, 0.3]), denominator_coef=np.array([0.1, 0.2, 0.3]), clip_values=(1, 0)\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"fir_filter\", [False, True])\ndef test_estimate_gradient(fir_filter, art_warning, expected_values):\n\n try:\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[0]\n x2 = expected_data[1]\n x3 = expected_data[2]\n\n grad0 = expected_data[3]\n grad1 = expected_data[4]\n grad2 = expected_data[5]\n\n result0 = expected_data[6]\n result1 = expected_data[7]\n result2 = expected_data[8]\n\n # Create signal data\n x = np.array([np.array(x1 * 2), np.array(x2 * 2), np.array(x3 * 2)], dtype=object)\n\n # Create input gradient\n grad = np.array([np.array(grad0), np.array(grad1), np.array(grad2)], dtype=object)\n\n # Filter params\n numerator_coef = np.array([0.1, 0.2, -0.1, -0.2])\n\n if fir_filter:\n denominator_coef = np.array([1.0])\n else:\n denominator_coef = np.array([1.0, 0.1, 0.3, 0.4])\n\n # Create filter\n audio_filter = LFilter(numerator_coef=numerator_coef, denominator_coef=denominator_coef)\n\n # Estimate gradient\n estimated_grad = audio_filter.estimate_gradient(x, grad=grad)\n\n # Test\n assert estimated_grad.shape == x.shape\n np.testing.assert_array_almost_equal(result0, estimated_grad[0], decimal=0)\n np.testing.assert_array_almost_equal(result1, estimated_grad[1], decimal=0)\n np.testing.assert_array_almost_equal(result2, estimated_grad[2], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params(art_warning):\n\n try:\n\n with pytest.raises(ValueError):\n _ = LFilter(numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]), denominator_coef=[0.0, 0.1, 0.3, 0.4])\n\n with pytest.raises(ValueError):\n _ = LFilter(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]), denominator_coef=np.array([0.0, 0.1, 0.3, 0.4])\n )\n\n with pytest.raises(ValueError):\n _ = LFilter(numerator_coef=[0.1, 0.2, -0.1, -0.2], denominator_coef=np.array([1.0, 0.1, 0.3, 0.4]))\n\n with pytest.raises(ValueError):\n _ = LFilter(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]),\n denominator_coef=np.array([1.0, 0.1, 0.3, 0.4]),\n axis=1.0,\n )\n\n with pytest.raises(ValueError):\n _ = LFilter(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]),\n denominator_coef=np.array([1.0, 0.1, 0.3, 0.4]),\n initial_cond=1.0,\n )\n\n with pytest.raises(ValueError):\n _ = LFilter(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]),\n denominator_coef=np.array([1.0, 0.1, 0.3, 0.4]),\n verbose=\"True\",\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/audio/test_l_filter_pytorch.json\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n{\n \"test_audio_filter[False]\": [\n [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n [\n -0.000103762934,\n -0.000303964334,\n -0.000158207942,\n 0.000130204164,\n 0.000140768461,\n 4.04138154e-06,\n -0.000100820056,\n -6.26970723e-05,\n 2.87954499e-05,\n 5.93094592e-05,\n 2.27166784e-05,\n -1.3271565e-05,\n 4.35872198e-06,\n 4.02366786e-05,\n -9.17821035e-06,\n -4.9518876e-05,\n -2.67004216e-05,\n 5.93773893e-06,\n 2.11202023e-05,\n 6.83116525e-07,\n -2.4038749e-05,\n -1.23528616e-05,\n 1.12255238e-05,\n 2.44062358e-05,\n 1.74439847e-05,\n 2.00138729e-05\n ],\n [\n -1.8311106e-05,\n -4.6998506e-05,\n -2.0142215e-06,\n 5.8247628e-05,\n 4.7149268e-05,\n -3.0724209e-06,\n -4.3240292e-05,\n -2.5821355e-05,\n 1.9835043e-05,\n 3.8318274e-05,\n 4.0220264e-05,\n 4.3689197e-05,\n 3.8430262e-05,\n 2.1895425e-05,\n -6.7816509e-05,\n -0.00020132199,\n -9.0355054e-05,\n 0.00012097351,\n 0.00013216017,\n 2.0204312e-05,\n -7.1746785e-05,\n -5.7854388e-05,\n 7.0203455e-06,\n 4.8404847e-05,\n 3.145442e-05,\n 1.9199029e-05,\n 3.6422553e-05,\n 4.820884e-05,\n 3.1506053e-05,\n -6.8804489e-05\n ],\n [\n -8.23999726e-05,\n -0.000226752527,\n -6.55232361e-05,\n 0.000189938044,\n 0.000164608602,\n 4.64848699e-06,\n -8.00448834e-05,\n 5.36849875e-05,\n 0.000260933652,\n 0.000154619047,\n -9.38530357e-05,\n -0.000113907212,\n -3.98988004e-06,\n -1.33394606e-05,\n -0.00027235056,\n -0.000321181869,\n 3.67591638e-05,\n 0.000284018839,\n 0.000162287542,\n -6.42566083e-05,\n -0.000110090376,\n 7.82894858e-05,\n 0.000295048871,\n 0.000155844362,\n -0.000114051938,\n -0.000125901017,\n 2.77904201e-06,\n -2.33865194e-06\n ]\n ],\n \"test_audio_filter[True]\": [\n [\n -0.0010376293,\n -0.0010681478,\n -0.0010986663,\n -0.0011291848,\n -0.0011291848,\n -0.0011291848,\n -0.0011902219,\n -0.0011597034,\n -0.0011902219,\n -0.0011291848,\n -0.0011291848,\n -0.0010681478,\n -0.00091555528\n ],\n [\n -0.00018311106,\n -0.00012207404,\n -6.1037019e-05,\n 0.0,\n 3.0518509e-05,\n 0.0,\n -3.0518509e-05,\n 0.0,\n 0.0,\n 9.1555528e-05,\n 0.00021362957,\n 0.0003357036,\n 0.00042725913,\n 0.00045777764,\n -0.00018311106\n ],\n [\n -0.00082399976,\n -0.00070192572,\n -0.00054933317,\n -0.00042725913,\n -0.00036622211,\n -0.00027466659,\n -0.00021362957,\n 0.00054933317,\n 0.00057985168,\n 0.00061037019,\n 0.00067140721,\n 0.00070192572,\n 0.00067140721,\n -0.00015259255\n ],\n [\n -0.00010376293,\n -0.00031434064,\n -0.00021973327,\n -1.8311101e-05,\n -1.5259249e-05,\n -6.1036999e-06,\n -6.1037099e-06,\n -1.525928e-05,\n -6.1037199e-06,\n 3.0518599e-06,\n 1.220743e-05,\n 1.8311121e-05,\n 3.3570352e-05,\n 4.5777753e-05,\n -9.1555521e-06,\n -3.6622205e-05,\n -1.8311101e-05,\n -1.5259249e-05,\n -6.1036999e-06,\n -6.1037099e-06,\n -1.525928e-05,\n -6.1037199e-06,\n 3.0518599e-06,\n 1.220743e-05,\n 1.8311121e-05,\n 3.3570352e-05\n ],\n [\n -1.8311106e-05,\n -4.8829617e-05,\n -1.2207404e-05,\n 3.6622212e-05,\n 3.3570363e-05,\n 1.8311106e-05,\n -6.1037017e-06,\n -1.2207403e-05,\n 3.0518509e-06,\n 1.5259255e-05,\n 3.9674062e-05,\n 6.7140718e-05,\n 7.0192567e-05,\n 5.4933316e-05,\n -3.6622212e-05,\n -0.00018616291,\n -0.00012207404,\n 2.4414809e-05,\n 3.6622212e-05,\n 3.3570363e-05,\n 1.8311106e-05,\n -6.1037017e-06,\n -1.2207403e-05,\n 3.0518509e-06,\n 1.5259255e-05,\n 3.9674062e-05,\n 6.7140718e-05,\n 7.0192567e-05,\n 5.4933316e-05,\n -3.6622212e-05\n ],\n [\n -8.2399973e-05,\n -0.00023499252,\n -0.00011291848,\n 8.239998e-05,\n 7.3244424e-05,\n 5.1881467e-05,\n 4.5777761e-05,\n 0.00011291848,\n 0.00024414808,\n 0.00016479995,\n 2.1362957e-05,\n 2.7466658e-05,\n 1.8311106e-05,\n -8.5451829e-05,\n -0.00032044435,\n -0.00035401472,\n -8.2399973e-05,\n 8.239998e-05,\n 7.3244424e-05,\n 5.1881467e-05,\n 4.5777761e-05,\n 0.00011291848,\n 0.00024414808,\n 0.00016479995,\n 2.1362957e-05,\n 2.7466658e-05,\n 1.8311106e-05,\n -8.5451829e-05\n ]\n ]\n}\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/audio/test_l_filter_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.preprocessing.audio import LFilterPyTorch\nfrom art.config import ART_NUMPY_DTYPE\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.skip_module(\"torchaudio\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\n@pytest.mark.parametrize(\"fir_filter\", [False, True])\ndef test_audio_filter(fir_filter, art_warning, expected_values):\n try:\n # Load data for testing\n expected_data = expected_values()\n\n x1 = expected_data[0]\n x2 = expected_data[1]\n x3 = expected_data[2]\n result_0 = expected_data[3]\n result_1 = expected_data[4]\n result_2 = expected_data[5]\n\n # Create signal data\n x = np.array(\n [\n np.array(x1 * 2, dtype=ART_NUMPY_DTYPE),\n np.array(x2 * 2, dtype=ART_NUMPY_DTYPE),\n np.array(x3 * 2, dtype=ART_NUMPY_DTYPE),\n ],\n dtype=object,\n )\n\n # Filter params\n numerator_coef = np.array([0.1, 0.2, -0.1, -0.2], dtype=ART_NUMPY_DTYPE)\n\n if fir_filter:\n denominator_coef = np.array([1.0, 0.0, 0.0, 0.0], dtype=ART_NUMPY_DTYPE)\n else:\n denominator_coef = np.array([1.0, 0.1, 0.3, 0.4], dtype=ART_NUMPY_DTYPE)\n\n # Create filter\n audio_filter = LFilterPyTorch(numerator_coef=numerator_coef, denominator_coef=denominator_coef)\n\n # Apply filter\n result = audio_filter(x)\n\n # Test\n assert result[1] is None\n np.testing.assert_array_almost_equal(result_0, result[0][0], decimal=0)\n np.testing.assert_array_almost_equal(result_1, result[0][1], decimal=0)\n np.testing.assert_array_almost_equal(result_2, result[0][2], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"torchaudio\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_default(art_warning):\n try:\n # Small data for testing\n x = np.array([[0.37, 0.68, 0.63, 0.48, 0.48, 0.18, 0.19]], dtype=ART_NUMPY_DTYPE)\n\n # Create filter\n audio_filter = LFilterPyTorch()\n\n # Apply filter\n result = audio_filter(x)\n\n # Test\n assert result[1] is None\n np.testing.assert_array_almost_equal(x, result[0], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"torchaudio\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_clip_values(art_warning):\n try:\n # Small data for testing\n x = np.array([[0.37, 0.68, 0.63, 0.48, 0.48, 0.18, 0.19]], dtype=ART_NUMPY_DTYPE)\n\n # Create filter\n audio_filter = LFilterPyTorch(clip_values=(0, 1))\n\n # Apply filter\n result = audio_filter(x)\n\n # Test\n assert result[1] is None\n np.testing.assert_array_almost_equal(x, result[0], decimal=0)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"torchaudio\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_triple_clip_values_error(art_warning):\n try:\n exc_msg = \"`clip_values` should be a tuple of 2 floats containing the allowed data range.\"\n with pytest.raises(ValueError, match=exc_msg):\n LFilterPyTorch(\n numerator_coef=np.array([0.1, 0.2, 0.3]),\n denominator_coef=np.array([0.1, 0.2, 0.3]),\n clip_values=(0, 1, 2),\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_module(\"torchaudio\")\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_relation_clip_values_error(art_warning):\n try:\n exc_msg = \"Invalid `clip_values`: min >= max.\"\n with pytest.raises(ValueError, match=exc_msg):\n LFilterPyTorch(\n numerator_coef=np.array([0.1, 0.2, 0.3]), denominator_coef=np.array([0.1, 0.2, 0.3]), clip_values=(1, 0)\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.skip_framework(\"tensorflow\", \"keras\", \"kerastf\", \"non_dl_frameworks\")\ndef test_check_params(art_warning):\n\n try:\n\n with pytest.raises(ValueError):\n _ = LFilterPyTorch(numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]), denominator_coef=[0.0, 0.1, 0.3, 0.4])\n\n with pytest.raises(ValueError):\n _ = LFilterPyTorch(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]), denominator_coef=np.array([0.0, 0.1, 0.3, 0.4])\n )\n\n with pytest.raises(ValueError):\n _ = LFilterPyTorch(numerator_coef=[0.1, 0.2, -0.1, -0.2], denominator_coef=np.array([1.0, 0.1, 0.3, 0.4]))\n\n with pytest.raises(ValueError):\n _ = LFilterPyTorch(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]),\n denominator_coef=np.array([1.0, 0.1, 0.3, 0.4, 0.2]),\n )\n\n with pytest.raises(ValueError):\n _ = LFilterPyTorch(\n numerator_coef=np.array([0.1, 0.2, -0.1, -0.2]),\n denominator_coef=np.array([1.0, 0.1, 0.3, 0.4]),\n verbose=\"True\",\n )\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/expectation_over_transformation/test_image_rotation.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nimport torch\n\nfrom art.preprocessing.expectation_over_transformation.image_rotation.tensorflow import (\n EoTImageRotationTensorFlow,\n rotate_images,\n)\nfrom art.preprocessing.expectation_over_transformation.image_rotation.pytorch import EoTImageRotationPyTorch\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_image_rotation_classification_tensorflow_v2(art_warning, fix_get_mnist_subset):\n try:\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n nb_samples = 3\n\n eot = EoTImageRotationTensorFlow(\n nb_samples=nb_samples, angles=(45.0, 45.0), clip_values=(0.0, 1.0), label_type=\"classification\"\n )\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n from matplotlib import pyplot as plt\n\n plt.matshow(x_eot.numpy()[0, :, :, 0])\n plt.show()\n\n x_eot_expected = np.array(\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.07058824,\n 0.3137255,\n 0.6117647,\n 0.05490196,\n 0.0,\n 0.54509807,\n 0.04313726,\n 0.13725491,\n 0.31764707,\n 0.9411765,\n 0.1764706,\n 0.0627451,\n 0.3647059,\n 0.0,\n 0.99215686,\n 0.99215686,\n 0.98039216,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_image_rotation_classification_tensorflow_v2_rotate_images(art_warning):\n try:\n # Create a test image: batch of 1, shape 5x5 with a simple pattern\n x = np.zeros((1, 5, 5, 1), dtype=np.float32)\n x[0, 2, 2, 0] = 1.0 # Center pixel set to 1\n\n angles = tf.constant([np.pi / 2], dtype=tf.float32) # 90 degrees rotation\n\n # Rotate using custom function\n rotated_custom = rotate_images(x, angles, interpolation=\"NEAREST\")\n assert rotated_custom[0, 2, 2, 0] == 1.0\n\n # Create a test image: batch of 1, shape 5x5 with a simple pattern\n x = np.zeros((1, 5, 5, 1), dtype=np.float32)\n x[0, 0, 0, 0] = 1.0 # Center pixel set to 1\n\n # Rotate using custom function\n rotated_custom = rotate_images(x, angles, interpolation=\"NEAREST\")\n assert rotated_custom[0, 4, 0, 0] == 1.0\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_image_rotation_classification_pytorch(art_warning, fix_get_mnist_subset):\n try:\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n x_train_mnist = torch.from_numpy(x_train_mnist)\n y_train_mnist = torch.from_numpy(y_train_mnist)\n\n nb_samples = 3\n\n eot = EoTImageRotationPyTorch(\n nb_samples=nb_samples, angles=(45.0, 45.0), clip_values=(0.0, 1.0), label_type=\"classification\"\n )\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.07058824,\n 0.3137255,\n 0.6117647,\n 0.05490196,\n 0.0,\n 0.54509807,\n 0.04313726,\n 0.13725491,\n 0.31764707,\n 0.9411765,\n 0.1764706,\n 0.0627451,\n 0.3647059,\n 0.0,\n 0.99215686,\n 0.99215686,\n 0.98039216,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 0, 14, :], x_eot_expected)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_image_rotation_object_detection_pytorch(art_warning, fix_get_mnist_subset):\n try:\n x_train_mnist, _, _, _ = fix_get_mnist_subset\n\n x_train_mnist = torch.from_numpy(x_train_mnist[0:2])\n\n y_od = [\n {\n \"boxes\": torch.from_numpy(np.array([[1, 1, 3, 3]])),\n \"labels\": torch.from_numpy(np.ones((1,))),\n \"scores\": torch.from_numpy(np.ones((1,))),\n },\n {\n \"boxes\": torch.from_numpy(np.array([[15, 15, 18, 20]])),\n \"labels\": torch.from_numpy(np.ones((1,))),\n \"scores\": torch.from_numpy(np.ones((1,))),\n },\n ]\n\n nb_samples = 3\n\n eot = EoTImageRotationPyTorch(\n nb_samples=nb_samples, angles=[90.0], clip_values=(0.0, 1.0), label_type=\"object_detection\"\n )\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_od)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.07058824,\n 0.99215686,\n 0.99215686,\n 0.99215686,\n 0.8039216,\n 0.3529412,\n 0.74509805,\n 0.99215686,\n 0.94509804,\n 0.31764707,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.5803922,\n 0.99215686,\n 0.99215686,\n 0.7647059,\n 0.04313726,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 0, 14, :], x_eot_expected)\n np.testing.assert_almost_equal(y_eot[0][\"boxes\"], np.array([[1, 25, 3, 27]]))\n np.testing.assert_almost_equal(y_eot[nb_samples][\"boxes\"], np.array([[15, 10, 20, 13]]))\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/expectation_over_transformation/natural_corruptions/test_brightness.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_brightness_pytorch(art_warning, fix_get_mnist_subset):\n try:\n import torch\n from art.preprocessing.expectation_over_transformation.natural_corruptions.brightness.pytorch import (\n EoTBrightnessPyTorch,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n x_train_mnist = np.transpose(x_train_mnist, (0, 2, 3, 1)) # transpose to NHWC\n\n nb_samples = 3\n\n eot = EoTBrightnessPyTorch(nb_samples=nb_samples, delta=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=torch.from_numpy(x_train_mnist), y=torch.from_numpy(y_train_mnist))\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.5176471,\n 1.0,\n 1.0,\n 1.0,\n 0.6666667,\n 0.29803923,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_brightness_tensorflow_v2(art_warning, fix_get_mnist_subset):\n try:\n from art.preprocessing.expectation_over_transformation.natural_corruptions.brightness.tensorflow import (\n EoTBrightnessTensorFlow,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n nb_samples = 3\n\n eot = EoTBrightnessTensorFlow(nb_samples=nb_samples, delta=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.5176471,\n 1.0,\n 1.0,\n 1.0,\n 0.6666667,\n 0.29803923,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n 0.2,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/expectation_over_transformation/natural_corruptions/test_contrast.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_contrast_pytorch(art_warning, fix_get_mnist_subset):\n try:\n import torch\n from art.preprocessing.expectation_over_transformation.natural_corruptions.contrast.pytorch import (\n EoTContrastPyTorch,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n x_train_mnist = np.transpose(x_train_mnist, (0, 2, 3, 1)) # transpose to NHWC\n\n nb_samples = 3\n\n eot = EoTContrastPyTorch(nb_samples=nb_samples, contrast_factor=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=torch.from_numpy(x_train_mnist), y=torch.from_numpy(y_train_mnist))\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.17367348,\n 0.29837936,\n 0.30857542,\n 0.30857542,\n 0.20347738,\n 0.1297519,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n x_eot, y_eot = eot.forward(\n x=torch.from_numpy(np.repeat(x_train_mnist, repeats=3, axis=1)), y=torch.from_numpy(y_train_mnist)\n )\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n with pytest.raises(ValueError):\n _ = EoTContrastPyTorch(nb_samples=nb_samples, contrast_factor=(0.2, 0.2, 0.3), clip_values=(0.0, 1.0))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_contrast_tensorflow_v2(art_warning, fix_get_mnist_subset):\n try:\n from art.preprocessing.expectation_over_transformation.natural_corruptions.contrast.tensorflow import (\n EoTContrastTensorFlow,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n nb_samples = 3\n\n eot = EoTContrastTensorFlow(nb_samples=nb_samples, contrast_factor=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.17367348,\n 0.29837936,\n 0.30857542,\n 0.30857542,\n 0.20347738,\n 0.1297519,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n 0.11014406,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n x_eot, y_eot = eot.forward(x=np.repeat(x_train_mnist, repeats=3, axis=3), y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n with pytest.raises(ValueError):\n _ = EoTContrastTensorFlow(nb_samples=nb_samples, contrast_factor=(0.2, 0.2, 0.3), clip_values=(0.0, 1.0))\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/expectation_over_transformation/natural_corruptions/test_gaussian_noise.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_gaussian_noise_pytorch(art_warning, fix_get_mnist_subset):\n try:\n import torch\n from art.preprocessing.expectation_over_transformation.natural_corruptions.gaussian_noise.pytorch import (\n EoTGaussianNoisePyTorch,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n x_train_mnist = np.transpose(x_train_mnist, (0, 2, 3, 1)) # transpose to NHWC\n\n nb_samples = 3\n\n eot = EoTGaussianNoisePyTorch(nb_samples=nb_samples, std=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=torch.from_numpy(x_train_mnist), y=torch.from_numpy(y_train_mnist))\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_gaussian_noise_tensorflow_v2(art_warning, fix_get_mnist_subset):\n try:\n from art.preprocessing.expectation_over_transformation.natural_corruptions.gaussian_noise.tensorflow import (\n EoTGaussianNoiseTensorFlow,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n nb_samples = 3\n\n eot = EoTGaussianNoiseTensorFlow(nb_samples=nb_samples, std=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/expectation_over_transformation/natural_corruptions/test_shot_noise.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_shot_noise_pytorch(art_warning, fix_get_mnist_subset):\n try:\n import torch\n from art.preprocessing.expectation_over_transformation.natural_corruptions.shot_noise.pytorch import (\n EoTShotNoisePyTorch,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n x_train_mnist = np.transpose(x_train_mnist, (0, 2, 3, 1)) # transpose to NHWC\n\n nb_samples = 3\n\n eot = EoTShotNoisePyTorch(nb_samples=nb_samples, lam=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=torch.from_numpy(x_train_mnist), y=torch.from_numpy(y_train_mnist))\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_shot_noise_tensorflow_v2(art_warning, fix_get_mnist_subset):\n try:\n from art.preprocessing.expectation_over_transformation.natural_corruptions.shot_noise.tensorflow import (\n EoTShotNoiseTensorFlow,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n nb_samples = 3\n\n eot = EoTShotNoiseTensorFlow(nb_samples=nb_samples, lam=(0.2, 0.2), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/expectation_over_transformation/natural_corruptions/test_zoom_blur.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef fix_get_mnist_subset(get_mnist_dataset):\n (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = get_mnist_dataset\n n_train = 10\n n_test = 10\n yield x_train_mnist[:n_train], y_train_mnist[:n_train], x_test_mnist[:n_test], y_test_mnist[:n_test]\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_eot_zoom_blur_pytorch(art_warning, fix_get_mnist_subset):\n try:\n import torchvision\n\n if \"+\" in torchvision.__version__:\n torchvision_version = torchvision.__version__.split(\"+\")[0]\n else:\n torchvision_version = torchvision.__version__\n torchvision_version = list(map(int, torchvision_version.lower().split(\".\")))\n\n if torchvision_version[0] >= 0 and torchvision_version[1] >= 8:\n import torch\n from art.preprocessing.expectation_over_transformation.natural_corruptions.zoom_blur.pytorch import (\n EoTZoomBlurPyTorch,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n x_train_mnist = np.transpose(x_train_mnist, (0, 2, 3, 1)) # transpose to NHWC\n\n nb_samples = 3\n\n eot = EoTZoomBlurPyTorch(nb_samples=nb_samples, zoom=(1.5, 1.5), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=torch.from_numpy(x_train_mnist), y=torch.from_numpy(y_train_mnist))\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 9.3583600e-05,\n 6.7037535e-03,\n 7.0553131e-02,\n 4.1708022e-01,\n 8.4442711e-01,\n 9.2741704e-01,\n 8.8823336e-01,\n 6.6305310e-01,\n 3.1785199e-01,\n 1.1077325e-01,\n 2.7649008e-02,\n 4.9111363e-03,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_eot_zoom_blur_tensorflow_v2(art_warning, fix_get_mnist_subset):\n try:\n from art.preprocessing.expectation_over_transformation.natural_corruptions.zoom_blur.tensorflow import (\n EoTZoomBlurTensorFlow,\n )\n\n x_train_mnist, y_train_mnist, _, _ = fix_get_mnist_subset\n\n nb_samples = 3\n\n eot = EoTZoomBlurTensorFlow(nb_samples=nb_samples, zoom=(1.5, 1.5), clip_values=(0.0, 1.0))\n x_eot, y_eot = eot.forward(x=x_train_mnist, y=y_train_mnist)\n\n assert x_eot.shape[0] == nb_samples * x_train_mnist.shape[0]\n assert y_eot.shape[0] == nb_samples * y_train_mnist.shape[0]\n\n x_eot_expected = np.array(\n [\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 9.3583600e-05,\n 6.7037535e-03,\n 7.0553131e-02,\n 4.1708022e-01,\n 8.4442711e-01,\n 9.2741704e-01,\n 8.8823336e-01,\n 6.6305310e-01,\n 3.1785199e-01,\n 1.1077325e-01,\n 2.7649008e-02,\n 4.9111363e-03,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n 0.0000000e00,\n ]\n )\n\n np.testing.assert_almost_equal(x_eot.numpy()[0, 14, :, 0], x_eot_expected)\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/image/test_image_resize.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport cv2\nimport pytest\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.preprocessing.image import ImageResize, ImageResizePyTorch, ImageResizeTensorFlowV2\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef image_batch(channels_first, label_type):\n channels = 3\n height = 20\n width = 16\n\n if channels_first:\n data_shape = (2, channels, height, width)\n else:\n data_shape = (2, height, width, channels)\n x = (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n if label_type == \"classification\":\n y = np.arange(len(x))\n elif label_type == \"object_detection\":\n y = []\n for _ in range(len(x)):\n y_1, x_1 = np.random.uniform(0, (height / 2, width / 2))\n y_2, x_2 = np.random.uniform((y_1 + 3, x_1 + 3), (height, width))\n target_dict = {\n \"boxes\": np.array([[x_1, y_1, x_2, y_2]]),\n \"labels\": np.array([0]),\n }\n y.append(target_dict)\n else:\n y = None\n\n return x, y\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"height\", [16, 20, 24])\n@pytest.mark.parametrize(\"width\", [16, 20, 24])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"label_type\", [None, \"classification\", \"object_detection\"])\n@pytest.mark.parametrize(\"interpolation\", [cv2.INTER_LINEAR, cv2.INTER_AREA])\ndef test_resize_numpy(height, width, channels_first, label_type, interpolation, image_batch, art_warning):\n x, y = image_batch\n\n try:\n resize = ImageResize(\n height=height,\n width=width,\n channels_first=channels_first,\n label_type=label_type,\n interpolation=interpolation,\n )\n\n x_preprocess, y_preprocess = resize(x, y)\n\n if channels_first:\n assert x_preprocess.shape == (x.shape[0], x.shape[1], height, width)\n else:\n assert x_preprocess.shape == (x.shape[0], height, width, x.shape[3])\n\n if label_type == \"classification\":\n np.testing.assert_array_equal(y, y_preprocess)\n elif label_type == \"object_detection\":\n assert y[0][\"boxes\"].shape == y_preprocess[0][\"boxes\"].shape\n np.testing.assert_array_equal(y[0][\"labels\"], y_preprocess[0][\"labels\"])\n else:\n assert y is None\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"height\", [16, 20, 24])\n@pytest.mark.parametrize(\"width\", [16, 20, 24])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"label_type\", [None, \"classification\", \"object_detection\"])\n@pytest.mark.parametrize(\"interpolation\", [\"bilinear\", \"area\"])\ndef test_resize_pytorch(height, width, channels_first, label_type, interpolation, image_batch, art_warning):\n import torch\n\n x, y = image_batch\n\n x = torch.from_numpy(x)\n if label_type == \"classification\":\n y = torch.from_numpy(y)\n elif label_type == \"object_detection\":\n y = [{k: torch.from_numpy(v) for k, v in y_i.items()} for y_i in y]\n\n try:\n resize = ImageResizePyTorch(\n height=height,\n width=width,\n channels_first=channels_first,\n label_type=label_type,\n interpolation=interpolation,\n )\n\n x_preprocess, y_preprocess = resize.forward(x, y)\n\n if channels_first:\n assert x_preprocess.shape == (x.shape[0], x.shape[1], height, width)\n else:\n assert x_preprocess.shape == (x.shape[0], height, width, x.shape[3])\n\n if label_type == \"classification\":\n np.testing.assert_array_equal(y, y_preprocess)\n elif label_type == \"object_detection\":\n assert y[0][\"boxes\"].shape == y_preprocess[0][\"boxes\"].shape\n np.testing.assert_array_equal(y[0][\"labels\"], y_preprocess[0][\"labels\"])\n else:\n assert y is None\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"height\", [16, 20, 24])\n@pytest.mark.parametrize(\"width\", [16, 20, 24])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"label_type\", [None, \"classification\", \"object_detection\"])\n@pytest.mark.parametrize(\"interpolation\", [\"bilinear\", \"area\"])\ndef test_resize_tensorflow(height, width, channels_first, label_type, interpolation, image_batch, art_warning):\n import tensorflow as tf\n\n x, y = image_batch\n\n x = tf.convert_to_tensor(x)\n if label_type == \"classification\":\n y = tf.convert_to_tensor(y)\n elif label_type == \"object_detection\":\n y = [{k: tf.convert_to_tensor(v) for k, v in y_i.items()} for y_i in y]\n\n try:\n resize = ImageResizeTensorFlowV2(\n height=height,\n width=width,\n channels_first=channels_first,\n label_type=label_type,\n interpolation=interpolation,\n )\n\n x_preprocess, y_preprocess = resize.forward(x, y)\n\n if channels_first:\n assert x_preprocess.shape == (x.shape[0], x.shape[1], height, width)\n else:\n assert x_preprocess.shape == (x.shape[0], height, width, x.shape[3])\n\n if label_type == \"classification\":\n np.testing.assert_array_equal(y, y_preprocess)\n elif label_type == \"object_detection\":\n assert y[0][\"boxes\"].shape == y_preprocess[0][\"boxes\"].shape\n np.testing.assert_array_equal(y[0][\"labels\"], y_preprocess[0][\"labels\"])\n else:\n assert y is None\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params_numpy(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = ImageResize(height=0, width=32)\n\n with pytest.raises(ValueError):\n _ = ImageResize(height=32, width=0)\n\n with pytest.raises(ValueError):\n _ = ImageResize(height=0, width=0)\n\n with pytest.raises(ValueError):\n _ = ImageResize(height=32, width=32, clip_values=(0,))\n\n with pytest.raises(ValueError):\n _ = ImageResize(height=32, width=32, clip_values=(1, 0))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params_pytorch(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = ImageResizePyTorch(height=0, width=32)\n\n with pytest.raises(ValueError):\n _ = ImageResizePyTorch(height=32, width=0)\n\n with pytest.raises(ValueError):\n _ = ImageResizePyTorch(height=0, width=0)\n\n with pytest.raises(ValueError):\n _ = ImageResizePyTorch(height=32, width=32, clip_values=(0,))\n\n with pytest.raises(ValueError):\n _ = ImageResizePyTorch(height=32, width=32, clip_values=(1, 0))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_check_params_tensorflow(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = ImageResizeTensorFlowV2(height=0, width=32)\n\n with pytest.raises(ValueError):\n _ = ImageResizeTensorFlowV2(height=32, width=0)\n\n with pytest.raises(ValueError):\n _ = ImageResizeTensorFlowV2(height=0, width=0)\n\n with pytest.raises(ValueError):\n _ = ImageResizeTensorFlowV2(height=32, width=32, clip_values=(0,))\n\n with pytest.raises(ValueError):\n _ = ImageResizeTensorFlowV2(height=32, width=32, clip_values=(1, 0))\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/preprocessing/image/test_image_square_pad.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\n\nimport numpy as np\nimport pytest\n\nfrom art.config import ART_NUMPY_DTYPE\nfrom art.preprocessing.image import ImageSquarePad, ImageSquarePadPyTorch, ImageSquarePadTensorFlowV2\nfrom tests.utils import ARTTestException\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture()\ndef image_batch(height, width, channels_first, label_type):\n channels = 3\n\n if channels_first:\n data_shape = (2, channels, height, width)\n else:\n data_shape = (2, height, width, channels)\n x = (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n\n if label_type == \"classification\":\n y = np.arange(len(x))\n elif label_type == \"object_detection\":\n y = []\n for _ in range(len(x)):\n y_1, x_1 = np.random.uniform(0, (height / 2, width / 2))\n y_2, x_2 = np.random.uniform((y_1 + 3, x_1 + 3), (height, width))\n target_dict = {\n \"boxes\": np.array([[x_1, y_1, x_2, y_2]]),\n \"labels\": np.array([0]),\n }\n y.append(target_dict)\n else:\n y = None\n\n return x, y\n\n\n@pytest.mark.framework_agnostic\n@pytest.mark.parametrize(\"height\", [16, 20, 24])\n@pytest.mark.parametrize(\"width\", [16, 20, 24])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"label_type\", [None, \"classification\", \"object_detection\"])\n@pytest.mark.parametrize(\"pad_mode\", [\"constant\", \"reflect\"])\ndef test_square_pad_numpy(height, width, channels_first, label_type, pad_mode, image_batch, art_warning):\n x, y = image_batch\n length = max(height, width)\n\n try:\n resize = ImageSquarePad(\n channels_first=channels_first,\n label_type=label_type,\n pad_mode=pad_mode,\n )\n\n x_preprocess, y_preprocess = resize(x, y)\n\n if channels_first:\n assert x_preprocess.shape == (x.shape[0], x.shape[1], length, length)\n else:\n assert x_preprocess.shape == (x.shape[0], length, length, x.shape[3])\n\n if label_type == \"classification\":\n np.testing.assert_array_equal(y, y_preprocess)\n elif label_type == \"object_detection\":\n assert y[0][\"boxes\"].shape == y_preprocess[0][\"boxes\"].shape\n np.testing.assert_array_equal(y[0][\"labels\"], y_preprocess[0][\"labels\"])\n else:\n assert y is None\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\n@pytest.mark.parametrize(\"height\", [16, 20, 24])\n@pytest.mark.parametrize(\"width\", [16, 20, 24])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"label_type\", [None, \"classification\", \"object_detection\"])\n@pytest.mark.parametrize(\"pad_mode\", [\"constant\", \"reflect\"])\ndef test_square_pad_pytorch(height, width, channels_first, label_type, pad_mode, image_batch, art_warning):\n import torch\n\n x, y = image_batch\n length = max(height, width)\n\n x = torch.from_numpy(x)\n if label_type == \"classification\":\n y = torch.from_numpy(y)\n elif label_type == \"object_detection\":\n y = [{k: torch.from_numpy(v) for k, v in y_i.items()} for y_i in y]\n\n try:\n resize = ImageSquarePadPyTorch(\n channels_first=channels_first,\n label_type=label_type,\n pad_mode=pad_mode,\n )\n\n x_preprocess, y_preprocess = resize.forward(x, y)\n\n if channels_first:\n assert x_preprocess.shape == (x.shape[0], x.shape[1], length, length)\n else:\n assert x_preprocess.shape == (x.shape[0], length, length, x.shape[3])\n\n if label_type == \"classification\":\n np.testing.assert_array_equal(y, y_preprocess)\n elif label_type == \"object_detection\":\n assert y[0][\"boxes\"].shape == y_preprocess[0][\"boxes\"].shape\n np.testing.assert_array_equal(y[0][\"labels\"], y_preprocess[0][\"labels\"])\n else:\n assert y is None\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\n@pytest.mark.parametrize(\"height\", [16, 20, 24])\n@pytest.mark.parametrize(\"width\", [16, 20, 24])\n@pytest.mark.parametrize(\"channels_first\", [True, False])\n@pytest.mark.parametrize(\"label_type\", [None, \"classification\", \"object_detection\"])\n@pytest.mark.parametrize(\"pad_mode\", [\"CONSTANT\", \"REFLECT\"])\ndef test_square_pad_tensorflow(height, width, channels_first, label_type, pad_mode, image_batch, art_warning):\n import tensorflow as tf\n\n x, y = image_batch\n length = max(height, width)\n\n x = tf.convert_to_tensor(x)\n if label_type == \"classification\":\n y = tf.convert_to_tensor(y)\n elif label_type == \"object_detection\":\n y = [{k: tf.convert_to_tensor(v) for k, v in y_i.items()} for y_i in y]\n\n try:\n resize = ImageSquarePadTensorFlowV2(\n channels_first=channels_first,\n label_type=label_type,\n pad_mode=pad_mode,\n )\n\n x_preprocess, y_preprocess = resize.forward(x, y)\n\n if channels_first:\n assert x_preprocess.shape == (x.shape[0], x.shape[1], length, length)\n else:\n assert x_preprocess.shape == (x.shape[0], length, length, x.shape[3])\n\n if label_type == \"classification\":\n np.testing.assert_array_equal(y, y_preprocess)\n elif label_type == \"object_detection\":\n assert y[0][\"boxes\"].shape == y_preprocess[0][\"boxes\"].shape\n np.testing.assert_array_equal(y[0][\"labels\"], y_preprocess[0][\"labels\"])\n else:\n assert y is None\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.framework_agnostic\ndef test_check_params_numpy(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = ImageSquarePad(pad_mode=\"constant\", clip_values=(0,))\n\n with pytest.raises(ValueError):\n _ = ImageSquarePad(pad_mode=\"constant\", clip_values=(1, 0))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"pytorch\")\ndef test_check_params_pytorch(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = ImageSquarePadPyTorch(pad_mode=\"constant\", clip_values=(0,))\n\n with pytest.raises(ValueError):\n _ = ImageSquarePadPyTorch(pad_mode=\"constant\", clip_values=(1, 0))\n\n except ARTTestException as e:\n art_warning(e)\n\n\n@pytest.mark.only_with_platform(\"tensorflow2\")\ndef test_check_params_tensorflow(art_warning):\n try:\n with pytest.raises(ValueError):\n _ = ImageSquarePadTensorFlowV2(pad_mode=\"constant\", clip_values=(0,))\n\n with pytest.raises(ValueError):\n _ = ImageSquarePadTensorFlowV2(pad_mode=\"constant\", clip_values=(1, 0))\n\n except ARTTestException as e:\n art_warning(e)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: tests/utils/test_utils.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport pytest\n\nfrom art.utils import Deprecated, deprecated, deprecated_keyword_arg\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestDeprecated:\n \"\"\"\n Test the deprecation decorator functions and methods.\n \"\"\"\n\n def test_deprecated_simple(self):\n @deprecated(\"1.3.0\")\n def simple_addition(a, b):\n return a + b\n\n with pytest.deprecated_call():\n simple_addition(1, 2)\n\n def test_deprecated_reason_keyword(self, recwarn):\n @deprecated(\"1.3.0\", reason=\"With some reason message.\")\n def simple_addition(a, b):\n return a + b\n\n warn_msg_expected = (\n \"Function 'simple_addition' is deprecated and will be removed in future release 1.3.0.\"\n \"\\nWith some reason message.\"\n )\n\n simple_addition(1, 2)\n warn_obj = recwarn.pop(DeprecationWarning)\n assert str(warn_obj.message) == warn_msg_expected\n\n def test_deprecated_replaced_by_keyword(self, recwarn):\n @deprecated(\"1.3.0\", replaced_by=\"sum\")\n def simple_addition(a, b):\n return a + b\n\n warn_msg_expected = (\n \"Function 'simple_addition' is deprecated and will be removed in future release 1.3.0.\"\n \" It will be replaced by 'sum'.\"\n )\n\n simple_addition(1, 2)\n warn_obj = recwarn.pop(DeprecationWarning)\n assert str(warn_obj.message) == warn_msg_expected\n\n\nclass TestDeprecatedKeyword:\n \"\"\"\n Test the deprecation decorator for keyword arguments.\n \"\"\"\n\n def test_deprecated_keyword_used(self):\n @deprecated_keyword_arg(\"a\", \"1.3.0\")\n def simple_addition(a=Deprecated, b=1):\n result = a if a is Deprecated else a + b\n return result\n\n with pytest.deprecated_call():\n simple_addition(a=1)\n\n def test_deprecated_keyword_not_used(self, recwarn):\n @deprecated_keyword_arg(\"b\", \"1.3.0\")\n def simple_addition(a, b=Deprecated):\n result = a if b is Deprecated else a + b\n return result\n\n simple_addition(1)\n assert len(recwarn) == 0\n\n def test_reason(self, recwarn):\n @deprecated_keyword_arg(\"a\", \"1.3.0\", reason=\"With some reason message.\")\n def simple_addition(a=Deprecated, b=1):\n result = a if a is Deprecated else a + b\n return result\n\n warn_msg_expected = (\n \"Keyword argument 'a' in 'simple_addition' is deprecated and will be removed in future release 1.3.0.\"\n \"\\nWith some reason message.\"\n )\n\n simple_addition(a=1)\n warn_obj = recwarn.pop(DeprecationWarning)\n assert str(warn_obj.message) == warn_msg_expected\n\n def test_replaced_by(self, recwarn):\n @deprecated_keyword_arg(\"b\", \"1.3.0\", replaced_by=\"c\")\n def simple_addition(a=1, b=Deprecated, c=1):\n result = a + c if b is Deprecated else a + b\n return result\n\n warn_msg_expected = (\n \"Keyword argument 'b' in 'simple_addition' is deprecated and will be removed in future release 1.3.0.\"\n \" It will be replaced by 'c'.\"\n )\n\n simple_addition(a=1, b=1)\n warn_obj = recwarn.pop(DeprecationWarning)\n assert str(warn_obj.message) == warn_msg_expected\n\n def test_replaced_by_keyword_missing_signature_error(self, recwarn):\n @deprecated_keyword_arg(\"b\", \"1.3.0\", replaced_by=\"c\")\n def simple_addition(a=1, b=Deprecated):\n result = a if b is Deprecated else a + b\n return result\n\n exc_msg = \"Deprecated keyword replacement not found in function signature.\"\n with pytest.raises(ValueError, match=exc_msg):\n simple_addition(a=1)\n\n def test_deprecated_keyword_default_value_error(self):\n @deprecated_keyword_arg(\"a\", \"1.3.0\")\n def simple_addition(a=None, b=1):\n result = a if a is None else a + b\n return result\n\n exc_msg = \"Deprecated keyword argument must default to the Decorator singleton.\"\n with pytest.raises(ValueError, match=exc_msg):\n simple_addition(a=1)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MLOps\n\nThis directory will contain samples and examples to show how to leverage ART for MLOps, in Machine Learning Platforms and Pipelines.\n\nThe will contain designs, specifications, shared code and processes that meet the following goals:\n* Enable integration between MLOps Pipelines and ART e.g. Kubeflow Pipelines working with ART\n* Enable ART to be surfaced in ML Platforms e.g. OpenScale, KFServing\n* Enable support structure for this code to be maintained and tested\n\nSamples:\n\n[Kubeflow](kubeflow/)\n\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/kubeflow/README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# Kubeflow Pipeline Components for ART\n\nKubeflow pipeline components are implementations of Kubeflow pipeline tasks. Each task takes\none or more [artifacts](https://www.kubeflow.org/docs/pipelines/overview/concepts/output-artifact/)\nas input and may produce one or more\n[artifacts](https://www.kubeflow.org/docs/pipelines/overview/concepts/output-artifact/) as output.\n\n\n**Example: ART Components**\n* [Adversarial Robustness Evaluation - FGSM - PyTorch](robustness_evaluation_fgsm_pytorch)\n\nEach task usually includes two parts:\n\nEach component has a component.yaml which will describe the functionality exposed by it, for e.g.\n\n```\nname: 'Adversarial Robustness Evaluation'\ndescription: |\n Evaluate the adversarial robustness using the Fast Gradient Sign Method of the Adversarial Robustness Toolbox (ART).\n This is a simple demonstration of how to create evaluations using adversarial methods, and generally it is not recommended\n to evaluate adversarial robustness solely using the Fast Gradient Sign Method. To create a thorough robustness assessment,\n please refer to https://arxiv.org/abs/1902.06705 which provides widely accepted guidelines on different combinations of attacks.\nmetadata:\n annotations: {platform: 'OpenSource'}\ninputs:\n - {name: model_id, description: 'Required. Training model ID', default: 'training-dummy'}\n - {name: epsilon, description: 'Required. Epsilon value for the FGSM attack', default: '0.2'}\n - {name: model_class_file, description: 'Required. pytorch model class file'}\n - {name: model_class_name, description: 'Required. pytorch model class name', default: 'model'}\n - {name: feature_testset_path, description: 'Required. Feature test dataset path in the data bucket'}\n - {name: label_testset_path, description: 'Required. Label test dataset path in the data bucket'}\n - {name: loss_fn, description: 'Required. PyTorch model loss function'}\n - {name: optimizer, description: 'Required. PyTorch model optimizer'}\n - {name: clip_values, description: 'Required. PyTorch model clip_values allowed for features (min, max)'}\n - {name: nb_classes, description: 'Required. The number of classes of the model'}\n - {name: input_shape, description: 'Required. The shape of one input instance for the pytorch model'}\n - {name: data_bucket_name, description: 'Bucket that has the processed data', default: 'training-data'}\n - {name: result_bucket_name, description: 'Bucket that has the training results', default: 'training-result'}\n - {name: adversarial_accuracy_threshold, description: 'Model accuracy threshold on adversarial samples', default: '0.2'}\noutputs:\n - {name: metric_path, description: 'Path for robustness check output'}\n - {name: robust_status, description: 'Path for robustness status output'}\nimplementation:\n container:\n image: aipipeline/robustness-evaluation:pytorch\n command: ['python']\n args: [\n -u, robustness_evaluation_fgsm_pytorch.py,\n --model_id, {inputValue: model_id},\n --model_class_file, {inputValue: model_class_file},\n --model_class_name, {inputValue: model_class_name},\n --feature_testset_path, {inputValue: feature_testset_path},\n --label_testset_path, {inputValue: label_testset_path},\n --epsilon, {inputValue: epsilon},\n --loss_fn, {inputValue: loss_fn},\n --optimizer, {inputValue: optimizer},\n --clip_values, {inputValue: clip_values},\n --nb_classes, {inputValue: nb_classes},\n --input_shape, {inputValue: input_shape},\n --metric_path, {outputPath: metric_path},\n --robust_status, {outputPath: robust_status},\n --data_bucket_name, {inputValue: data_bucket_name},\n --result_bucket_name, {inputValue: result_bucket_name},\n --adversarial_accuracy_threshold, {inputValue: adversarial_accuracy_threshold}\n ]\n```\n\nSee how to [use the Kubeflow Pipelines SDK](https://www.kubeflow.org/docs/pipelines/sdk/sdk-overview/)\nand [build your own components](https://www.kubeflow.org/docs/pipelines/sdk/build-component/).\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/kubeflow/robustness_evaluation_fgsm_pytorch/component.yaml\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nname: 'Adversarial Robustness Evaluation'\ndescription: |\n Evaluate the adversarial robustness using the Fast Gradient Sign Method of the Adversarial Robustness Toolbox (ART).\n This is a simple demonstration of how to create evaluations using adversarial methods, and generally it is not recommended\n to evaluate adversarial robustness solely using the Fast Gradient Sign Method. To create a thorough robustness assessment,\n please refer to https://arxiv.org/abs/1902.06705 which provides widely accepted guidelines on different combinations of attacks.\nmetadata:\n annotations: {platform: 'OpenSource'}\ninputs:\n - {name: model_id, type: String, description: 'Required. Training model ID', default: 'training-dummy'}\n - {name: epsilon, type: String, description: 'Required. Epsilon value for the FGSM attack', default: '0.2'}\n - {name: model_class_file, type: String, description: 'Required. pytorch model class file'}\n - {name: model_class_name, type: String, description: 'Required. pytorch model class name', default: 'model'}\n - {name: feature_testset_path, type: String, description: 'Required. Feature test dataset path in the data bucket'}\n - {name: label_testset_path, type: String, description: 'Required. Label test dataset path in the data bucket'}\n - {name: loss_fn, type: String, description: 'Required. PyTorch model loss function'}\n - {name: optimizer, type: String, description: 'Required. PyTorch model optimizer'}\n - {name: clip_values, type: String, description: 'Required. PyTorch model clip_values allowed for features (min, max)'}\n - {name: nb_classes, type: String, description: 'Required. The number of classes of the model'}\n - {name: input_shape, type: String, description: 'Required. The shape of one input instance for the pytorch model'}\n - {name: data_bucket_name, type: String, description: 'Bucket that has the processed data', default: 'training-data'}\n - {name: result_bucket_name, type: String, description: 'Bucket that has the training results', default: 'training-result'}\n - {name: adversarial_accuracy_threshold, type: String, description: 'Model accuracy threshold on adversarial samples', default: '0.2'}\noutputs:\n - {name: metric_path, type: String, description: 'Path for robustness check output'}\n - {name: robust_status, type: String, description: 'Path for robustness status output'}\nimplementation:\n container:\n image: aipipeline/robustness-evaluation:pytorch\n command: ['python']\n args: [\n -u, robustness_evaluation_fgsm_pytorch.py,\n --model_id, {inputValue: model_id},\n --model_class_file, {inputValue: model_class_file},\n --model_class_name, {inputValue: model_class_name},\n --feature_testset_path, {inputValue: feature_testset_path},\n --label_testset_path, {inputValue: label_testset_path},\n --epsilon, {inputValue: epsilon},\n --loss_fn, {inputValue: loss_fn},\n --optimizer, {inputValue: optimizer},\n --clip_values, {inputValue: clip_values},\n --nb_classes, {inputValue: nb_classes},\n --input_shape, {inputValue: input_shape},\n --metric_path, {outputPath: metric_path},\n --robust_status, {outputPath: robust_status},\n --data_bucket_name, {inputValue: data_bucket_name},\n --result_bucket_name, {inputValue: result_bucket_name},\n --adversarial_accuracy_threshold, {inputValue: adversarial_accuracy_threshold}\n ]\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/kubeflow/robustness_evaluation_fgsm_pytorch/src/robustness.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"Robustness evaluation module.\"\"\"\n\nimport zipfile\nimport importlib\nimport re\n\nimport numpy as np\nfrom minio import Minio\n\nimport torch\nimport torch.utils.data\n\nfrom art.estimators.classification import PyTorchClassifier\nfrom art.attacks.evasion.fast_gradient import FastGradientMethod\n\nfrom robustness_util import get_metrics\n\n\ndef robustness_evaluation(\n object_storage_url,\n object_storage_username,\n object_storage_password,\n data_bucket_name,\n result_bucket_name,\n model_id,\n feature_testset_path=\"processed_data/X_test.npy\",\n label_testset_path=\"processed_data/y_test.npy\",\n clip_values=(0, 1),\n nb_classes=2,\n input_shape=(1, 3, 64, 64),\n model_class_file=\"model.py\",\n model_class_name=\"model\",\n LossFn=\"\",\n Optimizer=\"\",\n epsilon=0.2,\n):\n\n url = re.compile(r\"https?://\")\n cos = Minio(\n url.sub(\"\", object_storage_url),\n access_key=object_storage_username,\n secret_key=object_storage_password,\n secure=False,\n )\n\n dataset_filenamex = \"X_test.npy\"\n dataset_filenamey = \"y_test.npy\"\n weights_filename = \"model.pt\"\n model_files = model_id + \"/_submitted_code/model.zip\"\n\n cos.fget_object(data_bucket_name, feature_testset_path, dataset_filenamex)\n cos.fget_object(data_bucket_name, label_testset_path, dataset_filenamey)\n cos.fget_object(result_bucket_name, model_id + \"/\" + weights_filename, weights_filename)\n cos.fget_object(result_bucket_name, model_files, \"model.zip\")\n\n # Load PyTorch model definition from the source code.\n zip_ref = zipfile.ZipFile(\"model.zip\", \"r\")\n zip_ref.extractall(\"model_files\")\n zip_ref.close()\n\n modulename = \"model_files.\" + model_class_file.split(\".\")[0].replace(\"-\", \"_\")\n\n \"\"\"\n We required users to define where the model class is located or follow\n some naming convention we have provided.\n \"\"\"\n model_class = getattr(importlib.import_module(modulename), model_class_name)\n\n # load & compile model\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n model = model_class().to(device)\n model.load_state_dict(torch.load(weights_filename, map_location=device))\n\n # Define Loss and optimizer function for the PyTorch model\n if LossFn:\n loss_fn = eval(LossFn)\n else:\n loss_fn = torch.nn.CrossEntropyLoss()\n if Optimizer:\n optimizer = eval(Optimizer)\n else:\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n # create pytorch classifier\n classifier = PyTorchClassifier(\n model=model,\n loss=loss_fn,\n optimizer=optimizer,\n input_shape=input_shape,\n nb_classes=nb_classes,\n clip_values=clip_values,\n )\n\n # load test dataset\n x = np.load(dataset_filenamex)\n y = np.load(dataset_filenamey)\n\n # craft adversarial samples using FGSM\n crafter = FastGradientMethod(classifier, eps=epsilon)\n x_samples = crafter.generate(x)\n\n # obtain all metrics (robustness score, perturbation metric, reduction in confidence)\n metrics, y_pred_orig, y_pred_adv = get_metrics(model, x, x_samples, y)\n\n print(\"metrics:\", metrics)\n return metrics\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/kubeflow/robustness_evaluation_fgsm_pytorch/src/robustness_evaluation_fgsm_pytorch.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport json\nimport argparse\nimport os\n\nfrom robustness import robustness_evaluation\n\n\ndef get_secret(path, default=\"\"):\n try:\n with open(path, \"r\") as f:\n cred = f.readline().strip(\"'\")\n f.close()\n return cred\n except Exception:\n return default\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--epsilon\", type=float, help=\"Epsilon value for the FGSM attack\", default=0.2)\n parser.add_argument(\"--model_id\", type=str, help=\"Training model id\", default=\"training-dummy\")\n parser.add_argument(\n \"--metric_path\", type=str, help=\"Path for robustness check output\", default=\"/tmp/robustness.txt\"\n )\n parser.add_argument(\n \"--robust_status\", type=str, help=\"Path for robustness status output\", default=\"/tmp/status.txt\"\n )\n parser.add_argument(\"--model_class_file\", type=str, help=\"pytorch model class file\", default=\"model.py\")\n parser.add_argument(\"--model_class_name\", type=str, help=\"pytorch model class name\", default=\"model\")\n parser.add_argument(\n \"--loss_fn\", type=str, help=\"PyTorch model loss function\", default=\"torch.nn.CrossEntropyLoss()\"\n )\n parser.add_argument(\n \"--optimizer\",\n type=str,\n help=\"pytorch model optimizer\",\n default=\"torch.optim.Adam(model.parameters(), lr=0.001)\",\n )\n parser.add_argument(\n \"--clip_values\", type=str, help=\"pytorch model clip_values allowed for features (min, max)\", default=\"(0,1)\"\n )\n parser.add_argument(\"--nb_classes\", type=int, help=\"The number of classes of the model\", default=2)\n parser.add_argument(\n \"--input_shape\", type=str, help=\"The shape of one input instance for the pytorch model\", default=\"(1,3,64,64)\"\n )\n parser.add_argument(\n \"--feature_testset_path\",\n type=str,\n help=\"Feature test dataset path in the data bucket\",\n default=\"processed_data/X_test.npy\",\n )\n parser.add_argument(\n \"--label_testset_path\",\n type=str,\n help=\"Label test dataset path in the data bucket\",\n default=\"processed_data/y_test.npy\",\n )\n parser.add_argument(\n \"--data_bucket_name\", type=str, help=\"Bucket that has the processed data\", default=\"training-data\"\n )\n parser.add_argument(\n \"--result_bucket_name\", type=str, help=\"Bucket that has the training results\", default=\"training-result\"\n )\n parser.add_argument(\n \"--adversarial_accuracy_threshold\",\n type=float,\n help=\"Model accuracy threshold on adversarial samples\",\n default=0.2,\n )\n args = parser.parse_args()\n\n epsilon = args.epsilon\n metric_path = args.metric_path\n model_id = args.model_id\n robust_status = args.robust_status\n model_class_file = args.model_class_file\n model_class_name = args.model_class_name\n LossFn = args.loss_fn\n Optimizer = args.optimizer\n nb_classes = args.nb_classes\n feature_testset_path = args.feature_testset_path\n label_testset_path = args.label_testset_path\n data_bucket_name = args.data_bucket_name\n result_bucket_name = args.result_bucket_name\n clip_values = eval(args.clip_values)\n input_shape = eval(args.input_shape)\n adversarial_accuracy_threshold = args.adversarial_accuracy_threshold\n\n object_storage_url = get_secret(\"/app/secrets/s3_url\", \"minio-service.kubeflow:9000\")\n object_storage_username = get_secret(\"/app/secrets/s3_access_key_id\", \"minio\")\n object_storage_password = get_secret(\"/app/secrets/s3_secret_access_key\", \"minio123\")\n\n metrics = robustness_evaluation(\n object_storage_url,\n object_storage_username,\n object_storage_password,\n data_bucket_name,\n result_bucket_name,\n model_id,\n feature_testset_path=feature_testset_path,\n label_testset_path=label_testset_path,\n clip_values=clip_values,\n nb_classes=nb_classes,\n input_shape=input_shape,\n model_class_file=model_class_file,\n model_class_name=model_class_name,\n LossFn=LossFn,\n Optimizer=Optimizer,\n epsilon=epsilon,\n )\n\n if not os.path.exists(os.path.dirname(metric_path)):\n os.makedirs(os.path.dirname(metric_path))\n with open(metric_path, \"w\") as report:\n report.write(json.dumps(metrics))\n\n robust = \"true\"\n if metrics[\"model accuracy on adversarial samples\"] < adversarial_accuracy_threshold:\n robust = \"false\"\n\n if not os.path.exists(os.path.dirname(robust_status)):\n os.makedirs(os.path.dirname(robust_status))\n with open(robust_status, \"w\") as report:\n report.write(robust)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/kubeflow/robustness_evaluation_fgsm_pytorch/src/robustness_util.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport numpy as np\nimport numpy.linalg as la\n\nimport torch\nimport torch.utils.data\nfrom torch.autograd import Variable\n\n\ndef get_metrics(model, x_original, x_adv_samples, y):\n model_accuracy_on_non_adversarial_samples, y_pred = evaluate(model, x_original, y)\n model_accuracy_on_adversarial_samples, y_pred_adv = evaluate(model, x_adv_samples, y)\n\n pert_metric = get_perturbation_metric(x_original, x_adv_samples, y_pred, y_pred_adv, ord=2)\n conf_metric = get_confidence_metric(y_pred, y_pred_adv)\n\n data = {\n \"model accuracy on test data\": float(model_accuracy_on_non_adversarial_samples),\n \"model accuracy on adversarial samples\": float(model_accuracy_on_adversarial_samples),\n \"confidence reduced on correctly classified adv_samples\": float(conf_metric),\n \"average perturbation on misclassified adv_samples\": float(pert_metric),\n }\n return data, y_pred, y_pred_adv\n\n\n# Compute the accuaracy and predicted label using the given test dataset\ndef evaluate(model, X_test, y_test):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n test = torch.utils.data.TensorDataset(\n Variable(torch.FloatTensor(X_test.astype(\"float32\"))), Variable(torch.LongTensor(y_test.astype(\"float32\")))\n )\n test_loader = torch.utils.data.DataLoader(test, batch_size=64, shuffle=False)\n model.eval()\n correct = 0\n accuracy = 0\n y_pred = []\n with torch.no_grad():\n for images, labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n predictions = torch.softmax(outputs.data, dim=1).detach().numpy()\n correct += predicted.eq(labels.data.view_as(predicted)).sum().item()\n y_pred += predictions.tolist()\n accuracy = 1.0 * correct / len(test_loader.dataset)\n y_pred = np.array(y_pred)\n return accuracy, y_pred\n\n\ndef get_perturbation_metric(x_original, x_adv, y_pred, y_pred_adv, ord=2):\n idxs = np.argmax(y_pred_adv, axis=1) != np.argmax(y_pred, axis=1)\n\n if np.sum(idxs) == 0.0:\n return 0\n\n perts_norm = la.norm((x_adv - x_original).reshape(x_original.shape[0], -1), ord, axis=1)\n perts_norm = perts_norm[idxs]\n\n return np.mean(perts_norm / la.norm(x_original[idxs].reshape(np.sum(idxs), -1), ord, axis=1))\n\n\n# This computes the change in confidence for all images in the test set\ndef get_confidence_metric(y_pred, y_pred_adv):\n y_classidx = np.argmax(y_pred, axis=1)\n y_classconf = y_pred[np.arange(y_pred.shape[0]), y_classidx]\n\n y_adv_classidx = np.argmax(y_pred_adv, axis=1)\n y_adv_classconf = y_pred_adv[np.arange(y_pred_adv.shape[0]), y_adv_classidx]\n\n idxs = y_classidx == y_adv_classidx\n\n if np.sum(idxs) == 0.0:\n return 0\n\n idxnonzero = y_classconf != 0\n idxs = idxs & idxnonzero\n\n return np.mean((y_classconf[idxs] - y_adv_classconf[idxs]) / y_classconf[idxs])\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/mlops/kubeflow/robustness_evaluation_fgsm_pytorch/src/model_files/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'ART_IBM' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: utils/resources/create_model_weights.py\n<|im_end|>\n<|im_start|>assistant\nREPO: ART_IBM\nCODE:\n# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2019\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport os\nimport pickle\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier, BaggingClassifier, ExtraTreesClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\nimport numpy as np\n\nfrom tests.utils import load_dataset, master_seed\n\n\ndef main_mnist_binary():\n master_seed(1234)\n\n model = Sequential()\n model.add(Conv2D(1, kernel_size=(7, 7), activation=\"relu\", input_shape=(28, 28, 1)))\n model.add(MaxPooling2D(pool_size=(4, 4)))\n model.add(Flatten())\n model.add(Dense(1, activation=\"sigmoid\"))\n\n model.compile(loss=\"binary_crossentropy\", optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), metrics=[\"accuracy\"])\n\n (x_train, y_train), (_, _), _, _ = load_dataset(\"mnist\")\n\n y_train = np.argmax(y_train, axis=1)\n y_train[y_train < 5] = 0\n y_train[y_train >= 5] = 1\n\n model.fit(x_train, y_train, batch_size=128, epochs=10)\n\n w_0, b_0 = model.layers[0].get_weights()\n w_3, b_3 = model.layers[3].get_weights()\n\n np.save(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models/scikit/\", \"W_CONV2D_MNIST_BINARY\"\n ),\n w_0,\n )\n np.save(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models/scikit/\" \"B_CONV2D_MNIST_BINARY\"\n ),\n b_0,\n )\n np.save(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models/scikit/\" \"W_DENSE_MNIST_BINARY\"\n ),\n w_3,\n )\n np.save(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)), \"utils/resources/models/scikit/\" \"B_DENSE_MNIST_BINARY\"\n ),\n b_3,\n )\n\n\ndef main_diabetes():\n master_seed(1234)\n\n model = Sequential()\n model.add(Dense(100, activation=\"relu\", input_dim=10))\n model.add(Dense(10, activation=\"relu\"))\n model.add(Dense(1))\n\n model.compile(loss=\"mean_squared_error\", optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), metrics=[\"accuracy\"])\n\n (x_train, y_train), (_, _), _, _ = load_dataset(\"diabetes\")\n\n model.fit(x_train, y_train, batch_size=128, epochs=10)\n\n w_0, b_0 = model.layers[0].get_weights()\n w_1, b_1 = model.layers[1].get_weights()\n w_2, b_2 = model.layers[2].get_weights()\n\n np.save(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"resources/models/\", \"W_DENSE1_DIABETES\"),\n w_0,\n )\n np.save(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"resources/models/\" \"B_DENSE1_DIABETES\"),\n b_0,\n )\n np.save(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"resources/models/\" \"W_DENSE2_DIABETES\"),\n w_1,\n )\n np.save(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"resources/models/\" \"B_DENSE2_DIABETES\"),\n b_1,\n )\n np.save(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"resources/models/\" \"W_DENSE3_DIABETES\"),\n w_2,\n )\n np.save(\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"resources/models/\" \"B_DENSE3_DIABETES\"),\n b_2,\n )\n\n\ndef create_scikit_model_weights():\n master_seed(1234)\n\n model_list = {\n \"decisionTreeClassifier\": DecisionTreeClassifier(),\n \"extraTreeClassifier\": ExtraTreeClassifier(),\n \"adaBoostClassifier\": AdaBoostClassifier(),\n \"baggingClassifier\": BaggingClassifier(),\n \"extraTreesClassifier\": ExtraTreesClassifier(n_estimators=10),\n \"gradientBoostingClassifier\": GradientBoostingClassifier(n_estimators=10),\n \"randomForestClassifier\": RandomForestClassifier(n_estimators=10),\n \"logisticRegression\": LogisticRegression(solver=\"lbfgs\", multi_class=\"auto\"),\n \"svc\": SVC(gamma=\"auto\"),\n \"linearSVC\": LinearSVC(),\n }\n\n clipped_models = {model_name: model for model_name, model in model_list.items()}\n unclipped_models = {model_name: model for model_name, model in model_list.items()}\n\n (x_train_iris, y_train_iris), (_, _), _, _ = load_dataset(\"iris\")\n\n y_train_iris = np.argmax(y_train_iris, axis=1)\n\n for model_name, model in clipped_models.items():\n model.fit(X=x_train_iris, y=y_train_iris)\n pickle.dump(\n model,\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"resources/models/scikit/\",\n \"scikit-\" + model_name + \"-iris-clipped-eq-1.6.1.pickle\",\n ),\n \"wb\",\n ),\n )\n\n for model_name, model in unclipped_models.items():\n model.fit(X=x_train_iris, y=y_train_iris)\n pickle.dump(\n model,\n open(\n os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"resources/models/scikit/\",\n \"scikit-\" + model_name + \"-iris-unclipped-eq-1.6.1.pickle\",\n ),\n \"wb\",\n ),\n )\n\n\nif __name__ == \"__main__\":\n # main_mnist_binary()\n create_scikit_model_weights()\n # main_diabetes()\n\n<|im_end|>"}