-
Notifications
You must be signed in to change notification settings - Fork 737
Added cflow algorithm #47
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
Merged
Merged
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
44cd135
Added cflow algorithm
blakshma efece38
added cflow reqs
samet-akcay 04d1610
changing default image size
blakshma 52399fa
revert image size and delete resume from checkpoint
blakshma 9f95b20
removed reference to github
blakshma 82192aa
reducing batch size for training and inference
blakshma 6b632bf
decreasing fiber batch size
blakshma fa1b4df
Added cflow algorithm
blakshma 7e3a369
added cflow reqs
samet-akcay cdcf489
changing default image size
blakshma 5c7240d
revert image size and delete resume from checkpoint
blakshma 8219029
removed reference to github
blakshma 8d4c17a
reducing batch size for training and inference
blakshma 83e1bb2
decreasing fiber batch size
blakshma 1e0d605
reducing patience for quicker convergence
blakshma 8547c39
Merge branch 'algo/barath/cflow' of github.com:openvinotoolkit/anomal…
blakshma 5971542
updating config file
blakshma 3df4924
Merge branch 'development' of github.com:openvinotoolkit/anomalib int…
samet-akcay 860c490
fixing checkpoint issue, added normalization param
blakshma 2308c64
rolling back to resnet18
blakshma f1eb5f0
perform metric computation on cpu
djdameln 3977a5d
normalization on cpu
djdameln c155a21
round performance comparison
samet-akcay 30b6b51
Merge branch 'fix/da/cpu-metric-computation' of github.com:openvinoto…
samet-akcay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Real-Time Unsupervised Anomaly Detection via Conditional Normalizing Flows | ||
|
||
This is the implementation of the [CW-AD](https://arxiv.org/pdf/2107.12571v1.pdf) paper. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
"""Real-Time Unsupervised Anomaly Detection via Conditional Normalizing Flows. | ||
|
||
[CW-AD](https://arxiv.org/pdf/2107.12571v1.pdf) | ||
""" | ||
|
||
# Copyright (C) 2020 Intel Corporation | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions | ||
# and limitations under the License. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
"""Helper functions to create backbone model.""" | ||
|
||
# Copyright (C) 2020 Intel Corporation | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions | ||
# and limitations under the License. | ||
|
||
import math | ||
|
||
import FrEIA.framework as Ff | ||
import FrEIA.modules as Fm | ||
import torch | ||
from FrEIA.framework.sequence_inn import SequenceINN | ||
from torch import nn | ||
|
||
|
||
def positional_encoding_2d(condition_vector: int, height: int, width: int) -> torch.Tensor: | ||
"""Creates embedding to store relative position of the feature vector using sine and cosine functions. | ||
|
||
Args: | ||
condition_vector (int): Length of the condition vector | ||
height (int): H of the positions | ||
width (int): W of the positions | ||
|
||
Raises: | ||
ValueError: Cannot generate encoding with conditional vector length not as multiple of 4 | ||
|
||
Returns: | ||
torch.Tensor: condition_vector x HEIGHT x WIDTH position matrix | ||
""" | ||
if condition_vector % 4 != 0: | ||
raise ValueError(f"Cannot use sin/cos positional encoding with odd dimension (got dim={condition_vector})") | ||
pos_encoding = torch.zeros(condition_vector, height, width) | ||
# Each dimension use half of condition_vector | ||
condition_vector = condition_vector // 2 | ||
div_term = torch.exp(torch.arange(0.0, condition_vector, 2) * -(math.log(1e4) / condition_vector)) | ||
pos_w = torch.arange(0.0, width).unsqueeze(1) | ||
pos_h = torch.arange(0.0, height).unsqueeze(1) | ||
pos_encoding[0:condition_vector:2, :, :] = ( | ||
torch.sin(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1) | ||
) | ||
pos_encoding[1:condition_vector:2, :, :] = ( | ||
torch.cos(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1) | ||
) | ||
pos_encoding[condition_vector::2, :, :] = ( | ||
torch.sin(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width) | ||
) | ||
pos_encoding[condition_vector + 1 :: 2, :, :] = ( | ||
torch.cos(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width) | ||
) | ||
return pos_encoding | ||
|
||
|
||
def subnet_fc(dims_in: int, dims_out: int): | ||
"""Subnetwork which predicts the affine coefficients. | ||
|
||
Args: | ||
dims_in (int): input dimensions | ||
dims_out (int): output dimensions | ||
|
||
Returns: | ||
nn.Sequential: Feed-forward subnetwork | ||
""" | ||
return nn.Sequential(nn.Linear(dims_in, 2 * dims_in), nn.ReLU(), nn.Linear(2 * dims_in, dims_out)) | ||
|
||
|
||
def cflow_head(condition_vector: int, coupling_blocks: int, clamp_alpha: float, n_features: int) -> SequenceINN: | ||
"""Create invertible decoder network. | ||
|
||
Args: | ||
condition_vector (int): length of the condition vector | ||
coupling_blocks (int): number of coupling blocks to build the decoder | ||
clamp_alpha (float): clamping value to avoid exploding values | ||
n_features (int): number of decoder features | ||
|
||
Returns: | ||
SequenceINN: decoder network block | ||
""" | ||
coder = Ff.SequenceINN(n_features) | ||
print("CNF coder:", n_features) | ||
for _ in range(coupling_blocks): | ||
coder.append( | ||
Fm.AllInOneBlock, | ||
cond=0, | ||
cond_shape=(condition_vector,), | ||
subnet_constructor=subnet_fc, | ||
affine_clamping=clamp_alpha, | ||
global_affine_type="SOFTPLUS", | ||
permute_soft=True, | ||
) | ||
return coder |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
dataset: | ||
name: mvtec | ||
format: mvtec | ||
path: ./datasets/MVTec | ||
url: ftp://guest:[email protected]/mvtec_anomaly_detection/mvtec_anomaly_detection.tar.xz | ||
category: leather | ||
task: segmentation | ||
label_format: None | ||
image_size: 256 | ||
train_batch_size: 16 | ||
test_batch_size: 16 | ||
inference_batch_size: 16 | ||
fiber_batch_size: 64 | ||
num_workers: 36 | ||
|
||
model: | ||
name: cflow | ||
backbone: resnet18 | ||
layers: | ||
- layer2 | ||
- layer3 | ||
- layer4 | ||
decoder: freia-cflow | ||
condition_vector: 128 | ||
coupling_blocks: 8 | ||
clamp_alpha: 1.9 | ||
lr: 0.0001 | ||
early_stopping: | ||
patience: 3 | ||
metric: pixel_AUROC | ||
mode: max | ||
normalization_method: min_max # options: [null, min_max, cdf] | ||
threshold: | ||
image_default: 0 | ||
pixel_default: 0 | ||
adaptive: true | ||
|
||
project: | ||
seed: 0 | ||
path: ./results | ||
log_images_to: [local] | ||
logger: false | ||
save_to_csv: false | ||
|
||
# PL Trainer Args. Don't add extra parameter here. | ||
trainer: | ||
accelerator: null | ||
accumulate_grad_batches: 1 | ||
amp_backend: native | ||
amp_level: O2 | ||
auto_lr_find: false | ||
auto_scale_batch_size: false | ||
auto_select_gpus: false | ||
benchmark: false | ||
check_val_every_n_epoch: 1 | ||
checkpoint_callback: true | ||
default_root_dir: null | ||
deterministic: true | ||
distributed_backend: null | ||
fast_dev_run: false | ||
flush_logs_every_n_steps: 100 | ||
gpus: 1 | ||
gradient_clip_val: 0 | ||
limit_predict_batches: 1.0 | ||
limit_test_batches: 1.0 | ||
limit_train_batches: 1.0 | ||
limit_val_batches: 1.0 | ||
log_every_n_steps: 50 | ||
log_gpu_memory: null | ||
max_epochs: 50 | ||
max_steps: null | ||
min_epochs: null | ||
min_steps: null | ||
move_metrics_to_cpu: false | ||
multiple_trainloader_mode: max_size_cycle | ||
num_nodes: 1 | ||
num_processes: 1 | ||
num_sanity_val_steps: 0 | ||
overfit_batches: 0.0 | ||
plugins: null | ||
precision: 32 | ||
prepare_data_per_node: true | ||
process_position: 0 | ||
profiler: null | ||
progress_bar_refresh_rate: null | ||
reload_dataloaders_every_epoch: false | ||
replace_sampler_ddp: true | ||
stochastic_weight_avg: false | ||
sync_batchnorm: false | ||
terminate_on_nan: false | ||
tpu_cores: null | ||
track_grad_norm: -1 | ||
truncated_bptt_steps: null | ||
val_check_interval: 1.0 | ||
weights_save_path: null | ||
weights_summary: top |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you have sample results? It would be nice to include them here for consistency with other tasks. Here is an example https://github.com/openvinotoolkit/anomalib/blob/development/anomalib/models/stfpm/README.md
Otherwise, can you create a ticket for it to address this in a different PR.