Skip to content
This repository was archived by the owner on Jul 21, 2023. It is now read-only.

Commit 7cbc3ba

Browse files
payotogithub-actions[bot]evawoodbridge
authored
Add yolo v4 config (#16)
* Add copy ci action to Pytorch repo * Add yolo v4 config * Remove test and CI references * Remove readme * [GH-Actions] Add new files from specs (#17) .github/deployment-configs/deploy-yolo-notebook.yaml Co-authored-by: Alexandre <18074599+payoto@users.noreply.github.com> * Add test entry * [GH-Actions] Add modified files from specs (#18) .github/deployment-configs/deploy-yolo-notebook.yaml Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Downgrade torch requirement * loosen old requirements * Modified files for add-yolo-notebook (#19) * [GH-Actions] Add modified files from specs .github/deployment-configs/deploy-yolo-notebook.yaml * Update object-detection-with-yolo/requirements.txt --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Alexandre Payot <18074599+payoto@users.noreply.github.com> * Modified files for add-yolo-notebook (#20) * [GH-Actions] Add modified files from specs .github/deployment-configs/deploy-yolo-notebook.yaml * [GH-Actions] Add new files from specs .github/deployment-configs/deploy-yolo-notebook.yaml --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Remove unnecessary files * Loosen requirements * Downgrade torch requirements * Add run on gradient button with shortened link --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: evawGraphcore <110815532+evawGraphcore@users.noreply.github.com>
1 parent f1628d1 commit 7cbc3ba

43 files changed

Lines changed: 6965 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
_examples_internal_repository: &_examples_internal_repository
2+
origin: examples-internal/
3+
ref: null
4+
5+
_current_repo_in_github_actions: &_current_repo_in_github_actions
6+
origin: notebooks/
7+
ref: null
8+
9+
yolov4-object-detection:
10+
source:
11+
paths:
12+
- expression: '*'
13+
path: vision/yolo_v4/pytorch
14+
recursive: true
15+
repository:
16+
origin: examples-internal/
17+
ref: yolo-notebook
18+
prefix: vision/yolo_v4/pytorch
19+
excludes:
20+
- path: vision/yolo_v4/pytorch/.ci/
21+
- path: vision/yolo_v4/pytorch/conftest.py
22+
- path: vision/yolo_v4/pytorch/tests/
23+
- path: vision/yolo_v4/pytorch/README.md
24+
target:
25+
renames: {}
26+
repository:
27+
<<: *_current_repo_in_github_actions
28+
prefix: object-detection-with-yolo

.gradient/notebook-tests.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,14 @@ vit-model-training:
9898
timeout: 10000
9999
requirements_file: requirements.txt
100100

101+
object-detection-with-yolo:
102+
location: ../object-detection-with-yolo
103+
generated: true
104+
notebook:
105+
file: notebook_yolo.ipynb
106+
timeout: 3600
107+
108+
101109
# Useful references
102110
useful-managing-ipu-resources:
103111
location: ../useful-tips
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
CXX ?= g++
3+
CXXFLAGS = -std=c++14 -g -fPIC -shared -I..
4+
LDLIBS = -lpopart -lpoplar -lpopops
5+
ONNX_NAMESPACE = -DONNX_NAMESPACE=onnx
6+
7+
BUILD_DIR = utils/custom_ops/build
8+
COPY_SOURCE = utils/custom_ops/copy_tensor/copy_custom_op.cpp
9+
COPY_TARGET = $(BUILD_DIR)/copy_tensor_custom_op.so
10+
11+
NMS_DIR = utils/custom_ops/nms
12+
NMS_SOURCE = $(NMS_DIR)/nms_custom_op.cpp
13+
NMS_TARGET = $(BUILD_DIR)/nms_custom_op.so
14+
15+
all: create_build_dir copy_custom_op nms_custom_op
16+
17+
.PHONY: create_build_dir
18+
create_build_dir:
19+
mkdir -p $(BUILD_DIR)
20+
21+
copy_custom_op: $(COPY_SOURCE)
22+
$(CXX) $? $(LDLIBS) $(CXXFLAGS) $(ONNX_NAMESPACE) -o $(COPY_TARGET)
23+
24+
nms_custom_op: $(NMS_SOURCE) $(NMS_DIR)/nms.cpp $(NMS_DIR)/ipu_utils.cpp
25+
$(CXX) $? $(LDLIBS) $(CXXFLAGS) $(ONNX_NAMESPACE) -o $(NMS_TARGET)
26+
27+
.PHONY: clean
28+
clean:
29+
rm -rf $(BUILD_DIR)

object-detection-with-yolo/api.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# Copyright (c) 2023 Graphcore Ltd. All rights reserved.
2+
import yacs
3+
import torch
4+
import poptorch
5+
import numpy as np
6+
from PIL import Image
7+
from ruamel import yaml
8+
from run import ipu_options
9+
from typing import NamedTuple
10+
from typing import List, Tuple
11+
from poptorch import inferenceModel
12+
from models.yolov4_p5 import Yolov4P5
13+
from utils.config import get_cfg_defaults
14+
from torchvision.transforms import Compose
15+
from utils.visualization import plotting_tool
16+
from utils.postprocessing import post_processing
17+
from utils.tools import load_and_fuse_pretrained_weights
18+
from utils.preprocessing import ResizeImage, Pad, ToNumpy, ToTensor
19+
20+
21+
class YoloOutput(NamedTuple):
22+
x_top_left: float
23+
y_top_left: float
24+
width: float
25+
height: float
26+
detection_confidence: float
27+
detected_class_id: float
28+
detected_class_name: str
29+
30+
31+
class YOLOv4InferencePipeline:
32+
def __init__(self, checkpoint_path: str):
33+
self.cfg = get_cfg_defaults()
34+
self.config = "configs/inference-yolov4p5.yaml"
35+
self.cfg.merge_from_file(self.config)
36+
self.cfg.freeze()
37+
self.checkpoint = checkpoint_path
38+
self.model = self.prepare_inference_yolo_v4_model_for_ipu()
39+
self.class_names = yaml.safe_load(open("configs/class_name.yaml"))["class_names"]
40+
41+
def __call__(self, image: Image) -> Tuple[List[YoloOutput], List[np.array]]:
42+
transformed_image, size = self.preprocess_image(image)
43+
y = self.model(transformed_image)
44+
dummy_label = []
45+
processed_batch = post_processing(self.cfg, y, [size], dummy_label)
46+
batch_as_list = processed_batch[0][0].tolist()
47+
named_output = [
48+
YoloOutput._make(obj[0:5] + [obj[-1]] + [self.class_names[int(obj[-1])]]) for obj in batch_as_list
49+
]
50+
51+
return named_output
52+
53+
def preprocess_image(self, img: Image) -> Tuple[torch.Tensor, torch.Tensor]:
54+
height, width = img.size
55+
print("original image dimensions:\nh:", height, "w:", width)
56+
57+
img_conv = img.convert("RGB")
58+
59+
# Change the data type of the dataloader depending of the options
60+
if self.cfg.model.uint_io:
61+
image_type = "uint"
62+
elif not self.cfg.model.ipu or not self.cfg.model.half:
63+
image_type = "float"
64+
else:
65+
image_type = "half"
66+
67+
size = torch.as_tensor(img_conv.size)
68+
resize_img_mthd = ResizeImage(self.cfg.model.image_size)
69+
print("img_size: ", self.cfg.model.image_size)
70+
pad_mthd = Pad(self.cfg.model.image_size)
71+
image_to_tensor_mthd = Compose([ToNumpy(), ToTensor(int(self.cfg.dataset.max_bbox_per_scale), image_type)])
72+
dummy_label = np.array([[1.0, 1.0, 1.0, 1.0, 1.0]])
73+
transformed_image, transformed_labels = resize_img_mthd((img_conv, dummy_label))
74+
transformed_image, transformed_labels = pad_mthd((transformed_image, transformed_labels))
75+
transformed_image, transformed_labels = image_to_tensor_mthd((transformed_image, transformed_labels))
76+
transformed_image, _ = torch.unsqueeze(transformed_image, dim=0), torch.unsqueeze(transformed_labels, dim=0)
77+
78+
return transformed_image, size
79+
80+
def prepare_inference_yolo_v4_model_for_ipu(self) -> poptorch.PoplarExecutor:
81+
mode = "inference"
82+
original_model = Yolov4P5
83+
model = original_model(self.cfg)
84+
85+
# Insert the pipeline splits if using pipeline
86+
if self.cfg.model.pipeline_splits:
87+
named_layers = {name: layer for name, layer in model.named_modules()}
88+
for ipu_idx, split in enumerate(self.cfg.model.pipeline_splits):
89+
named_layers[split] = poptorch.BeginBlock(ipu_id=ipu_idx + 1, layer_to_call=named_layers[split])
90+
91+
model = load_and_fuse_pretrained_weights(model, self.checkpoint)
92+
model.optimize_for_inference()
93+
model.eval()
94+
95+
# Create the specific ipu options if self.cfg.model.ipu
96+
ipu_opts = ipu_options(self.cfg, model, mode) if self.cfg.model.ipu else None
97+
98+
model = inferenceModel(model, ipu_opts)
99+
100+
return model
101+
102+
def plot_img(self, processed_batch: List[YoloOutput], original_img: Image) -> List[str]:
103+
list_of_predictions = [torch.Tensor([list(p)[0:6] for p in processed_batch])]
104+
img_path = plotting_tool(self.cfg, list_of_predictions, [original_img])
105+
return img_path
106+
107+
def detach(self):
108+
if self.model.isAttachedToDevice():
109+
self.model.detachFromDevice()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
config_options: &config_options
3+
requirements_path: requirements.txt
4+
pre_run_commands: [make]
5+
6+
pytorch_yolov4_infer_real_pod4:
7+
<<: *config_options
8+
description:
9+
PyTorch Yolov4 inference benchmark on 4 IPUs using coco val2017 dataset
10+
parameters:
11+
- [img_size, batch_size, device_iterations, max_detections, topk_nums]
12+
- [896, 1, 5, 200, 1800]
13+
- [896, 1, 10, 300, 1468]
14+
- [640, 2, 5, 200, 1200]
15+
- [640, 2, 10, 300, 1300]
16+
- [512, 2, 5, 200, 2600]
17+
- [512, 2, 10, 300, 1400]
18+
- [416, 2, 5, 200, 3000]
19+
- [416, 4, 10, 100, 900]
20+
cmd: >-
21+
mpirun --tag-output --np 4 --allow-run-as-root
22+
python3 run.py
23+
--device-iterations {device_iterations}
24+
--image-size {img_size}
25+
--micro-batch-size {batch_size}
26+
--benchmark
27+
--mode test_inference
28+
--nms-max-detections {max_detections}
29+
--pre-nms-topk-k {topk_nums}
30+
data:
31+
throughput:
32+
regexp: 'throughput: *(.*?) samples\/sec'
33+
latency:
34+
regexp: 'latency avg: *(.*?) ms'
35+
output:
36+
- [Batchsize, "batch_size"]
37+
- [Device iterations, "device_iterations"]
38+
- [Image size, "img_size"]
39+
- [Pre-nms Topk, "topk_nums"]
40+
- [NMS max detections, "max_detections"]
41+
- [samples/sec, "throughput"]
42+
- [latency(ms), "latency"]
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class_names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
2+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
3+
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
4+
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
5+
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
6+
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
7+
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
8+
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
9+
'hair drier', 'toothbrush']
10+
coco_91_class: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
11+
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
12+
64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
system:
2+
num_ipus: 1
3+
num_workers: 20
4+
model:
5+
input_channels: 3
6+
activation: mish
7+
normalization: batch
8+
anchors:
9+
p3width: [13, 31, 24, 61]
10+
p3height: [17, 25, 51, 45]
11+
p4width: [48, 119, 97, 217]
12+
p4height: [102, 96, 189, 184]
13+
p5width: [171, 324, 616, 800]
14+
p5height: [384, 451, 618, 800]
15+
n_classes: 80
16+
class_name_path: ./configs/class_name.yaml
17+
strides: [8, 16, 32]
18+
precision: half
19+
image_size: 896
20+
micro_batch_size: 1
21+
mode: test
22+
ipu: true
23+
ipuopts:
24+
device_iterations: 1
25+
inference:
26+
class_conf_threshold: 0.4
27+
obj_threshold: 0.4
28+
iou_threshold: 0.65
29+
plot_output: false
30+
plot_step: 250
31+
plot_dir: plots
32+
dataset:
33+
name: coco
34+
max_bbox_per_scale: 90
35+
train:
36+
cache_data: false
37+
file: train2017.txt
38+
cache_path: ./utils/data/train
39+
data_aug: false
40+
test:
41+
cache_data: false
42+
file: val2017.txt
43+
cache_path: ./utils/data/test
44+
data_aug: false
45+
mosaic: false
46+
color: false
47+
eval:
48+
metrics: true
49+
verbose: false
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
system:
2+
num_ipus: 16
3+
num_workers: 20
4+
model:
5+
input_channels: 3
6+
activation: mish
7+
normalization: group
8+
pipeline_splits: [backbone.cspdark2.csp.res_modules.1, backbone.cspdark4.csp.bottleneck_conv1, neck.cspUp2.bneck_csp.res_modules.0.conv1]
9+
anchors:
10+
p3width: [6, 13, 11, 27]
11+
p3height: [8, 12, 26, 19]
12+
p4width: [24, 54, 39, 88]
13+
p4height: [40, 38, 74, 73]
14+
p5width: [66, 123, 226, 293]
15+
p5height: [135, 195, 119, 258]
16+
n_classes: 80
17+
class_name_path: ./configs/class_name.yaml
18+
strides: [8, 16, 32]
19+
precision: mixed
20+
image_size: 416
21+
micro_batch_size: 1
22+
mode: train
23+
ipu: true
24+
uint_io: true
25+
max_nlabels_p3: 1000
26+
max_nlabels_p4: 500
27+
max_nlabels_p5: 200
28+
ipuopts:
29+
device_iterations: 4
30+
gradient_accumulation: 16
31+
training:
32+
initial_lr: 0.01
33+
stochastic_rounding: True
34+
inference:
35+
class_conf_threshold: 0.001
36+
obj_threshold: 0.001
37+
iou_threshold: 0.6
38+
plot_output: false
39+
plot_step: 250
40+
plot_dir: plots
41+
dataset:
42+
name: coco
43+
max_bbox_per_scale: 150
44+
train:
45+
cache_data: false
46+
file: train2017.txt
47+
cache_path: ./utils/data/train
48+
data_aug: true
49+
test:
50+
cache_data: false
51+
file: val2017.txt
52+
cache_path: ./utils/data/test
53+
data_aug: false
54+
mosaic: true
55+
color: true
56+
eval:
57+
metrics: false
58+
verbose: false
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.

0 commit comments

Comments
 (0)