### Demo Documents
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/genindex.html
Examples and demonstrations of structural elements and markup within the theme.
```APIDOC
## Demo Documents
### Structural Elements
Demonstrates the usage of structural elements.
### Structural Elements 2
Further examples of structural elements.
### Paragraph Level Markup
Details on paragraph formatting and markup.
### Lists & Tables
Examples of lists and tables.
### `test_py_module`
Documentation for the `test_py_module`.
```
--------------------------------
### Define Python class with docstring examples
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
A module example showing class definitions and embedded code usage within docstrings.
```python
1# -*- coding: utf-8 -*-
2"""Test Module for sphinx_rtd_theme."""
3
4
5class Foo:
6
7 """Docstring for class Foo.
8
9 This text tests for the formatting of docstrings generated from output
10 ``sphinx.ext.autodoc``. Which contain reST, but sphinx nests it in the
11 ``
``, and ``- `` tags. Also, ```` is used for class, method names
12 and etc, but those will *always* have the ``.descname`` or
13 ``.descclassname`` class.
14
15 Normal ```` (like the I just wrote here) needs to be shown with
16 the same style as anything else with ````this type of markup````.
17
18 It's common for programmers to give a code example inside of their
19 docstring::
20
21 from test_py_module import Foo
22
23 myclass = Foo()
24 myclass.dothismethod('with this argument')
25 myclass.flush()
26
27 print(myclass)
28
29
30 Here is a link to :py:meth:`capitalize`.
31 Here is a link to :py:meth:`__init__`.
32
33 """
34
35 #: Doc comment for class attribute Foo.bar.
36 #: It can have multiple lines.
37 bar = 1
38
39 flox = 1.5 #: Doc comment for Foo.flox. One line only.
40
```
--------------------------------
### Initialize NATSBench Model
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/nas.html
Instantiate the NATS-Bench model for benchmarking NAS algorithms. Requires installation of 'nats_bench' and downloading benchmark data.
```python
trojanvision.models.NATSbench(_name ='nats_bench'_, _model =_NATSbench_, _model_index =0_, _model_seed =777_, _hp =200_, _dataset =None_, _dataset_name =None_, _nats_path =None_, _search_space ='tss'_, _** kwargs_)
```
--------------------------------
### Doctest Block Example
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
Shows a doctest block, used for Python-specific usage examples that can be copied from interactive sessions.
```python
>>> print 'Python-specific usage examples; begun with ">>>"'
Python-specific usage examples; begun with ">>>"
>>> print '(cut and pasted from interactive Python sessions)'
(cut and pasted from interactive Python sessions)
```
--------------------------------
### Define function with highlighted lines
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
A Python function example demonstrating line numbering and emphasis.
```python
1def some_function():
2 interesting = False
3 print 'This line is highlighted.'
4 print 'This one is not...'
5 print '...but this one is.'
```
--------------------------------
### Define a class with optional parameters
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/api.html
Example of manually documenting a class with multiple optional parameters, as seen in the django-payments module.
```python
class payments.dotpay.DotpayProvider(seller_id , pin[, channel=0[, lock=False], lang='pl'])
```
--------------------------------
### Literal Block Example
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
Demonstrates how to create a literal block in reStructuredText. Indentation is preserved.
```text
if literal_block:
text = 'is left as-is'
spaces_and_linebreaks = 'are preserved'
markup_processing = None
```
--------------------------------
### Install trojanzoo_sphinx_theme
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/installing.html
Add these two settings to your Sphinx conf.py file to use the trojanzoo_sphinx_theme. Ensure the theme repository is symlinked or subtreed into your docs directory.
```python
html_theme = "trojanzoo_sphinx_theme"
html_theme_path = ["_themes", ]
```
--------------------------------
### Get DataLoader
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Creates a PyTorch DataLoader. If a dataset is not provided, it calls `get_dataset()`. Supports various configurations for batch size, shuffling, and workers.
```python
get_dataloader(_mode =None_, _dataset =None_, _batch_size =None_, _shuffle =None_, _num_workers =None_, _pin_memory =True_, _drop_last =False_, _collate_fn =None_, _** kwargs_)
```
--------------------------------
### Get Dataset Configuration
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/configs.html
Retrieves the configuration specific to a given dataset name. It uses the merged full configuration by default.
```python
get_config(_dataset_name_ , _config =None_, _** kwargs_)[source]
Get config for specific dataset.
Parameters:
* **dataset_name** (_str_) – Dataset name.
* **config** – (ConfigType): The config for all datasets. `value = full_config[config_file][key][dataset_name]`. Defaults to `self.full_config`.
Returns:
_Param[str, Module[str, Any]]_ – Config for `dataset_name`. `value = full_config[config_file][key]`.
```
--------------------------------
### Get Defense Filename
Source: https://ain-soph.github.io/trojanzoo/trojanvision/defenses/index.html
Retrieves filenames associated with the current defense settings. Useful for logging or saving intermediate results.
```python
get_filename(_** kwargs_)
```
--------------------------------
### Line Block Example
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
Illustrates a line block in reStructuredText. Each line starts with a vertical bar, and line breaks are preserved.
```text
| This is a line block.
| It ends with a blank line.
| Each new line begins with a vertical bar (“|”).
| Line breaks and initial indents are preserved.
| Continuation lines are wrapped portions of long lines; they begin with a space in place of the vertical bar.
| The left edge of a continuation line need not be aligned with the left edge of the text above it.
| This is a second line block.
|
|
| Blank lines are permitted internally, but they must begin with a “|”.
| Take it away, Eric the Orchestra Leader!
| > A one, two, a one two three four
|
|
| Half a bee, philosophically,
| must, _ipso facto_ , half not be.
| But half the bee has got to be,
| _vis a vis_ its entity. D’you see?
|
|
| But can a bee be said to be
| or not to be an entire bee,
| when half the bee is not a bee,
| due to some ancient injury?
|
|
| Singing…
```
--------------------------------
### Initialize and use the Foo class
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/api.html
Demonstrates basic instantiation and method invocation for the Foo class.
```python
from test_py_module import Foo
myclass = Foo()
myclass.dothismethod('with this argument')
myclass.flush()
print(myclass)
```
--------------------------------
### initialize
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Initializes the dataset by downloading and extracting necessary files if they are not already prepared.
```APIDOC
## POST /api/data/initialize
### Description
Initialize the dataset (download and extract) if it’s not prepared yet (need overriding).
### Method
POST
### Endpoint
/api/data/initialize
### Parameters
#### Request Body
- **args** - Optional - Positional arguments for initialization.
- **kwargs** - Optional - Keyword arguments for initialization.
### Response
#### Success Response (200)
- **status** (str) - Initialization status message.
### Response Example
```json
{
"status": "Initialization complete."
}
```
```
--------------------------------
### get_parallel_model
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/models.html
Gets the parallel model if multiple GPUs are available.
```APIDOC
## GET /get_parallel_model
### Description
Get the parallel model if there are more than 1 GPU available.
Warning: `torch.nn.DataParallel` would be deprecated according to https://github.com/pytorch/pytorch/issues/65936. We need to consider using `torch.nn.parallel.DistributedDataParallel` instead.
### Method
GET
### Endpoint
/get_parallel_model
### Parameters
#### Path Parameters
None
#### Query Parameters
- **_model** (__Model_) - Required - The non-parallel model.
### Request Example
```json
{
"_model": ""
}
```
### Response
#### Success Response (200)
- **parallel_model** (__Model | nn.DataParallel_) - The parallel model if there are more than 1 GPU available.
#### Response Example
```json
{
"parallel_model": ""
}
```
```
--------------------------------
### Create a defense instance
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/defenses.html
Instantiates a defense object using provided configuration or default values. This is the recommended method for users to initialize defenses.
```python
trojanzoo.defenses.create(_defense_name =None_, _defense =None_, _folder_path =None_, _dataset_name =None_, _dataset =None_, _model_name =None_, _model =None_, _config =config_, _class_dict ={}_, _** kwargs_)[source]
```
--------------------------------
### environ.create
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/environ.html
Loads environment values from configuration and command line.
```APIDOC
## POST /environ/create
### Description
Loads environment values from configuration and command line.
### Method
POST
### Endpoint
/environ/create
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **cmd_config_path** (str) - Optional - Path to the command configuration.
- **dataset_name** (str) - Optional - The dataset name.
- **dataset** (str | trojanzoo.datasets.Dataset) - Optional - Dataset instance or name.
- **model** (trojanzoo.models.Model) - Optional - Model instance.
- **config** (Config) - Optional - The default parameter config.
- **seed** (int) - Optional - The random seed.
- **data_seed** (int) - Optional - Seed for data processing.
- **cudnn_benchmark** (bool) - Optional - Whether to use cuDNN benchmark.
- **cache_threshold** (float) - Optional - Threshold for cache clearing.
- **verbose** (int) - Optional - Verbosity level.
- **color** (bool) - Optional - Whether to use colorful outputs.
- **device** (str | device) - Optional - The device to use ('auto', 'cpu', 'gpu').
- **tqdm** (bool) - Optional - Whether to use tqdm for progress bars.
- **kwargs** (dict) - Optional - Additional keyword arguments for 'optim_args', 'train_args', 'writer_args'.
### Request Example
{
"dataset_name": "cifar10",
"model": "",
"config": "",
"optim_args": {"lr": 0.01}
}
### Response
#### Success Response (200)
- **env** (Env) - The environment instance.
#### Response Example
{
"env": ""
}
```
--------------------------------
### Initialize Dataset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Initializes the dataset by downloading and extracting files if they are not already prepared. This method requires overriding for specific dataset implementations.
```python
initialize(_* args_, _** kwargs_)
```
--------------------------------
### Block Quote Example
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
Demonstrates a block quote in reStructuredText. Content is indented and attributed.
```text
> My theory by A. Elk. Brackets Miss, brackets. This theory goes as follows and begins now. All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. That is my theory, it is mine, and belongs to me and I own it, and what it is too.
> —Anne Elk (Miss)
```
--------------------------------
### Summarize Configuration Information
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/configs.html
Provides a summary of the configuration settings. You can specify which configurations to include in the summary, such as 'final', 'cmd', or specific config keys.
```python
summary(_keys =['final']_, _config =None_, _indent =0_)[source]
Summary the config information.
Parameters:
* **keys** (_list_ _[__str_ _]__|__str_) –
keys of configs to summary.
* `'final'`: `self.full_config`
* `'cmd'`: `self.cmd_config`
* `key in self.config_dict.keys()`
Defaults to `['final']`.
* **indent** (_int_) – The space indent of entire string. Defaults to `0`.
```
--------------------------------
### Get Feature Map (_Model.get_fm)
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/models.html
Retrieves the feature map after preprocessing and feature extraction.
```APIDOC
## Method _Model.get_fm
### Description
`x -> self.preprocess -> self.features -> return`
### Parameters
#### Parameters
- **x** - Input tensor.
- **kwargs** - Keyword arguments passed to `torch.save`.
```
--------------------------------
### Create Image Dataset Instance
Source: https://ain-soph.github.io/trojanzoo/trojanvision/datasets/index.html
Creates an image dataset instance, using default values from config for unspecified arguments. The default folder_path is '{data_dir}/{data_type}/{name}'.
```python
trojanvision.datasets.create(_dataset_name =None_, _dataset =None_, _config =config_, _class_dict =class_dict_, _** kwargs_)
```
--------------------------------
### Get Final Feature Map (_Model.get_final_fm)
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/models.html
Retrieves the final feature map after pooling.
```APIDOC
## Method _Model.get_final_fm
### Description
`x -> self.get_fm -> self.pool -> self.flatten -> return`
### Parameters
#### Parameters
- **x** - Input tensor.
- **kwargs** - Keyword arguments passed to `torch.save`.
```
--------------------------------
### Get Class-based Subset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/data.html
Filters a dataset to return a subset containing only the specified classes.
```python
>>> import torch
>>> from trojanzoo.utils.data import get_class_subset, TensorListDataset
>>>
>>> data = torch.ones(11, 3, 32, 32)
>>> targets = list(range(11))
>>> dataset = TensorListDataset(data, targets)
>>> subset = get_class_subset(dataset, class_list=[2, 3])
>>> len(subset)
2
```
--------------------------------
### Create Defense Instance
Source: https://ain-soph.github.io/trojanzoo/trojanvision/defenses/index.html
Creates an instance of a specified backdoor defense. Requires defense name, dataset, and configuration.
```python
trojanvision.defenses.create(_defense_name =None_, _defense =None_, _dataset_name =None_, _dataset =None_, _config =config_, _class_dict =class_dict_, _** kwargs_)
```
--------------------------------
### Configure HTML Theme Options
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/configuring.html
Define project-wide theme settings within the html_theme_options dictionary in your conf.py file.
```python
html_theme_options = {
'collapse_navigation': False,
'sticky_navigation': True,
'navigation_depth': 4,
'includehidden': True,
'display_version': True,
'prev_next_buttons_location': bottom,
'style_external_links': False,
'github_url': '',
'home_url': /,
'collapsedSections': '',
'doc_items': '',
'logo': '',
'logo_dark': '',
'logo_icon': '',
}
```
--------------------------------
### Get Transform
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Provides the appropriate dataset transform for a given mode (e.g., 'train' or 'valid').
```python
_abstractmethod _get_transform(_mode_)
```
--------------------------------
### Process Class
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/module.html
Inherits from BasicObject to manage output levels and logging.
```APIDOC
## Process
### Description
Inherits BasicObject and specifies output levels for logging or data generation.
### Parameters
- **output** (int/Iterable[str]) - Optional - The level of output or the set of output items.
### Methods
- **get_output(org_output=None)**: Returns a set of output items based on the output level.
- **get_output_int(org_output=0)**: Static method to map integer levels to specific output sets (e.g., 0-4: {'verbose'}).
- **output_iter(name, _iter, iteration=None)**: Static method to format iteration strings.
```
--------------------------------
### Literal Block Example
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
Demonstrates a literal block within a compound paragraph. This is used for displaying preformatted text.
```text
Connecting... OK
Transmitting data... OK
Disconnecting... OK
```
--------------------------------
### Get Original Dataset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Fetches the original, unsplitted dataset. This is a wrapper function; the specific implementation needs to be overridden.
```python
get_org_dataset(_mode_ , _** kwargs_)
```
--------------------------------
### Create Dataset Instance
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Instantiate a dataset object. Default parameters are used from the provided config if not specified in kwargs. The default folder path is '{data_dir}/{data_type}/{name}'.
```python
trojanzoo.datasets.create(_dataset_name =None_, _dataset =None_, _config =config_, _class_dict ={}_, _** kwargs_)
```
--------------------------------
### Quoted Literal Block Example
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/demo.html
Shows a literal block that is quoted, without indentation. Preserves whitespace and line breaks.
```text
>> Great idea!
>
> Why didn't I think of that?
```
--------------------------------
### Summary (_Model.summary)
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/models.html
Prints a string summary of the model instance.
```APIDOC
## Method _Model.summary
### Description
Prints a string summary of the model instance by calling `trojanzoo.utils.module.BasicObject.summary()` and `trojanzoo.utils.model.summary()`.
### Parameters
#### Parameters
- **depth** (int) - Passed to `trojanzoo.utils.model.summary()`. If `None`, set as `env['verbose']`. If still `None`, set as `1`. Defaults to `None`.
- **verbose** (bool) - Passed to `trojanzoo.utils.model.summary()`. Defaults to `True`.
- **indent** (int) - Passed to `trojanzoo.utils.module.BasicObject.summary()` and passed to `trojanzoo.utils.model.summary()` with `10` more. Defaults to `0`.
- **kwargs** - Passed to `trojanzoo.utils.model.summary()`.
```
--------------------------------
### Class: Foo
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/api.html
Documentation for the Foo class, including its methods, attributes, and initialization parameters.
```APIDOC
## Class _test_py_module.test.Foo(_qux_ , _spam =False_)
### Description
Docstring for class Foo.
This text tests for the formatting of docstrings generated from output `sphinx.ext.autodoc`. Which contain reST, but sphinx nests it in the `
`, and `- ` tags. Also, `` is used for class, method names and etc, but those will _always_ have the `.descname` or `.descclassname` class.
Normal `` (like the I just wrote here) needs to be shown with the same style as anything else with ```this type of markup```.
It’s common for programmers to give a code example inside of their docstring:
```
from test_py_module import Foo
myclass = Foo()
myclass.dothismethod('with this argument')
myclass.flush()
print(myclass)
```
Here is a link to `capitalize()`. Here is a link to `__init__()`.
### Methods
#### __init__(_qux_ , _spam =False_)
Start the Foo.
Parameters:
* **qux** (_string_) – The first argument to initialize class.
* **spam** (_bool_) – Spam me yes or no…
#### __weakref__
list of weak references to the object
#### add(_val1_ , _val2_)
Return the added values.
Parameters:
* **val1** (_int_) – First number to add.
* **val2** (_int_) – Second number to add.
Return type:
int
#### another_function(_a_ , _b_ , _** kwargs_)
Here is another function.
Parameters:
* **a** (_int_) – The number of green hats you own.
* **b** (_int_) – The number of non-green hats you own.
* **kwargs** (_float_) – Additional keyword arguments. Each keyword parameter should specify the name of your favorite cuisine. The values should be floats, specifying the mean price of your favorite dish in that cooking style.
Returns:
A 2-tuple. The first element is the mean price of all dishes across cuisines. The second element is the total number of hats you own: a+b.
Return type:
tuple
Raises:
**ValueError** – When `a` is not an integer.
Added in version 1.0: This was added in 1.0
Changed in version 2.0: This was changed in 2.0
Deprecated since version 3.0: This is deprecated since 3.0
#### capitalize(_myvalue_)
Return a string as uppercase.
Parameters:
**myvalue** (_string_) – String to change
Return type:
string
### Attributes
#### bar _ = 1_
Doc comment for class attribute Foo.bar. It can have multiple lines.
#### baz _ = 2_
Docstring for class attribute Foo.baz.
#### flox _ = 1.5_
Doc comment for Foo.flox. One line only.
#### qux
Doc comment for instance attribute qux.
#### spam
Docstring for instance attribute spam.
```
--------------------------------
### summary
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/model.html
Prints a string summary of the module structure.
```APIDOC
## summary
### Description
Prints a string summary of the module, similar to tensorflow.keras.Model.summary().
### Parameters
- **module** (torch.nn.Module) - Required - The module to process.
- **depth** (int) - Optional - The traverse depth. Defaults to 0.
- **verbose** (bool) - Optional - Whether to output auxiliary information. Defaults to True.
- **indent** (int) - Optional - The space indent for the entire string. Defaults to 0.
- **tree_length** (int) - Optional - The tree length. Defaults to None.
- **indent_atom** (int) - Optional - The indent incremental for each sub-structure. Defaults to 12.
```
--------------------------------
### Config Methods
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/configs.html
Provides details on the methods available within the `Config` class for managing configurations.
```APIDOC
## Config Methods
### get_config
#### Description
Get config for specific dataset.
#### Parameters
* **dataset_name** (str) - Dataset name.
* **config** (ConfigType) - The config for all datasets. `value = full_config[config_file][key][dataset_name]`. Defaults to `self.full_config`.
* **kwargs** (dict) - Additional keyword arguments.
#### Returns
* Param[str, Module[str, Any]] - Config for `dataset_name`. `value = full_config[config_file][key]`.
### load_config
#### Description
Load yaml or json configs from `path`.
#### Parameters
* **path** (str) - Path to config file.
#### Returns
* ConfigType - Config loaded from `path`.
### merge
#### Description
Merge different configs of `keys` in `self.config_dict`.
#### Parameters
* **keys** (list[str]) - Keys of `self.config_dict` to merge. Defaults to `['package', 'user', 'project']`.
#### Returns
* ConfigType - Merged config.
### summary
#### Description
Summary the config information.
#### Parameters
* **keys** (list[str] | str) - Keys of configs to summary. `'final'`: `self.full_config`, `'cmd'`: `self.cmd_config`, `key in self.config_dict.keys()`. Defaults to `['final']`.
* **config** (ConfigType) - The config to summarize. Defaults to `self.full_config`.
* **indent** (int) - The space indent of entire string. Defaults to `0`.
```
--------------------------------
### Python Test Module Docstring
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/lists_tables.html
Example of a Python docstring formatted for Sphinx, demonstrating reST within a docstring for a test module.
```python
1# -*- coding: utf-8 -*-
2"""Test Module for sphinx_rtd_theme."""
3
4
5class Foo:
6
7 """Docstring for class Foo.
8
9 This text tests for the formatting of docstrings generated from output
10 ``sphinx.ext.autodoc``. Which contain reST, but sphinx nests it in the
```
--------------------------------
### Create Attack Instance
Source: https://ain-soph.github.io/trojanzoo/trojanvision/attacks/index.html
Instantiates an attack object using provided configuration and parameters.
```python
trojanvision.attacks.create(_attack_name =None_, _attack =None_, _dataset_name =None_, _dataset =None_, _model_name =None_, _model =None_, _config =config_, _class_dict =class_dict_, _** kwargs_)[source]
```
--------------------------------
### Load Configuration File
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/configs.html
Loads configuration settings from a YAML or JSON file located at the specified path. This is a static method within the Config class.
```python
_static _load_config(_path_)[source]
Load yaml or json configs from `path`.
Parameters:
**path** (_str_) – Path to config file.
Returns:
_ConfigType_ – Config loaded from `path`.
```
--------------------------------
### Get Class Subset from Dataset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Extracts a subset of a dataset containing only specified classes. Ensure the dataset and class list are correctly formatted.
```python
>>> from trojanzoo.utils.data import TensorListDataset
>>> from trojanzoo.utils.data import get_class_subset
>>> import torch
>>>
>>> data = torch.ones(11, 3, 32, 32)
>>> targets = list(range(11))
>>> dataset = TensorListDataset(data, targets)
>>> subset = get_class_subset(dataset, class_list=[2, 3])
>>> len(subset)
2
```
--------------------------------
### Get Dataset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Retrieves a dataset, optionally splitting the training set if `valid_set` is False. Supports specifying a random seed and a list of classes to include.
```python
get_dataset(_mode =None_, _seed =None_, _class_list =None_, _** kwargs_)
```
--------------------------------
### Initialize TensorListDataset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/data.html
Creates a dataset from a torch.Tensor and a list of labels. Inherits from torch.utils.data.Dataset.
```python
>>> import torch
>>> from trojanzoo.utils.data import TensorListDataset
>>>
>>> data = torch.ones(10, 3, 32, 32)
>>> targets = list(range(10))
>>> dataset = TensorListDataset(data, targets)
>>> x, y = dataset[3]
>>> x.shape
torch.Size([3, 32, 32])
>>> y
3
```
--------------------------------
### Initialize ENAS Model
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/nas.html
Instantiate an ENAS model. This implementation relies on pre-generated ENAS macro files. It is recommended to use DARTS with 'enas' model_arch instead.
```python
trojanvision.models.ENAS(_name ='enas'_, _model =_ENAS_, _folder_path =None_, _** kwargs_)
```
--------------------------------
### Get All Intermediate Layer Outputs
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/model.html
Captures outputs from all intermediate layers of a PyTorch module for a given input tensor. Allows filtering of layer types and control over traversal depth and verbosity.
```python
>>> import torch
>>> import torchvision
>>> from trojanzoo.utils.model import get_all_layer
>>>
>>> model = torchvision.models.densenet121()
```
--------------------------------
### trojanzoo.trainer.create
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/trainer.html
Creates a trainer instance with specified configurations.
```APIDOC
## POST /api/users
### Description
Creates a trainer instance.
For arguments not included in `kwargs`, use the default values in `config`.
For trainer implementation, see `Trainer`.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Path Parameters
- **dataset_name** (str) - Optional - The dataset name.
- **dataset** (str | trojanzoo.datasets.Dataset) - Optional - Dataset instance (required for `model_ema`) or dataset name (as the alias of dataset_name).
- **model** (trojanzoo.models.Model) - Optional - Model instance.
- **model_ema** (bool) - Optional - Whether to use `ExponentialMovingAverage`. Defaults to `False`.
- **pre_conditioner** (str) - Optional - Choose from `None`, `'kfac'`, `'ekfac'`. Defaults to `None`.
- **tensorboard** (bool) - Optional - Whether to use `torch.utils.tensorboard.writer.SummaryWriter`. Defaults to `False`.
- **ClassType** (type[Trainer]) - Optional - The trainer class type. Defaults to `Trainer`.
- **config** (Config) - Optional - The default parameter config.
- ****kwargs** (dict) - Optional - The keyword arguments in keys of `['optim_args', 'train_args', 'writer_args']`.
### Request Body
```json
{
"example": "request body"
}
```
### Response
#### Success Response (200)
- **trainer_instance** (Trainer) - The created trainer instance.
#### Response Example
```json
{
"example": "response body"
}
```
```
--------------------------------
### Get Loss Weights
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Calculates loss weights as the reciprocal of class data size to address data imbalance. It can load weights from a file if they exist, otherwise, it calculates, saves, and returns them.
```python
get_loss_weights(_file_path =None_, _verbose =True_)
```
--------------------------------
### ImageSet Class Initialization
Source: https://ain-soph.github.io/trojanzoo/trojanvision/datasets/index.html
Initializes the basic ImageSet class for image datasets. Users should prefer the create() function for a more user-friendly experience.
```python
_class _trojanvision.datasets.ImageSet(_norm_par =None_, _normalize =False_, _transform =None_, _auto_augment =False_, _mixup =False_, _mixup_alpha =0.0_, _cutmix =False_, _cutmix_alpha =0.0_, _cutout =False_, _cutout_length =None_, _** kwargs_)
```
--------------------------------
### Get Layer Names from Module
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/model.html
Retrieves a list of layer names from a PyTorch module. Supports filtering by depth, adding prefixes, and controlling whether to include non-leaf nodes or only traverse sequential containers.
```python
>>> import torchvision
>>> from trojanzoo.utils.model import get_layer_name
>>>
>>> model = torchvision.models.resnet18()
>>> get_layer_name(model, depth=0)
[]
>>> get_layer_name(model, depth=1)
['conv1', 'maxpool', 'layer1', 'layer2',
'layer3', 'layer4', 'avgpool', 'fc']
>>> get_layer_name(model, depth=2, prefix='model')
['model.conv1', 'model.maxpool', 'model.layer1.0', 'model.layer1.1',
'model.layer2.0', 'model.layer2.1', 'model.layer3.0', 'model.layer3.1',
'model.layer4.0', 'model.layer4.1', 'model.avgpool', 'model.fc']
>>> get_layer_name(model, seq_only=True)
['conv1', 'maxpool', 'layer1.0', 'layer1.1', 'layer2.0', 'layer2.1',
'layer3.0', 'layer3.1', 'layer4.0', 'layer4.1', 'avgpool', 'fc']
>>> get_layer_name(model, seq_only=True, non_leaf=True)
['conv1', 'maxpool',
'layer1.0', 'layer1.1', 'layer1',
'layer2.0', 'layer2.1', 'layer2',
'layer3.0', 'layer3.1', 'layer3',
'layer4.0', 'layer4.1', 'layer4',
'avgpool', 'fc']
>>> get_layer_name(model)
['conv1', 'maxpool',
'layer1.0.conv1', 'layer1.0.conv2', 'layer1.1.conv1', 'layer1.1.conv2',
'layer2.0.conv1', 'layer2.0.conv2', 'layer2.0.downsample.0', 'layer2.1.conv1', 'layer2.1.conv2',
'layer3.0.conv1', 'layer3.0.conv2', 'layer3.0.downsample.0', 'layer3.1.conv1', 'layer3.1.conv2',
'layer4.0.conv1', 'layer4.0.conv2', 'layer4.0.downsample.0', 'layer4.1.conv1', 'layer4.1.conv2',
'avgpool', 'fc']
```
--------------------------------
### Initialize InputAwareDynamic Attack
Source: https://ain-soph.github.io/trojanzoo/trojanvision/attacks/backdoor/dynamic.html
Constructor for the InputAwareDynamic attack class. Requires parameters for mask density, poison percentage, and loss coefficients.
```python
_class _trojanvision.attacks.InputAwareDynamic(_train_mask_epochs =25_, _lambda_div =1.0_, _lambda_norm =100.0_, _mask_density =0.032_, _cross_percent =0.1_, _natural =False_, _poison_percent =0.1_, _** kwargs_)[source]
```
--------------------------------
### Initialize PNASNet Model
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/nas.html
Instantiate a PNASNet model. Note that this implementation is imported from a third-party repository and correctness is not guaranteed.
```python
trojanvision.models.PNASNet(_name ='pnasnet'_, _layer ='_b'_, _model =_PNASNet_, _** kwargs_)
```
--------------------------------
### Print Module Summary
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/model.html
Displays a summary of a PyTorch module structure, similar to Keras model summary.
```python
>>> import torchvision
>>> from trojanzoo.utils.model import summary
>>>
>>> model=torchvision.models.resnet18()
>>> summary(model)
>>> summary(model, depth=1)
```
--------------------------------
### List available ShuffleNetV2 model names
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/torchvision.html
Displays the set of available model configuration names for the ShuffleNetV2 architecture.
```python
{'shufflenet_v2', 'shufflenet_v2_comp',
'shufflenet_v2_x0_5', 'shufflenet_v2_x1_0',
'shufflenet_v2_x1_5', 'shufflenet_v2_x2_0',
'shufflenet_v2_x0_5_comp', 'shufflenet_v2_x1_0_comp',
'shufflenet_v2_x1_5_comp', 'shufflenet_v2_x2_0_comp'}
```
--------------------------------
### List Available MagNet Model Names
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/others.html
Displays the set of available model names for the MagNet implementation.
```python
{'magnet'}
```
--------------------------------
### Using Lock Context Manager
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/index.html
Demonstrates the usage of the Lock class as a context manager to control access and avoid auxiliary computations. The lock state changes within the 'with' block.
```python
>>> from trojanzoo.utils.lock import Lock
>>>
>>> track = Lock()
>>> print(bool(track))
False
>>> with track():
>>> print(bool(track))
True
>>> print(bool(track))
False
>>> track.enable()
>>> print(bool(track))
True
>>> track.disable()
>>> print(bool(track))
False
```
--------------------------------
### ImageSet Methods
Source: https://ain-soph.github.io/trojanzoo/trojanvision/datasets/index.html
Documentation for utility methods within the ImageSet class.
```APIDOC
## ImageSet Methods
### get_transform
#### Description
Get dataset transform based on `self.transform`.
- `None |'none'` (`torchvision.transforms.PILToTensor` and `torchvision.transforms.ConvertImageDtype`)
- `'bit'` (transform used in BiT network)
- `'pytorch'` (pytorch transform used in ImageNet training).
#### Parameters
- **mode** (str) – The dataset mode (e.g., `'train' | 'valid'`).
- **normalize** (bool | None) – Whether to use `torchvision.transforms.Normalize` in dataset transform. Defaults to `self.normalize`.
#### Returns
- `torchvision.transforms.Compose` – The transform sequence.
### make_folder
#### Description
Save the dataset to `self.folder_path` as `trojanvision.datasets.ImageFolder` format.
`'{self.folder_path}/{self.name}/{mode}/{class_name}/{img_idx}.png'`
#### Parameters
- **img_type** (str) – The image types to save. Defaults to `'.png'`.
```
--------------------------------
### Create meters for MetricLogger
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/logger.html
Initializes specific meters within the MetricLogger instance. Each meter is an instance of SmoothedValue, configured with a provided format string.
```python
self.meters[meter_name] = SmoothedValue(fmt=fmt)
```
--------------------------------
### Class: DotpayProvider
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/demo/api.html
Documentation for the DotpayProvider class, which implements payments using the Dotpay.pl gateway.
```APIDOC
## Class _payments.dotpay.DotpayProvider(_seller_id_ , _pin_[, _channel=0_[, _lock=False_], _lang='pl'_])
### Description
This backend implements payments using a popular Polish gateway, Dotpay.pl.
Due to API limitations there is no support for transferring purchased items.
### Parameters:
* **seller_id** – Seller ID assigned by Dotpay
* **pin** – PIN assigned by Dotpay
* **channel** – Default payment channel (consult reference guide)
* **lang** – UI language
* **lock** – Whether to disable channels other than the default selected above
```
--------------------------------
### Sample Batch from Dataset
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/data.html
Samples a batch of data and targets from a dataset, either by specific indices or by random sampling with a batch size.
```python
>>> import torch
>>> from trojanzoo.utils.data import TensorListDataset, sample_batch
>>>
>>> data = torch.ones(10, 3, 32, 32)
>>> targets = list(range(10))
>>> dataset = TensorListDataset(data, targets)
>>> x, y = sample_batch(dataset, idx=[1, 2])
>>> x.shape
torch.Size([2, 3, 32, 32])
>>> y
tensor([1, 2])
>>> x, y = sample_batch(dataset, batch_size=4)
>>> y
tensor([6, 3, 2, 5])
```
--------------------------------
### Run Backdoor Defense Workflow
Source: https://ain-soph.github.io/trojanzoo/tutorials/basic.html
This script demonstrates the basic workflow for detecting backdoor attacks using TrojanZoo. It parses arguments for environment, dataset, model, trainer, marks, attacks, and defenses, then initializes and runs the defense detection process.
```python
#!/usr/bin/env python3
# CUDA_VISIBLE_DEVICES=0 python ./examples/backdoor_defense.py --color --verbose 1 --attack badnet --defense neural_cleanse --pretrained --validate_interval 1 --epochs 50 --lr 1e-2
import trojanvision
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
trojanvision.environ.add_argument(parser)
trojanvision.datasets.add_argument(parser)
trojanvision.models.add_argument(parser)
trojanvision.trainer.add_argument(parser)
trojanvision.marks.add_argument(parser)
trojanvision.attacks.add_argument(parser)
trojanvision.defenses.add_argument(parser)
kwargs = parser.parse_args().__dict__
env = trojanvision.environ.create(**kwargs)
dataset = trojanvision.datasets.create(**kwargs)
model = trojanvision.models.create(dataset=dataset, **kwargs)
trainer = trojanvision.trainer.create(dataset=dataset, model=model, **kwargs)
mark = trojanvision.marks.create(dataset=dataset, **kwargs)
attack = trojanvision.attacks.create(dataset=dataset, model=model, mark=mark, **kwargs)
defense = trojanvision.defenses.create(dataset=dataset, model=model, attack=attack, **kwargs)
if env['verbose']:
trojanvision.summary(env=env, dataset=dataset, model=model, mark=mark, trainer=trainer, attack=attack, defense=defense)
defense.detect(**trainer)
```
--------------------------------
### trojanvision.models.NATSbench
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/nas.html
Initializes a NATS-Bench model for benchmarking NAS algorithms.
```APIDOC
## NATS-Bench Model Initialization
### Description
NATS-Bench proposed by Xuanyi Dong from University of Technology Sydney.
### Parameters
- **model_index** (int) - Optional - model_index passed to api.get_net_config(). Ranging from 0 to 15624. Defaults to 0.
- **model_seed** (int) - Optional - model_seed passed to api.get_net_param(). Choose from [777, 888, 999]. Defaults to 777.
- **hp** (int) - Optional - Training epochs. Choose from [12, 200]. Defaults to 200.
- **nats_path** (str) - Optional - NATS benchmark file path.
- **search_space** (str) - Optional - Search space of topology or size. Choose from ['tss', 'sss'].
- **dataset_name** (str) - Optional - Dataset name. Choose from ['cifar10', 'cifar10-valid', 'cifar100', 'imagenet16-120'].
```
--------------------------------
### Define TrojanVision Config Paths
Source: https://ain-soph.github.io/trojanzoo/trojanvision/configs.html
Defines dictionary keys for package, user, and project configuration paths. Use this to locate configuration files.
```python
config_path: dict[str, str] = {
'package': os.path.dirname(__file__), # trojanvision/configs/*/*.yml
'user': os.path.normpath(os.path.expanduser('~/.trojanzoo/configs/trojanvision')),
'project': os.path.normpath('./configs/trojanvision'),
}
```
--------------------------------
### Initialize DARTS Model
Source: https://ain-soph.github.io/trojanzoo/trojanvision/models/nas.html
Instantiate a DARTS-like model for Neural Architecture Search. Configure parameters like model architecture, number of layers, and dropout probability.
```python
trojanvision.models.DARTS(_name ='darts'_, _model_arch ='darts'_, _layers =20_, _init_channels =36_, _dropout_p =0.2_, _auxiliary =False_, _auxiliary_weight =0.4_, _genotype =None_, _model =_DARTS_, _supernet =False_, _arch_search =False_, _use_full_train_set =False_, _arch_lr =3e-4_, _arch_weight_decay =1e-3_, _arch_unrolled =False_, _primitives =PRIMITIVES_, _** kwargs_)
```
--------------------------------
### Index - test_py_module.test.Foo Methods and Attributes
Source: https://ain-soph.github.io/trojanzoo_sphinx_theme/genindex.html
API documentation for methods and attributes within the Foo class of the test_py_module.test module.
```APIDOC
## Index
### `__init__()` (test_py_module.test.Foo method)
### `__weakref__` (test_py_module.test.Foo attribute)
### `add()` (test_py_module.test.Foo method)
### `another_function()` (test_py_module.test.Foo method)
### `bar` (test_py_module.test.Foo attribute)
### `baz` (test_py_module.test.Foo attribute)
### `capitalize()` (test_py_module.test.Foo method)
### `flox` (test_py_module.test.Foo attribute)
### `qux` (test_py_module.test.Foo attribute)
### `spam` (test_py_module.test.Foo attribute)
```
--------------------------------
### Check Dataset Files
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/datasets.html
Verify if the necessary dataset files are present. This method can accept keyword arguments passed to `get_org_dataset()`.
```python
check_files(_** kwargs_)
```
--------------------------------
### Env Class
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/environ.html
Represents the environment settings and variables.
```APIDOC
## Class: trojanzoo.environ.Env
### Description
The dict-like environment class that inherits `trojanzoo.utils.module.Param`. It should be singleton in most cases.
Warning: There is already an environ instance `trojanzoo.environ.env`. Call `create()` to set its value. NEVER call the class init method to create a new instance (unless you know what you’re doing).
### Parameters
- **device** (str | device) - Optional - Defaults to 'auto'. Can be 'auto' (use gpu if available), 'cpu', or 'gpu' | 'cuda'.
- **kwargs** - Additional keyword arguments.
### Variables
- **color** (bool) - Whether to show colorful outputs in console using ASNI escape characters. Defaults to `False`.
- **num_gpus** (int) - Number of available GPUs.
- **tqdm** (bool) - Whether to use `tqdm.tqdm` to show progress bar. Defaults to `False`.
- **verbose** (int) - The output level. Defaults to `0`.
- **cudnn_benchmark** (bool) - Whether to use `torch.backends.cudnn.benchmark` to accelerate without deterministic. Defaults to `False`.
- **cache_threshold** (float) - The threshold (MB) to call `torch.cuda.empty_cache`. Defaults to `None` (never).
- **seed** (int) - The random seed for numpy, torch and cuda.
- **data_seed** (int) - Seed to process data (e.g., `trojanzoo.datasets.Dataset.split_dataset()`)
- **device** (device) - The default device to store tensors.
- **world_size** (int) - Number of distributed machines. Defaults to `1`.
### Methods
- **add_argument**(_group_)
Adds environ arguments to argument parser group. View source to see specific arguments. Note: This is the implementation of adding arguments. For users, please use `add_argument()` instead, which is more user-friendly.
```
--------------------------------
### init_weights
Source: https://ain-soph.github.io/trojanzoo/trojanzoo/utils/model.html
Traverse a module to initialize weights of all submodules except for those specified in a filter list.
```APIDOC
## init_weights
### Description
Traverse module `m` to initialize weights of all submodules except for those in `filter_list`. Module parameters are reset by calling `module.reset_parameters()`.
### Parameters
- **m** (torch.nn.Module) - Required - Module to initialize.
- **filter_list** (tuple[type]) - Optional - List of submodule types as exceptions. Defaults to [].
```