Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Video tracking integration #1170

Merged
merged 26 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
8bd1c16
full dev dataset for CARLA video tracking scenario
yusong-tan Oct 12, 2021
08abe89
ran black and flake8
yusong-tan Oct 12, 2021
eec92cf
baseline GOTURN model for CARLA video tracking scenario
yusong-tan Oct 12, 2021
16bf7a0
art_experimental adversarial texture attack for CARLA video tracking …
yusong-tan Oct 12, 2021
02a285a
Merge branch 'dev' of https://github.com/twosixlabs/armory into dev_v…
Oct 14, 2021
6ca7391
integrating carla_video_tracking_dev, pushing progress
Oct 15, 2021
f3071e5
forgot to add these files to previous commit
Oct 15, 2021
c22bca5
Merge remote-tracking branch 'upstream/dev' into dev_video_tracking_d…
Oct 15, 2021
8510b3f
adding cached checksum
Oct 15, 2021
d38a7a7
adding test
Oct 17, 2021
fe81f52
Merge remote-tracking branch 'yusong-tan/dev_video_tracking_baseline_…
Oct 17, 2021
3c25815
pushing progress on added scenario, config, metric
Oct 18, 2021
90fd317
typos and formatting
Oct 18, 2021
97bc0d3
refactoring, define pred format, point to weights file; can now run -…
Oct 18, 2021
335c7b7
Merge remote-tracking branch 'yusong-tan/dev_video_tracking_attack' i…
Oct 18, 2021
d33f611
to comply with ART, refactor label format to mirror pred format; got …
Oct 18, 2021
bf4f21e
renaming config
Oct 18, 2021
2e6156c
formatting
Oct 18, 2021
811a14c
Merge branch 'dev_video_tracking_dev_dataset' of github.com:yusong-ta…
Oct 18, 2021
64561c3
adding updated tf1 dockerfile to fix ci tests
Oct 18, 2021
77ebba7
update tests to reflect label refactor
Oct 18, 2021
6d32b5f
adding test for carla video tracking model
Oct 18, 2021
023c050
remove unused variables
Oct 18, 2021
d0743f6
update pytorch Dockerfile to use newer ART
Oct 19, 2021
923d11d
Merge branch 'dev' of https://github.com/twosixlabs/armory into dev_v…
Oct 21, 2021
04f52a8
download external_repo in video_tracking test
Oct 21, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions armory/art_experimental/attacks/carla_adversarial_texture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import logging
import numpy as np
import torch

from art.attacks.evasion import AdversarialTexturePyTorch

logger = logging.getLogger(__name__)


class AdversarialPhysicalTexture(AdversarialTexturePyTorch):
"""
ART's AdversarialTexturePytorch with overriden generate()
"""

def __init__(self, estimator, **kwargs):
super().__init__(estimator=estimator, **kwargs)

def generate(self, x, y, y_patch_metadata=None, **kwargs):
"""
:param x: Sample videos with shape (NFHWC)
:param y: True labels of format `List[Dict[str, np.ndarray]]`, one dictionary for each input video. The keys of
the dictionary are:
- boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and
0 <= y1 < y2 <= H.
:param y_patch_metadata: Metadata of the green screen patch of format `List[Dict[str, np.ndarray]]`. The keys of
the dictionary are:
- gs_coords: the coordinates of the patch in [top_left, top_right, bottom_right, bottom_left] format
- cc_ground_truth: ground truth color information stored as np.ndarray with shape (24,3)
- cc_scene: scene color information stored as np.ndarray with shape (24,3)
- masks: binarized masks of the patch, where masks[n,x,y] == 1 means patch pixel in frame n and at position (x,y)
:Keyword Arguments:
* *shuffle* (``np.ndarray``) --
Shuffle order of samples, labels, initial boxes, and foregrounds for texture generation.
* *y_init* (``np.ndarray``) --
Initial boxes around object to be tracked of shape (nb_samples, 4) with second dimension representing
[x1, y1, x2, y2] with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.
* *foreground* (``np.ndarray``) --
Foreground masks of shape NFHWC of boolean values with False/0.0 representing foreground, preventing
updates to the texture, and True/1.0 for background, allowing updates to the texture.
:return: An array with adversarial patch and an array of the patch mask.
"""

if x.shape[0] > 1:
raise ValueError("batch size must be 1")

self.y_patch_metadata = y_patch_metadata

# this masked to embed patch into the background in the event of occlusion
foreground = y_patch_metadata[0]["masks"]
foreground = np.array([foreground])

# green screen coordinates used for placement of a rectangular patch
gs_coords = y_patch_metadata[0]["gs_coords"]

patch_width = np.max(gs_coords[:, 0]) - np.min(gs_coords[:, 0])
patch_height = np.max(gs_coords[:, 1]) - np.min(gs_coords[:, 1])

self.x_min = np.min(gs_coords[:, 0])
self.y_min = np.min(gs_coords[:, 1])
self.patch_height = patch_height
self.patch_width = patch_width

# Re-initialize some internal parameters
self.patch_shape = (self.patch_height, self.patch_width, 3)

if not (
self.estimator.postprocessing_defences is None
or self.estimator.postprocessing_defences == []
):
raise ValueError(
"Framework-specific implementation of Adversarial Patch attack does not yet support "
+ "postprocessing defences."
)

mean_value = (
self.estimator.clip_values[1] - self.estimator.clip_values[0]
) / 2.0 + self.estimator.clip_values[0]
self._initial_value = np.ones(self.patch_shape) * mean_value
self._patch = torch.tensor(
self._initial_value, requires_grad=True, device=self.estimator.device
)

attack_kwargs = {
"y_init": y[0]["boxes"][0:1],
"foreground": foreground,
"shuffle": kwargs.get("shuffle", False),
}

attacked_video = super().generate(x, y, **attack_kwargs)

return attacked_video
43 changes: 43 additions & 0 deletions armory/baseline_models/pytorch/carla_goturn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import torch
from typing import Optional
import numpy as np
from art.estimators.object_tracking import PyTorchGoturn

# Load model from MITRE external repo: https://github.com/yusong-tan/pygoturn
# This needs to be defined in your config's `external_github_repo` field to be
# downloaded and placed on the PYTHONPATH
from pygoturn.src.model import GoNet # clone from https://github.com/amoudgl/pygoturn

# load amoudgl model and instantiate ART PyTorchGoTurn model
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")


# NOTE: PyTorchGoturn expects numpy input, not torch.Tensor input
def get_art_model(
model_kwargs: dict, wrapper_kwargs: dict, weights_path: Optional[str] = None
) -> PyTorchGoturn:

model = GoNet()

if weights_path:
checkpoint = torch.load(weights_path, map_location=lambda storage, loc: storage)
model.load_state_dict(checkpoint["state_dict"])
model = model.to(DEVICE)

wrapped_model = PyTorchGoturn(
model=model,
input_shape=(
3,
224,
224,
), # GoNet() uses this parameter but expects input to actually have shape (HW3)
clip_values=(0.0, 1.0),
channels_first=False,
preprocessing=(
np.array([0.485, 0.456, 0.406]),
np.array([0.229, 0.224, 0.225]),
), # ImageNet means/stds
**wrapper_kwargs,
)

return wrapped_model
Loading