) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/resnet50-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/resnet50-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/resnet50-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/resnet50-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/image_recognition/tensorflow/resnet50v1_5/inference/README.md b/benchmarks/image_recognition/tensorflow/resnet50v1_5/inference/README.md
index f0c2bfed5..62590f2a5 100644
--- a/benchmarks/image_recognition/tensorflow/resnet50v1_5/inference/README.md
+++ b/benchmarks/image_recognition/tensorflow/resnet50v1_5/inference/README.md
@@ -50,7 +50,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
openssh-client (only required for multi-instance)
openssh-server (only required for multi-instance)
libopenmpi-dev (only required for multi-instance)
- horovod==0.21.0 (only required for multi-instance)
+ horovod==0.27.0 (only required for multi-instance)
Activate the tensorflow conda environment
conda activate tensorflow
@@ -68,7 +68,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
openssh-client (only required for multi-instance)
openssh-server (only required for multi-instance)
libopenmpi-dev (only required for multi-instance)
- horovod==0.21.0 (only required for multi-instance)
+ horovod==0.27.0 (only required for multi-instance)
A clone of the Model Zoo repo
git clone https://github.com/IntelAI/models.git
@@ -147,6 +147,6 @@ As an example, if the dataset location on Windows is `D:\user\ImageNet`, convert
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) [Int8](int8/Advanced.md) [BFloat16](bfloat16/Advanced.md) [FP16](fp16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/resnet50v1-5-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/resnet50v1-5-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/resnet50v1-5-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/resnet50v1-5-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/image_recognition/tensorflow/resnet50v1_5/training/README.md b/benchmarks/image_recognition/tensorflow/resnet50v1_5/training/README.md
index b88020162..62b3c2618 100644
--- a/benchmarks/image_recognition/tensorflow/resnet50v1_5/training/README.md
+++ b/benchmarks/image_recognition/tensorflow/resnet50v1_5/training/README.md
@@ -49,7 +49,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
openssh-client (only required for multi-instance)
openssh-server (only required for multi-instance)
libopenmpi-dev (only required for multi-instance)
- horovod==0.21.0 (only required for multi-instance)
+ horovod==0.27.0 (only required for multi-instance)
Activate the tensorflow conda environment
conda activate tensorflow
@@ -66,7 +66,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
openssh-client (only required for multi-instance)
openssh-server (only required for multi-instance)
libopenmpi-dev (only required for multi-instance)
- horovod==0.21.0 (only required for multi-instance)
+ horovod==0.27.0 (only required for multi-instance)
A clone of the Model Zoo repo
git clone https://github.com/IntelAI/models.git
@@ -92,6 +92,6 @@ export BATCH_SIZE=
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() [BFloat16](bfloat16/Advanced.md) [FP16](fp16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/resnet50v1-5-fp32-training-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/resnet50v1-5-fp32-training-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/resnet50v1-5-fp32-training-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/resnet50v1-5-fp32-training-tensorflow-container.html).
diff --git a/benchmarks/image_segmentation/tensorflow/3d_unet/inference/fp32/README.md b/benchmarks/image_segmentation/tensorflow/3d_unet/inference/fp32/README.md
index 0b58591f8..25757faa9 100644
--- a/benchmarks/image_segmentation/tensorflow/3d_unet/inference/fp32/README.md
+++ b/benchmarks/image_segmentation/tensorflow/3d_unet/inference/fp32/README.md
@@ -140,7 +140,7 @@ export BATCH_SIZE=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/3d-unet-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/3d-unet-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/3d-unet-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/3d-unet-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/image_segmentation/tensorflow/maskrcnn/inference/fp32/README.md b/benchmarks/image_segmentation/tensorflow/maskrcnn/inference/fp32/README.md
index f04e4e843..1c5228d96 100644
--- a/benchmarks/image_segmentation/tensorflow/maskrcnn/inference/fp32/README.md
+++ b/benchmarks/image_segmentation/tensorflow/maskrcnn/inference/fp32/README.md
@@ -118,7 +118,7 @@ export BATCH_SIZE=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/mask-rcnn-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/mask-rcnn-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/mask-rcnn-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/mask-rcnn-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/image_segmentation/tensorflow/unet/inference/fp32/README.md b/benchmarks/image_segmentation/tensorflow/unet/inference/fp32/README.md
index 0abc4d6c2..eb0ee0fec 100644
--- a/benchmarks/image_segmentation/tensorflow/unet/inference/fp32/README.md
+++ b/benchmarks/image_segmentation/tensorflow/unet/inference/fp32/README.md
@@ -91,7 +91,7 @@ export BATCH_SIZE=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/unet-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/unet-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/unet-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/unet-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/language_modeling/tensorflow/bert_large/inference/README.md b/benchmarks/language_modeling/tensorflow/bert_large/inference/README.md
index 266f3bbcd..e140a5ae8 100644
--- a/benchmarks/language_modeling/tensorflow/bert_large/inference/README.md
+++ b/benchmarks/language_modeling/tensorflow/bert_large/inference/README.md
@@ -156,6 +156,6 @@ bash quickstart\language_modeling\tensorflow\bert_large\inference\cpu\fp32\]() [BFloat16](bfloat16/Advanced.md) [FP16](fp16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/bert-large-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/bert-large-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/bert-large-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/bert-large-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/language_modeling/tensorflow/bert_large/training/README.md b/benchmarks/language_modeling/tensorflow/bert_large/training/README.md
index d4c5b3bb5..374c68124 100644
--- a/benchmarks/language_modeling/tensorflow/bert_large/training/README.md
+++ b/benchmarks/language_modeling/tensorflow/bert_large/training/README.md
@@ -89,7 +89,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
openssh-client (only required for multi-instance)
openssh-server (only required for multi-instance)
libopenmpi-dev (only required for multi-instance)
- horovod==0.25.0 (only required for multi-instance)
+ horovod==0.27.0 (only required for multi-instance)
Activate the `tensorflow` conda environment
conda activate tensorflow
@@ -106,7 +106,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
openssh-client (only required for multi-instance)
openssh-server (only required for multi-instance)
libopenmpi-dev (only required for multi-instance)
- horovod==0.25.0 (only required for multi-instance)
+ horovod==0.27.0 (only required for multi-instance)
A clone of the Model Zoo repo
git clone https://github.com/IntelAI/models.git
@@ -145,6 +145,6 @@ export CHECKPOINT_DIR=
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() [BFloat16](bfloat16/Advanced.md) [FP16](fp16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/bert-large-fp32-training-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/bert-large-fp32-training-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/bert-large-fp32-training-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/bert-large-fp32-training-tensorflow-container.html).
diff --git a/benchmarks/language_translation/tensorflow/mlperf_gnmt/inference/README.md b/benchmarks/language_translation/tensorflow/mlperf_gnmt/inference/README.md
index d7f2c436f..bab4f60f0 100644
--- a/benchmarks/language_translation/tensorflow/mlperf_gnmt/inference/README.md
+++ b/benchmarks/language_translation/tensorflow/mlperf_gnmt/inference/README.md
@@ -123,6 +123,3 @@ export BATCH_SIZE=
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
- workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/gnmt-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/gnmt-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/language_translation/tensorflow/transformer_lt_official/inference/README.md b/benchmarks/language_translation/tensorflow/transformer_lt_official/inference/README.md
index dde28d694..80029966c 100644
--- a/benchmarks/language_translation/tensorflow/transformer_lt_official/inference/README.md
+++ b/benchmarks/language_translation/tensorflow/transformer_lt_official/inference/README.md
@@ -144,6 +144,6 @@ As an example, if the pretrained model path on Windows is `D:\user\transformer_l
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/transformer-lt-official-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/transformer-lt-official-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/transformer-lt-official-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/transformer-lt-official-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/language_translation/tensorflow/transformer_mlperf/inference/README.md b/benchmarks/language_translation/tensorflow/transformer_mlperf/inference/README.md
index 9d16be825..84743c5b6 100644
--- a/benchmarks/language_translation/tensorflow/transformer_mlperf/inference/README.md
+++ b/benchmarks/language_translation/tensorflow/transformer_mlperf/inference/README.md
@@ -111,6 +111,6 @@ Licenses can be found in the model package, in the `licenses` directory.
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) [Int8](int8/Advanced.md) [BFloat16](bfloat16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/transformer-lt-mlperf-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/transformer-lt-mlperf-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/transformer-lt-official-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/transformer-lt-official-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/language_translation/tensorflow/transformer_mlperf/training/README.md b/benchmarks/language_translation/tensorflow/transformer_mlperf/training/README.md
index e09bbb4f7..a4f9bfbb8 100644
--- a/benchmarks/language_translation/tensorflow/transformer_mlperf/training/README.md
+++ b/benchmarks/language_translation/tensorflow/transformer_mlperf/training/README.md
@@ -92,6 +92,6 @@ export MPI_NUM_PROCESSES=
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() [BFloat16](bfloat16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/transformer-lt-mlperf-fp32-training-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/transformer-lt-mlperf-fp32-training-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/transformer-lt-mlperf-fp32-training-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/transformer-lt-mlperf-fp32-training-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/faster_rcnn/inference/fp32/README.md b/benchmarks/object_detection/tensorflow/faster_rcnn/inference/fp32/README.md
index fb8db2f0a..4d574b273 100644
--- a/benchmarks/object_detection/tensorflow/faster_rcnn/inference/fp32/README.md
+++ b/benchmarks/object_detection/tensorflow/faster_rcnn/inference/fp32/README.md
@@ -114,7 +114,3 @@ export PRETRAINED_MODEL=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
- workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/faster-rcnn-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/faster-rcnn-fp32-inference-tensorflow-container.html).
-
diff --git a/benchmarks/object_detection/tensorflow/faster_rcnn/inference/int8/README.md b/benchmarks/object_detection/tensorflow/faster_rcnn/inference/int8/README.md
index 95db9cd09..e5b5425d0 100644
--- a/benchmarks/object_detection/tensorflow/faster_rcnn/inference/int8/README.md
+++ b/benchmarks/object_detection/tensorflow/faster_rcnn/inference/int8/README.md
@@ -119,7 +119,3 @@ export PRETRAINED_MODEL=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
- workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/faster-rcnn-int8-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/faster-rcnn-int8-inference-tensorflow-container.html).
-
diff --git a/benchmarks/object_detection/tensorflow/rfcn/inference/README.md b/benchmarks/object_detection/tensorflow/rfcn/inference/README.md
index eb5b76ce2..72908a31f 100644
--- a/benchmarks/object_detection/tensorflow/rfcn/inference/README.md
+++ b/benchmarks/object_detection/tensorflow/rfcn/inference/README.md
@@ -215,6 +215,6 @@ As an example, if the dataset location on Windows is `D:\user\coco_dataset\val20
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) [Int8](int8/Advanced.md) []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/rfcn-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/rfcn-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/rfcn-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/rfcn-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/rfcn/inference/int8/README.md b/benchmarks/object_detection/tensorflow/rfcn/inference/int8/README.md
index 6b18d4a1d..3606bba08 100644
--- a/benchmarks/object_detection/tensorflow/rfcn/inference/int8/README.md
+++ b/benchmarks/object_detection/tensorflow/rfcn/inference/int8/README.md
@@ -208,7 +208,7 @@ As an example, if the dataset location on Windows is `D:\user\coco_dataset\val20
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/rfcn-int8-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/rfcn-int8-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/rfcn-int8-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/rfcn-int8-inference-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/README.md b/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/README.md
index 4ca9974e9..1d68d5627 100644
--- a/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/README.md
+++ b/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/README.md
@@ -156,7 +156,7 @@ As an example, if the dataset location on Windows is `D:\user\coco_dataset\coco_
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) [Int8](int8/Advanced.md) [BFloat16](bfloat16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-mobilenet-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-mobilenet-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-mobilenet-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-mobilenet-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/int8/README.md b/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/int8/README.md
index f81c04513..f593752f0 100644
--- a/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/int8/README.md
+++ b/benchmarks/object_detection/tensorflow/ssd-mobilenet/inference/int8/README.md
@@ -150,7 +150,7 @@ As an example, if the dataset location on Windows is `D:\user\coco_dataset\coco_
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-mobilenet-int8-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-mobilenet-int8-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-mobilenet-int8-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-mobilenet-int8-inference-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/ssd-resnet34/inference/README.md b/benchmarks/object_detection/tensorflow/ssd-resnet34/inference/README.md
index cabe1f141..6364c9150 100644
--- a/benchmarks/object_detection/tensorflow/ssd-resnet34/inference/README.md
+++ b/benchmarks/object_detection/tensorflow/ssd-resnet34/inference/README.md
@@ -208,6 +208,6 @@ As an example, if the dataset location on Windows is `D:\user\coco_dataset`, con
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) [Int8](int8/Advanced.md) [BFloat16](bfloat16/Advanced.md) for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-resnet34-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-resnet34-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-resnet34-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-resnet34-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/ssd-resnet34/training/bfloat16/README.md b/benchmarks/object_detection/tensorflow/ssd-resnet34/training/bfloat16/README.md
index 730d86143..7bb014019 100644
--- a/benchmarks/object_detection/tensorflow/ssd-resnet34/training/bfloat16/README.md
+++ b/benchmarks/object_detection/tensorflow/ssd-resnet34/training/bfloat16/README.md
@@ -57,8 +57,8 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
pillow>=9.3.0
protobuf-compiler
pycocotools
- tensorflow-addons==0.11.0
- Activate the tensorflow 2.5.0 conda environment
+ tensorflow-addons==0.18.0
+ Activate the tensorflow conda environment
conda activate tensorflow
@@ -84,7 +84,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
pillow>=9.3.0
protobuf-compiler
pycocotools
- tensorflow-addons==0.11.0
+ tensorflow-addons==0.18.0
A clone of the Model Zoo repo
git clone https://github.com/IntelAI/models.git
@@ -191,7 +191,7 @@ export BATCH_SIZE=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-resnet34-bfloat16-training-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-resnet34-bfloat16-training-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-resnet34-bfloat16-training-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-resnet34-bfloat16-training-tensorflow-container.html).
diff --git a/benchmarks/object_detection/tensorflow/ssd-resnet34/training/fp32/README.md b/benchmarks/object_detection/tensorflow/ssd-resnet34/training/fp32/README.md
index 42d868238..0ae60a3d8 100644
--- a/benchmarks/object_detection/tensorflow/ssd-resnet34/training/fp32/README.md
+++ b/benchmarks/object_detection/tensorflow/ssd-resnet34/training/fp32/README.md
@@ -51,8 +51,8 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
pillow>=9.3.0
protoc
pycocotools
- tensorflow-addons==0.11.0
- Activate the tensorflow 2.5.0 conda environment
+ tensorflow-addons==0.18.0
+ Activate the tensorflow conda environment
conda activate tensorflow
@@ -77,7 +77,7 @@ using [AI Kit](/docs/general/tensorflow/AIKit.md):
pillow>=9.3.0
protoc
pycocotools
- tensorflow-addons==0.11.0
+ tensorflow-addons==0.18.0
A clone of the Model Zoo repo
git clone https://github.com/IntelAI/models.git
@@ -129,7 +129,7 @@ export BATCH_SIZE=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-resnet34-fp32-training-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/ssd-resnet34-fp32-training-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-resnet34-fp32-training-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/ssd-resnet34-fp32-training-tensorflow-container.html).
diff --git a/benchmarks/recommendation/tensorflow/dien/inference/README.md b/benchmarks/recommendation/tensorflow/dien/inference/README.md
index 37b8197bd..528c48b92 100644
--- a/benchmarks/recommendation/tensorflow/dien/inference/README.md
+++ b/benchmarks/recommendation/tensorflow/dien/inference/README.md
@@ -105,6 +105,3 @@ As an example, if the pretrained model path on Windows is `D:\user\dien_fp32_sta
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [DevCatalog](http://software.intel.com/containers)
- workload container
-
diff --git a/benchmarks/recommendation/tensorflow/dien/training/README.md b/benchmarks/recommendation/tensorflow/dien/training/README.md
index c599babdb..18418f1b8 100644
--- a/benchmarks/recommendation/tensorflow/dien/training/README.md
+++ b/benchmarks/recommendation/tensorflow/dien/training/README.md
@@ -60,5 +60,5 @@ export OUTPUT_DIR=
## Additional Resources
* To run more advanced use cases, see the instructions [here](/benchmarks/recommendation/tensorflow/dien/inference/Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [DevCatalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [DevCatalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container
diff --git a/benchmarks/recommendation/tensorflow/ncf/inference/fp32/README.md b/benchmarks/recommendation/tensorflow/ncf/inference/fp32/README.md
index a4e53a6a4..fdfe91ced 100644
--- a/benchmarks/recommendation/tensorflow/ncf/inference/fp32/README.md
+++ b/benchmarks/recommendation/tensorflow/ncf/inference/fp32/README.md
@@ -110,7 +110,7 @@ export BATCH_SIZE=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/ncf-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/ncf-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/ncf-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/ncf-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/recommendation/tensorflow/wide_deep/inference/README.md b/benchmarks/recommendation/tensorflow/wide_deep/inference/README.md
index 2d9c54de4..3c10dc4ef 100644
--- a/benchmarks/recommendation/tensorflow/wide_deep/inference/README.md
+++ b/benchmarks/recommendation/tensorflow/wide_deep/inference/README.md
@@ -141,6 +141,6 @@ As an example, if the dataset location on Windows is `D:\\widedeep_dataset
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/wide-deep-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/wide-deep-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/wide-deep-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/wide-deep-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/recommendation/tensorflow/wide_deep_large_ds/inference/README.md b/benchmarks/recommendation/tensorflow/wide_deep_large_ds/inference/README.md
index 434845024..8abc052cd 100644
--- a/benchmarks/recommendation/tensorflow/wide_deep_large_ds/inference/README.md
+++ b/benchmarks/recommendation/tensorflow/wide_deep_large_ds/inference/README.md
@@ -94,6 +94,6 @@ export NUM_OMP_THREADS=1
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) [Int8](int8/Advanced.md) []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/wide-deep-large-dataset-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/wide-deep-large-dataset-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/wide-deep-large-dataset-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/wide-deep-large-dataset-fp32-inference-tensorflow-container.html).
diff --git a/benchmarks/recommendation/tensorflow/wide_deep_large_ds/training/README.md b/benchmarks/recommendation/tensorflow/wide_deep_large_ds/training/README.md
index 448a7d6b3..b8f65c8ef 100644
--- a/benchmarks/recommendation/tensorflow/wide_deep_large_ds/training/README.md
+++ b/benchmarks/recommendation/tensorflow/wide_deep_large_ds/training/README.md
@@ -95,6 +95,6 @@ export BATCH_SIZE=
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions [FP32](fp32/Advanced.md) []() []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/wide-deep-large-dataset-fp32-training-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/wide-deep-large-dataset-fp32-training-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/wide-deep-large-dataset-fp32-training-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/wide-deep-large-dataset-fp32-training-tensorflow-container.html).
diff --git a/benchmarks/text_to_speech/tensorflow/wavenet/inference/fp32/README.md b/benchmarks/text_to_speech/tensorflow/wavenet/inference/fp32/README.md
index cfd299fed..393e81a7d 100644
--- a/benchmarks/text_to_speech/tensorflow/wavenet/inference/fp32/README.md
+++ b/benchmarks/text_to_speech/tensorflow/wavenet/inference/fp32/README.md
@@ -88,7 +88,7 @@ export PRETRAINED_MODEL=
* To run more advanced use cases, see the instructions [here](Advanced.md)
for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [oneContainer](http://software.intel.com/containers)
+* To run the model using docker, please see the [oneContainer](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
- [https://software.intel.com/content/www/us/en/develop/articles/containers/wavenet-fp32-inference-tensorflow-container.html](https://software.intel.com/content/www/us/en/develop/articles/containers/wavenet-fp32-inference-tensorflow-container.html).
+ [https://www.intel.com/content/www/us/en/developer/articles/containers/wavenet-fp32-inference-tensorflow-container.html](https://www.intel.com/content/www/us/en/developer/articles/containers/wavenet-fp32-inference-tensorflow-container.html).
diff --git a/datasets/cloud_data_connector/samples/azure/requirements.txt b/datasets/cloud_data_connector/samples/azure/requirements.txt
index fc904eab0..4f9b001e2 100644
--- a/datasets/cloud_data_connector/samples/azure/requirements.txt
+++ b/datasets/cloud_data_connector/samples/azure/requirements.txt
@@ -1,3 +1,3 @@
-mlflow==2.5.0 #upgraded to resolve Snyk critical vulnerability
+mlflow==2.6.0 #upgraded to resolve Snyk critical vulnerability
scikit-learn==1.2.2
xlrd==2.0.1
\ No newline at end of file
diff --git a/datasets/cloud_data_connector/samples/interoperability/requirements.txt b/datasets/cloud_data_connector/samples/interoperability/requirements.txt
index a2e90b5e8..df0f06aab 100644
--- a/datasets/cloud_data_connector/samples/interoperability/requirements.txt
+++ b/datasets/cloud_data_connector/samples/interoperability/requirements.txt
@@ -1,4 +1,4 @@
-mlflow==2.5.0 #upgraded to resolve Snyk critical vulnerability
+mlflow==2.6.0 #upgraded to resolve Snyk critical vulnerability
scikit-learn==1.2.2
xlrd==2.0.1
pandas-gbq==0.19.1
diff --git a/docker/dataset/docker-compose.yml b/docker/dataset/docker-compose.yml
new file mode 100644
index 000000000..22c6442b8
--- /dev/null
+++ b/docker/dataset/docker-compose.yml
@@ -0,0 +1,37 @@
+#
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2023 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.
+#
+
+#
+
+version: '3'
+services:
+ preprocess-coco-val:
+ image: intel/object-detection:tf-1.15.2-preprocess-coco-val
+ pull_policy: always
+ build:
+ context: ../../
+ args:
+ http_proxy: ${http_proxy}
+ https_proxy: ${https_proxy}
+ no_proxy: ${no_proxy}
+ TF_MODELS_BRANCH: 7a9934df2afdf95be9405b4e9f1f2480d748dc40
+ BASE_IMAGE: ${TENSORFLOW_IMAGE:-intel/intel-optimized-tensorflow}
+ BASE_TAG: ${TENSORFLOW_TAG:-1.15.2}
+ dockerfile: docker/dataset/preprocess-coco-val/intel-tf-object-detection-preprocess-coco-val.Dockerfile
+ command: >
+ sh -c "python -c 'import tensorflow as tf; print(tf.__version__)'"
diff --git a/docker/flex-gpu/.actions.json b/docker/flex-gpu/.actions.json
new file mode 100644
index 000000000..990b77193
--- /dev/null
+++ b/docker/flex-gpu/.actions.json
@@ -0,0 +1,4 @@
+{
+ "VARIATIONS": ["NONE"],
+ "experimental": [true]
+}
diff --git a/docker/flex-gpu/docker-compose.yml b/docker/flex-gpu/docker-compose.yml
new file mode 100644
index 000000000..a8d9528f0
--- /dev/null
+++ b/docker/flex-gpu/docker-compose.yml
@@ -0,0 +1,95 @@
+#
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2023 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.
+#
+
+#
+
+version: '3'
+services:
+ pytorch-resnet50v1-5-inference:
+ build:
+ context: ../../
+ args:
+ http_proxy: ${http_proxy}
+ https_proxy: ${https_proxy}
+ no_proxy: ""
+ BASE_IMAGE: ${REGISTRY}/aiops/mlops
+ BASE_TAG: ${FLEX_PYT_BASE_TAG:-ipex-gpu-2.0.110-xpu}
+ dockerfile: docker/flex-gpu/pytorch-resnet50v1-5-inference/pytorch-flex-series-resnet50v1-5-inference.Dockerfile
+ command: >
+ sh -c "python -c 'import torch; import intel_extension_for_pytorch as ipex; print(\"torch:\", torch.__version__, \" ipex:\",ipex.__version__)'"
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-flex-gpu-resnet50v1-5-inference
+ pull_policy: always
+ pytorch-ssd-mobilenet-inference:
+ build:
+ args:
+ VOC_LABELS_URL: ${VOC_LABELS_URL:-https://drive.google.com/uc?id=1q1sXhKIxniInw3WASnEDKYMqPMuiDDvc}
+ dockerfile: docker/flex-gpu/pytorch-ssd-mobilenet-inference/pytorch-flex-series-ssd-mobilenet-inference.Dockerfile
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-ssd-mobilenet-inference
+ pytorch-yolov4-inference:
+ build:
+ dockerfile: docker/flex-gpu/pytorch-yolov4-inference/pytorch-flex-series-yolov4-inference.Dockerfile
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-yolov4-inference
+ tf-resnet50v1-5-inference:
+ build:
+ args:
+ BASE_IMAGE: ${FLEX_TF_BASE_IMAGE:-intel/intel-extension-for-tensorflow}
+ BASE_TAG: ${FLEX_TF_BASE_TAG:-xpu}
+ MODEL_URL: ${MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/resnet50_v1_int8.pb}
+ dockerfile: docker/flex-gpu/tf-resnet50v1-5-inference/tf-flex-series-resnet50v1-5-inference.Dockerfile
+ command: >
+ sh -c "python -c 'import tensorflow as tf; print(tf.__version__)'"
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-resnet50v1-5-inference
+ tf-ssd-mobilenet-inference:
+ build:
+ args:
+ BASE_TAG: ${FLEX_TF_BASE_TAG:-gpu}
+ MODEL_URL: ${MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/ssd_mobilenet_v1_int8_itex.pb}
+ dockerfile: docker/flex-gpu/tf-ssd-mobilenet-inference/tf-flex-series-ssd-mobilenet-inference.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-tf-flex-gpu-ssd-mobilenet-inference
+ tf-maskrcnn-inference:
+ build:
+ dockerfile: docker/flex-gpu/tf-maskrcnn-inference/tf-flex-series-maskrcnn-inference.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-segmentation-tf-flex-gpu-maskrcnn-inference
+ pytorch-stable-diffusion-inference:
+ build:
+ args:
+ BASE_IMAGE: ${REGISTRY}/aiops/mlops
+ BASE_TAG: ${FLEX_PYT_BASE_TAG:-ipex-gpu-2.0.110-xpu}
+ dockerfile: docker/flex-gpu/pytorch-stable-diffusion-inference/pytorch-flex-series-stable-diffusion-inference.Dockerfile
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-pytorch-flex-gpu-stable-diffusion-inference
+ pytorch-yolov5-inference:
+ build:
+ dockerfile: docker/flex-gpu/pytorch-yolov5-inference/pytorch-flex-series-yolov5-inference.Dockerfile
+ extends: pytorch-stable-diffusion-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-yolov5-inference
+ tf-stable-diffusion-inference:
+ build:
+ dockerfile: docker/flex-gpu/tf-stable-diffusion-inference/tf-flex-series-stable-diffusion-inference.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-tf-flex-gpu-stable-diffusion-inference
+ tf-efficientnet-inference:
+ build:
+ dockerfile: docker/flex-gpu/tf-efficientnet-inference/tf-flex-series-efficientnet-inference.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
diff --git a/docker/flex-gpu/pytorch-resnet50v1-5-inference/pytorch-flex-series-resnet50v1-5-inference.Dockerfile b/docker/flex-gpu/pytorch-resnet50v1-5-inference/pytorch-flex-series-resnet50v1-5-inference.Dockerfile
index 93076246b..c0c1d3b3a 100644
--- a/docker/flex-gpu/pytorch-resnet50v1-5-inference/pytorch-flex-series-resnet50v1-5-inference.Dockerfile
+++ b/docker/flex-gpu/pytorch-resnet50v1-5-inference/pytorch-flex-series-resnet50v1-5-inference.Dockerfile
@@ -27,8 +27,7 @@ FROM ${BASE_IMAGE}:${BASE_TAG}
WORKDIR /workspace/pytorch-flex-series-resnet50v1-5-inference
RUN apt-get update && \
- apt-get install -y parallel
-RUN apt-get install -y pciutils
+ apt-get install -y --no-install-recommends --fix-missing parallel pciutils numactl
RUN apt-get update && \
apt-get install -y --no-install-recommends --fix-missing numactl
diff --git a/docker/flex-gpu/pytorch-resnet50v1-5-inference/tests.yaml b/docker/flex-gpu/pytorch-resnet50v1-5-inference/tests.yaml
new file mode 100644
index 000000000..6e5f059fe
--- /dev/null
+++ b/docker/flex-gpu/pytorch-resnet50v1-5-inference/tests.yaml
@@ -0,0 +1,42 @@
+170-online:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/inference_block_format.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ NUM_ITERATIONS: '5000'
+ PRECISION: int8
+ OUTPUT_DIR: /tmp
+170-batch:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/inference_block_format.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1024'
+ NUM_ITERATIONS: '500'
+ PRECISION: int8
+ OUTPUT_DIR: /tmp
+140-batch:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/flex_multi_card_batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '256'
+ NUM_ITERATIONS: '500'
+ PRECISION: int8
+ OUTPUT_DIR: /tmp
+140-online:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/flex_multi_card_online_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '1'
+ NUM_ITERATIONS: '5000'
+ PRECISION: int8
+ OUTPUT_DIR: /tmp
diff --git a/dockerfiles/lpot/tensorflow/intel-tf-lpot.Dockerfile b/docker/flex-gpu/pytorch-stable-diffusion-inference/pytorch-flex-series-stable-diffusion-inference.Dockerfile
similarity index 56%
rename from dockerfiles/lpot/tensorflow/intel-tf-lpot.Dockerfile
rename to docker/flex-gpu/pytorch-stable-diffusion-inference/pytorch-flex-series-stable-diffusion-inference.Dockerfile
index 27314e6db..1bb9a927b 100644
--- a/dockerfiles/lpot/tensorflow/intel-tf-lpot.Dockerfile
+++ b/docker/flex-gpu/pytorch-stable-diffusion-inference/pytorch-flex-series-stable-diffusion-inference.Dockerfile
@@ -1,4 +1,4 @@
-# Copyright (c) 2021 Intel Corporation
+# Copyright (c) 2023 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -19,28 +19,28 @@
# throughout. Please refer to the TensorFlow dockerfiles documentation
# for more information.
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
+ARG BASE_IMAGE="intel/intel-extension-for-pytorch"
+ARG BASE_TAG="xpu-flex"
-ARG TENSORFLOW_TAG="2.5.0-ubuntu-20.04"
+FROM ${BASE_IMAGE}:${BASE_TAG}
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PY_VERSION="3.8"
+WORKDIR /home/user/workspace/pytorch-flex-series-stable-diffusion-inference
RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
+ apt-get install -y parallel
+RUN apt-get install -y pciutils
-RUN pip install lpot
+ARG PY_VERSION=3.10
-ARG LPOT_SOURCE_DIR=/src/lpot
-ARG LPOT_BRANCH=master
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends --fix-missing \
+ build-essential \
+ python${PY_VERSION}-dev
-ENV LPOT_SOURCE_DIR=$LPOT_SOURCE_DIR
+RUN pip install diffusers pytorch-fid transformers
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone --single-branch --branch ${LPOT_BRANCH} https://github.com/intel/lpot.git ${LPOT_SOURCE_DIR}
+COPY models/generative-ai/pytorch/stable_diffusion/inference/gpu models/generative-ai/pytorch/stable_diffusion/inference/gpu
+COPY quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/online_inference.sh quickstart/online_inference.sh
-WORKDIR ${LPOT_SOURCE_DIR}
+COPY LICENSE license/LICENSE
+COPY third_party license/third_party
diff --git a/docker/flex-gpu/pytorch-stable-diffusion-inference/tests.yaml b/docker/flex-gpu/pytorch-stable-diffusion-inference/tests.yaml
new file mode 100644
index 000000000..7a21b4e28
--- /dev/null
+++ b/docker/flex-gpu/pytorch-stable-diffusion-inference/tests.yaml
@@ -0,0 +1,18 @@
+fp32-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-pytorch-flex-gpu-stable-diffusion-inference
+ cmd: quickstart/online_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ PRECISION: fp32
+ BATCH_SIZE: '1'
+ OUTPUT_DIR: /tmp
+fp16-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-pytorch-flex-gpu-stable-diffusion-inference
+ cmd: quickstart/online_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ PRECISION: fp16
+ BATCH_SIZE: '1'
+ OUTPUT_DIR: /tmp
diff --git a/docker/flex-gpu/pytorch-yolov4-inference/pytorch-flex-series-yolov4-inference.Dockerfile b/docker/flex-gpu/pytorch-yolov4-inference/pytorch-flex-series-yolov4-inference.Dockerfile
index 08d29f63b..ef85703c5 100644
--- a/docker/flex-gpu/pytorch-yolov4-inference/pytorch-flex-series-yolov4-inference.Dockerfile
+++ b/docker/flex-gpu/pytorch-yolov4-inference/pytorch-flex-series-yolov4-inference.Dockerfile
@@ -19,10 +19,10 @@
# throughout. Please refer to the TensorFlow dockerfiles documentation
# for more information.
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-flex"
+ARG BASE_IMAGE="intel/intel-extension-for-pytorch"
+ARG BASE_TAG="xpu-flex"
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
+FROM ${BASE_IMAGE}:${BASE_TAG}
RUN apt-get update && \
apt-get install -y parallel
diff --git a/docker/flex-gpu/pytorch-yolov5-inference/pytorch-flex-series-yolov5-inference.Dockerfile b/docker/flex-gpu/pytorch-yolov5-inference/pytorch-flex-series-yolov5-inference.Dockerfile
new file mode 100644
index 000000000..a6e87346b
--- /dev/null
+++ b/docker/flex-gpu/pytorch-yolov5-inference/pytorch-flex-series-yolov5-inference.Dockerfile
@@ -0,0 +1,60 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+ARG BASE_IMAGE="intel/intel-extension-for-pytorch"
+ARG BASE_TAG="xpu-flex"
+
+FROM ${BASE_IMAGE}:${BASE_TAG}
+
+WORKDIR /home/user/workspace/pytorch-flex-series-yolov5-inference
+
+RUN apt-get update && \
+ apt-get install -y parallel
+RUN apt-get install -y pciutils
+
+# RUN sudo apt-get update && \
+RUN apt-get install -y --no-install-recommends --fix-missing numactl ffmpeg libsm6 libxext6
+
+ARG PY_VERSION=3.10
+
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends --fix-missing \
+ build-essential \
+ python${PY_VERSION}-dev
+
+RUN pip install \
+ matplotlib>=3.2.2 \
+ numpy>=1.18.5 \
+ opencv-python>=4.1.1 \
+ Pillow>=7.1.2 \
+ PyYAML>=5.3.1 \
+ requests>=2.23.0 \
+ scipy>=1.4.1 \
+ tqdm>=4.64.0 \
+ protobuf==3.20.1 \
+ pandas>=1.1.4 \
+ seaborn>=0.11.0
+
+COPY models/object_detection/pytorch/yolov5/inference/gpu models/object_detection/pytorch/yolov5/inference/gpu
+COPY quickstart/object_detection/pytorch/yolov5/inference/gpu/inference.sh quickstart/inference.sh
+
+COPY LICENSE license/LICENSE
+COPY third_party license/third_party
diff --git a/docker/flex-gpu/pytorch-yolov5-inference/tests.yaml b/docker/flex-gpu/pytorch-yolov5-inference/tests.yaml
new file mode 100644
index 000000000..f1e87e698
--- /dev/null
+++ b/docker/flex-gpu/pytorch-yolov5-inference/tests.yaml
@@ -0,0 +1,63 @@
+---
+170-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-yolov5-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '32'
+ NUM_ITERATIONS: '500'
+ IMAGE_FILE: /dataset/yolov5/000000581918.jpg
+ GPU_TYPE: flex_170
+ PRECISION: fp16
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/yolov5/000000581918.jpg
+ dst: /dataset/yolov5/000000581918.jpg
+170-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-yolov5-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ NUM_ITERATIONS: '5000'
+ IMAGE_FILE: /dataset/yolov5/000000581918.jpg
+ GPU_TYPE: flex_170
+ PRECISION: fp16
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/yolov5/000000581918.jpg
+ dst: /dataset/yolov5/000000581918.jpg
+140-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-yolov5-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '32'
+ NUM_ITERATIONS: '500'
+ IMAGE_FILE: /dataset/yolov5/000000581918.jpg
+ GPU_TYPE: flex_140
+ PRECISION: fp16
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/yolov5/000000581918.jpg
+ dst: /dataset/yolov5/000000581918.jpg
+140-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-object-detection-pytorch-flex-gpu-yolov5-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '1'
+ NUM_ITERATIONS: '5000'
+ IMAGE_FILE: /dataset/yolov5/000000581918.jpg
+ GPU_TYPE: flex_140
+ PRECISION: fp16
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/yolov5/000000581918.jpg
+ dst: /dataset/yolov5/000000581918.jpg
diff --git a/docker/flex-gpu/tf-efficientnet-inference/tests.yaml b/docker/flex-gpu/tf-efficientnet-inference/tests.yaml
new file mode 100644
index 000000000..bee287706
--- /dev/null
+++ b/docker/flex-gpu/tf-efficientnet-inference/tests.yaml
@@ -0,0 +1,124 @@
+b0-flex170-bs64-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '64'
+ MODEL_NAME: EfficientNetB0
+ PRECISION: fp16
+ GPU_TYPE: flex_170
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b0-flex170-bs128-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '128'
+ MODEL_NAME: EfficientNetB0
+ PRECISION: fp16
+ GPU_TYPE: flex_170
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b3-flex170-bs64-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '64'
+ MODEL_NAME: EfficientNetB3
+ PRECISION: fp16
+ GPU_TYPE: flex_170
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b3-flex170-bs128-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '128'
+ MODEL_NAME: EfficientNetB3
+ PRECISION: fp16
+ GPU_TYPE: flex_170
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b0-flex140-bs64-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '64'
+ MODEL_NAME: EfficientNetB0
+ PRECISION: fp16
+ GPU_TYPE: flex_140
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b0-flex140-bs128-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '128'
+ MODEL_NAME: EfficientNetB0
+ PRECISION: fp16
+ GPU_TYPE: flex_140
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b3-flex140-bs64-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '64'
+ MODEL_NAME: EfficientNetB3
+ PRECISION: fp16
+ GPU_TYPE: flex_140
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+b3-flex140-bs128-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-efficientnet-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ BATCH_SIZE: '128'
+ MODEL_NAME: EfficientNetB3
+ PRECISION: fp16
+ GPU_TYPE: flex_140
+ IMAGE_FILE: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
+ dst: /dataset/efficient-net/ILSVRC2012_val_00033350.JPEG
diff --git a/dockerfiles/intel-tf-image-recognition.Dockerfile b/docker/flex-gpu/tf-efficientnet-inference/tf-flex-series-efficientnet-inference.Dockerfile
similarity index 56%
rename from dockerfiles/intel-tf-image-recognition.Dockerfile
rename to docker/flex-gpu/tf-efficientnet-inference/tf-flex-series-efficientnet-inference.Dockerfile
index ed2f5e000..ec493d9d9 100644
--- a/dockerfiles/intel-tf-image-recognition.Dockerfile
+++ b/docker/flex-gpu/tf-efficientnet-inference/tf-flex-series-efficientnet-inference.Dockerfile
@@ -1,4 +1,4 @@
-# Copyright (c) 2020-2021 Intel Corporation
+# Copyright (c) 2023 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -19,17 +19,20 @@
# throughout. Please refer to the TensorFlow dockerfiles documentation
# for more information.
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
+ARG BASE_IMAGE="intel/intel-extension-for-tensorflow"
+ARG BASE_TAG="xpu"
-ARG TENSORFLOW_TAG="latest"
+FROM ${BASE_IMAGE}:${BASE_TAG}
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
+WORKDIR /workspace/tf-flex-series-efficientnet-inference
RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
+ apt-get install -y --no-install-recommends --fix-missing parallel pciutils numactl
+
+RUN pip install pillow
+
+COPY models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py
+COPY quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/batch_inference.sh quickstart/batch_inference.sh
+
+COPY LICENSE license/LICENSE
+COPY third_party license/third_party
diff --git a/docker/flex-gpu/tf-maskrcnn-inference/tests.yaml b/docker/flex-gpu/tf-maskrcnn-inference/tests.yaml
new file mode 100644
index 000000000..270fc0575
--- /dev/null
+++ b/docker/flex-gpu/tf-maskrcnn-inference/tests.yaml
@@ -0,0 +1,42 @@
+170-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-segmentation-tf-flex-gpu-maskrcnn-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ PRECISION: fp16
+ GPU_TYPE: flex_170
+ DATASET_DIR: /dataset/maskrcnn/coco
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/maskrcnn/coco
+ dst: /dataset/maskrcnn/coco
+170-batch-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-segmentation-tf-flex-gpu-maskrcnn-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '16'
+ PRECISION: fp16
+ GPU_TYPE: flex_170
+ DATASET_DIR: /dataset/maskrcnn/coco
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/maskrcnn/coco
+ dst: /dataset/maskrcnn/coco
+140-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-segmentation-tf-flex-gpu-maskrcnn-inference
+ cmd: quickstart/inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ PRECISION: fp16
+ GPU_TYPE: flex_140
+ DATASET_DIR: /dataset/maskrcnn/coco
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/maskrcnn/coco
+ dst: /dataset/maskrcnn/coco
diff --git a/docker/flex-gpu/tf-maskrcnn-inference/tf-flex-series-maskrcnn-inference.Dockerfile b/docker/flex-gpu/tf-maskrcnn-inference/tf-flex-series-maskrcnn-inference.Dockerfile
new file mode 100644
index 000000000..0978c5d2b
--- /dev/null
+++ b/docker/flex-gpu/tf-maskrcnn-inference/tf-flex-series-maskrcnn-inference.Dockerfile
@@ -0,0 +1,50 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+ARG BASE_IMAGE="intel/intel-extension-for-tensorflow"
+ARG BASE_TAG="xpu"
+
+FROM ${BASE_IMAGE}:${BASE_TAG}
+
+WORKDIR /workspace/tf-flex-series-maskrcnn-inference
+
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends --fix-missing parallel pciutils numactl
+
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends --fix-missing \
+ git build-essential libssl-dev libffi-dev python3.10-dev
+
+RUN python -m pip install opencv-python-headless pycocotools
+
+COPY models/image_segmentation/tensorflow/maskrcnn/inference/gpu models/image_segmentation/tensorflow/maskrcnn/inference/gpu
+COPY quickstart/image_segmentation/tensorflow/maskrcnn/inference/gpu/inference.sh quickstart/inference.sh
+
+RUN pip install git+https://github.com/NVIDIA/dllogger.git
+RUN git clone https://github.com/NVIDIA/DeepLearningExamples.git && \
+ cd /workspace/tf-flex-series-maskrcnn-inference/DeepLearningExamples && \
+ git checkout 5be8a3cae21ee2d80e3935a4746827cb3367bcac && \
+ mv /workspace/tf-flex-series-maskrcnn-inference/models/image_segmentation/tensorflow/maskrcnn/inference/gpu/EnableInference.patch . && \
+ git apply EnableInference.patch && \
+ cd -
+
+COPY LICENSE license/LICENSE
+COPY third_party license/third_party
diff --git a/docker/flex-gpu/tf-resnet50v1-5-inference/tests.yaml b/docker/flex-gpu/tf-resnet50v1-5-inference/tests.yaml
new file mode 100644
index 000000000..80bab7b72
--- /dev/null
+++ b/docker/flex-gpu/tf-resnet50v1-5-inference/tests.yaml
@@ -0,0 +1,52 @@
+batch-170-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ PRECISION : int8
+ GPU_TYPE: flex_series
+ OUTPUT_DIR: /tmp
+online-170-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/online_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ PRECISION : int8
+ GPU_TYPE: flex_series
+ OUTPUT_DIR: /tmp
+batch-140-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/flex_multi_card_batch_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ PRECISION : int8
+ GPU_TYPE: flex_series
+ BATCH_SIZE: '256'
+ OUTPUT_DIR: /tmp
+batch-140-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/flex_multi_card_online_inference.sh
+ ipc: host
+ device: /dev/dri
+ cap_add: SYS_NICE
+ env:
+ PRECISION : int8
+ GPU_TYPE: flex_series
+ BATCH_SIZE: '1'
+ OUTPUT_DIR: /tmp
+170-accuracy:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-flex-gpu-resnet50v1-5-inference
+ cmd: quickstart/accuracy.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ PRECISION : int8
+ GPU_TYPE: flex_series
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /tf_dataset/dataset/TF_Imagenet_FullData
+ dst: /tf_dataset/dataset/TF_Imagenet_FullData
diff --git a/docker/flex-gpu/tf-resnet50v1-5-inference/tf-flex-series-resnet50v1-5-inference.Dockerfile b/docker/flex-gpu/tf-resnet50v1-5-inference/tf-flex-series-resnet50v1-5-inference.Dockerfile
index 88c1e143d..916369381 100644
--- a/docker/flex-gpu/tf-resnet50v1-5-inference/tf-flex-series-resnet50v1-5-inference.Dockerfile
+++ b/docker/flex-gpu/tf-resnet50v1-5-inference/tf-flex-series-resnet50v1-5-inference.Dockerfile
@@ -27,11 +27,7 @@ FROM ${BASE_IMAGE}:${BASE_TAG}
WORKDIR /workspace/tf-flex-series-resnet50v1-5-inference
RUN apt-get update && \
- apt-get install -y parallel
-RUN apt-get install -y pciutils
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
+ apt-get install -y --no-install-recommends --fix-missing parallel pciutils numactl
ARG MODEL_URL
diff --git a/docker/flex-gpu/tf-stable-diffusion-inference/tests.yaml b/docker/flex-gpu/tf-stable-diffusion-inference/tests.yaml
new file mode 100644
index 000000000..a837a7a1d
--- /dev/null
+++ b/docker/flex-gpu/tf-stable-diffusion-inference/tests.yaml
@@ -0,0 +1,32 @@
+---
+fp32-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-tf-flex-gpu-stable-diffusion-inference
+ cmd: quickstart/online_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ PRECISION: fp32
+ OUTPUT_DIR: /tmp
+fp16-online-inference:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-tf-flex-gpu-stable-diffusion-inference
+ cmd: quickstart/online_inference.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ PRECISION: fp16
+ OUTPUT_DIR: /tmp
+fp16-accuracy:
+ img: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-generative-ai-tf-flex-gpu-stable-diffusion-inference
+ cmd: quickstart/accuracy.sh
+ ipc: host
+ device: /dev/dri
+ env:
+ BATCH_SIZE: '1'
+ PRECISION: fp16
+ REFERENCE_RESULT_FILE: /dataset/stable-diffusion/img_arrays_for_acc.txt
+ OUTPUT_DIR: /tmp
+ volumes:
+ - src: /dataset/stable-diffusion/img_arrays_for_acc.txt
+ dst: /dataset/stable-diffusion/img_arrays_for_acc.txt
diff --git a/docker/flex-gpu/tf-stable-diffusion-inference/tf-flex-series-stable-diffusion-inference.Dockerfile b/docker/flex-gpu/tf-stable-diffusion-inference/tf-flex-series-stable-diffusion-inference.Dockerfile
new file mode 100644
index 000000000..9e6e2865b
--- /dev/null
+++ b/docker/flex-gpu/tf-stable-diffusion-inference/tf-flex-series-stable-diffusion-inference.Dockerfile
@@ -0,0 +1,48 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+ARG BASE_IMAGE="intel/intel-extension-for-tensorflow"
+ARG BASE_TAG="xpu"
+
+FROM ${BASE_IMAGE}:${BASE_TAG}
+
+WORKDIR /workspace/tf-flex-series-stable-diffusion-inference
+
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends --fix-missing git
+
+COPY models/generative-ai/tensorflow/stable_diffusion/inference/gpu/ models/generative-ai/tensorflow/stable_diffusion/inference/gpu/
+
+COPY quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/online_inference.sh quickstart/online_inference.sh
+COPY quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/accuracy.sh quickstart/accuracy.sh
+
+RUN git clone https://github.com/keras-team/keras-cv.git && \
+ cd keras-cv && \
+ git reset --hard 66fa74b6a2a0bb1e563ae8bce66496b118b95200 && \
+ mv /workspace/tf-flex-series-stable-diffusion-inference/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/patch . && \
+ git apply patch && \
+ pip install matplotlib && \
+ pip install .
+
+RUN python -m pip install scikit-image
+
+COPY LICENSE license/LICENSE
+COPY third_party license/third_party
diff --git a/docker/max-gpu/docker-compose.yml b/docker/max-gpu/docker-compose.yml
new file mode 100644
index 000000000..3adbd29dc
--- /dev/null
+++ b/docker/max-gpu/docker-compose.yml
@@ -0,0 +1,86 @@
+#
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2023 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.
+#
+
+#
+
+version: '3'
+services:
+ pytorch-resnet50v1-5-inference:
+ build:
+ context: ../../
+ args:
+ http_proxy: ${http_proxy}
+ https_proxy: ${https_proxy}
+ no_proxy: ${no_proxy}
+ MAX_PYT_BASE_IMAGE: ${MAX_PYT_BASE_IMAGE:-intel/intel-extension-for-pytorch}
+ MAX_PYT_BASE_TAG: ${MAX_PYT_BASE_TAG:-xpu-max}
+ dockerfile: docker/max-gpu/pytorch-resnet50v1-5-inference/pytorch-max-series-resnet50v1-5-inference.Dockerfile
+ command: >
+ sh -c "python -c 'import torch; import intel_extension_for_pytorch as ipex; print(\"torch:\", torch.__version__, \" ipex:\",ipex.__version__)'"
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-max-gpu-resnet50v1-5-inference
+ pull_policy: always
+ pytorch-resnet50v1-5-training:
+ build:
+ args:
+ VOC_LABELS_URL: ${VOC_LABELS_URL:-https://drive.google.com/uc?id=1q1sXhKIxniInw3WASnEDKYMqPMuiDDvc}
+ dockerfile: docker/max-gpu/pytorch-bert-large-inference/pytorch-max-series-bert-large-inference.Dockerfile
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-pytorch-max-gpu-resnet50v1-5-training
+ pytorch-bert-large-inference:
+ build:
+ dockerfile: docker/max-gpu/pytorch-bert-large-inference/pytorch-max-series-bert-large-inference.Dockerfile
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-language-modeling-pytorch-max-gpu-bert-large-inference
+ pytorch-bert-large-training:
+ build:
+ dockerfile: docker/max-gpu/pytorch-bert-large-training/pytorch-max-series-bert-large-training.Dockerfile
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-language-modeling-pytorch-max-gpu-bert-large-training
+ tf-resnet50v1-5-inference:
+ build:
+ args:
+ MAX_TF_BASE_IMAGE: ${MAX_TF_BASE_IMAGE:-intel/intel-extension-for-tensorflow}
+ MAX_TF_BASE_TAG: ${MAX_TF_BASE_TAG:-gpu-horovod}
+ INT8_MODEL_URL: ${INT8_MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/resnet50_v1_int8.pb}
+ FP16_MODEL_URL: ${FP16_MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/resnet50_v1.pb}
+ FP32_MODEL_URL: ${FP32_MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/resnet50_v1.pb}
+ dockerfile: docker/max-gpu/tf-resnet50v1-5-inference/tf-max-series-resnet50v1-5-inference.Dockerfile
+ command: >
+ sh -c "python -c 'import tensorflow as tf; print(tf.__version__)'"
+ extends: pytorch-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-max-gpu-resnet50v1-5-inference
+ tf-resnet50v1-5-training:
+ build:
+ dockerfile: docker/max-gpu/tf-resnet50v1-5-training/tf-max-series-resnet50v1-5-training.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-image-recognition-tf-max-gpu-resnet50v1-5-training
+ tf-bert-large-inference:
+ build:
+ args:
+ MODEL_URL: ${MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/v2_7_0/fp32_bert_squad.pb}
+ dockerfile: docker/max-gpu/tf-bert-large-inference/tf-max-series-bert-large-inference.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-language-modeling-tf-max-gpu-bert-large-inference
+ tf-bert-large-training:
+ build:
+ args:
+ MODEL_URL: ${MODEL_URL:-https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/resnet50_v1_int8.pb}
+ dockerfile: docker/max-gpu/tf-bert-large-training/tf-max-series-bert-large-training.Dockerfile
+ extends: tf-resnet50v1-5-inference
+ image: ${REGISTRY}/aiops/mlops-ci:b-${GITHUB_RUN_NUMBER:-0}-language-modeling-tf-max-gpu-bert-large-training
+
diff --git a/docker/max-gpu/pytorch-bert-large-inference/tests.yml b/docker/max-gpu/pytorch-bert-large-inference/tests.yml
index 840b7c84d..554cc55b7 100644
--- a/docker/max-gpu/pytorch-bert-large-inference/tests.yml
+++ b/docker/max-gpu/pytorch-bert-large-inference/tests.yml
@@ -8,10 +8,8 @@ pytorch-max-gpu-bert-large-inference:
Tile: 2
DATASET_DIR: /pytorch/squad_data
BERT_WEIGHT: /pytorch/squad_large_finetuned_checkpoint
- OUTPUT_DIR: /output/pytorch-max-gpu-bert-large-inference
DOCKER_ARGS: --ipc=host --privileged --device=/dev/dri
volumes:
- OUTPUT_DIR: /output/pytorch-max-gpu-bert-large-inference
DATASET_DIR: /pytorch/squad_data
BERT_WEIGHT: /pytorch/squad_large_finetuned_checkpoint
diff --git a/tools/docker/tests/pytorch/import-torch.sh b/docker/pyt-cpu/Makefile
old mode 100755
new mode 100644
similarity index 63%
rename from tools/docker/tests/pytorch/import-torch.sh
rename to docker/pyt-cpu/Makefile
index 4b0ced8b4..f0ae20dfb
--- a/tools/docker/tests/pytorch/import-torch.sh
+++ b/docker/pyt-cpu/Makefile
@@ -1,8 +1,7 @@
-#!/usr/bin/env bash
#
# -*- coding: utf-8 -*-
#
-# Copyright (c) 2021 Intel Corporation
+# Copyright (c) 2023 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,23 +16,11 @@
# limitations under the License.
#
+#
-die() {
- echo $@
- exit 1
-}
-
-python -c '
-try:
- import torch
- print(True)
-except:
- print(False)
-'
-pytorch_available=$?
-
-if [[ $pytorch_available -eq 0 ]]; then
- echo "PASS: Pytorch is available"
-else
- die "FAIL: Could not import pytorch"
-fi
+PYT_BASE_IMAGE=intel/intel-extension-for-pytorch
+PYT_BASE_TAG=2.0.0-pip-base
+all:
+ @PYT_BASE_IMAGE=${PYT_BASE_IMAGE} \
+ PYT_BASE_TAG=${PYT_BASE_TAG} \
+ docker compose -f pyt-cpu-docker-compose.yml up --build
diff --git a/docker/pyt-cpu/pyt-cpu-docker-compose.yml b/docker/pyt-cpu/pyt-cpu-docker-compose.yml
new file mode 100644
index 000000000..aaef60bd8
--- /dev/null
+++ b/docker/pyt-cpu/pyt-cpu-docker-compose.yml
@@ -0,0 +1,36 @@
+#
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2023 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.
+#
+
+#
+
+version: '3'
+services:
+ pytorch-spr-bert-large-inference:
+ image: intel/language-modeling:pytorch-spr-bert-large-inference
+ pull_policy: always
+ build:
+ context: ../../
+ args:
+ http_proxy: ${http_proxy}
+ https_proxy: ${https_proxy}
+ no_proxy: ${no_proxy}
+ PYT_BASE_IMAGE: ${PYT_BASE_IMAGE:-intel/intel-extension-for-pytorch}
+ PYT_BASE_TAG: ${PYT_BASE_TAG:-2.0.0-pip-base}
+ dockerfile: docker/pyt-cpu/spr-bert-large-inference/pytorch-spr-bert-large-inference.Dockerfile
+ command: >
+ bash -c "python -c 'import torch; import intel_extension_for_pytorch as ipex; print(\"torch:\", torch.__version__, \" ipex:\",ipex.__version__)'"
diff --git a/docker/pyt-cpu/spr-bert-large-inference/pytorch-spr-bert-large-inference.Dockerfile b/docker/pyt-cpu/spr-bert-large-inference/pytorch-spr-bert-large-inference.Dockerfile
new file mode 100644
index 000000000..89919ac0d
--- /dev/null
+++ b/docker/pyt-cpu/spr-bert-large-inference/pytorch-spr-bert-large-inference.Dockerfile
@@ -0,0 +1,76 @@
+# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+ARG PYT_BASE_IMAGE="intel/intel-extension-for-pytorch"
+ARG PYT_BASE_TAG="2.0.0-pip-base"
+
+FROM ${PYT_BASE_IMAGE}:${PYT_BASE_TAG} AS intel-extension-for-pytorch
+RUN apt-get update && \
+ apt-get install --no-install-recommends --fix-missing -y \
+ build-essential \
+ ca-certificates \
+ git \
+ wget \
+ make \
+ cmake \
+ g++ \
+ gcc \
+ autoconf \
+ bzip2 \
+ tar
+
+RUN wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
+ tar -xzf gperftools-2.7.90.tar.gz && \
+ cd gperftools-2.7.90 && \
+ mkdir -p /workspace/lib/ && \
+ ./configure --prefix=/workspace/lib/tcmalloc/ && \
+ make && \
+ make install
+
+WORKDIR /workspace/pytorch-spr-bert-large-inference
+COPY models/language_modeling/pytorch/common/enable_ipex_for_transformers.diff models/language_modeling/pytorch/common/enable_ipex_for_transformers.diff
+COPY quickstart/language_modeling/pytorch/bert_large/inference/cpu/configure.json quickstart/configure.json
+COPY quickstart/language_modeling/pytorch/bert_large/inference/cpu/run_accuracy.sh quickstart/run_accuracy.sh
+COPY quickstart/language_modeling/pytorch/bert_large/inference/cpu/run_calibration.sh quickstart/run_calibration.sh
+COPY quickstart/language_modeling/pytorch/bert_large/inference/cpu/run_multi_instance_realtime.sh quickstart/run_multi_instance_realtime.sh
+COPY quickstart/language_modeling/pytorch/bert_large/inference/cpu/run_multi_instance_throughput.sh quickstart/run_multi_instance_throughput.sh
+
+RUN cd quickstart && \
+ git clone https://github.com/huggingface/transformers.git && \
+ cd transformers && \
+ git checkout v4.28.1 && \
+ git apply /workspace/pytorch-spr-bert-large-inference/models/language_modeling/pytorch/common/enable_ipex_for_transformers.diff && \
+ pip install -e ./ && \
+ pip install tensorboard && \
+ pip install intel-openmp
+
+ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
+
+# ENV LD_PRELOAD="/workspace/lib/tcmalloc/lib/libtcmalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
+ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
+
+RUN apt-get update && \
+ apt-get install --no-install-recommends --fix-missing -y \
+ numactl \
+ libegl1-mesa
+
+COPY LICENSE licenses/LICENSE
+COPY third_party licenses/third_party
diff --git a/docker/pyt-cpu/spr-bert-large-inference/tests.yml b/docker/pyt-cpu/spr-bert-large-inference/tests.yml
new file mode 100644
index 000000000..f3227b116
--- /dev/null
+++ b/docker/pyt-cpu/spr-bert-large-inference/tests.yml
@@ -0,0 +1,214 @@
+---
+pytorch-spr-bert-large-inference:
+ image_name: intel/language-modeling:pytorch-spr-bert-large-inference
+ tests:
+ - test_name: BERT Large FP32 Online inference
+ env_vars:
+ PRECISION: fp32
+ SCRIPT: quickstart/run_multi_instance_realtime.sh
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/fp32/real_time
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/fp32/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large FP32 Throughput inference
+ env_vars:
+ PRECISION: fp32
+ SCRIPT: quickstart/run_multi_instance_throughput.sh
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/fp32/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/fp32/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large FP32 Accuracy
+ env_vars:
+ PRECISION: fp32
+ SCRIPT: quickstart/run_accuracy.sh
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/fp32/accuracy
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/fp32/accuracy
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large BFloat16 Online inference
+ env_vars:
+ PRECISION: bf16
+ SCRIPT: quickstart/run_multi_instance_realtime.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/bf16/real_time
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/bf16/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large BFloat16 Throughput inference
+ env_vars:
+ PRECISION: bf16
+ SCRIPT: quickstart/run_multi_instance_throughput.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/bf16/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/bf16/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large BFloat16 Accuracy
+ env_vars:
+ PRECISION: bf16
+ SCRIPT: quickstart/run_accuracy.sh
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/bf16/accuracy
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/bf16/accuracy
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large INT8 Online inference
+ env_vars:
+ PRECISION: int8
+ SCRIPT: quickstart/run_multi_instance_realtime.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/int8/real_time
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/int8/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large INT8 Throughput inference
+ env_vars:
+ PRECISION: int8
+ SCRIPT: quickstart/run_multi_instance_throughput.sh
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/int8/throughput
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/int8/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large INT8 Accuracy
+ env_vars:
+ PRECISION: int8
+ SCRIPT: quickstart/run_accuracy.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/int8/accuracy
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/int8/accuracy
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large avx-int8 Online inference
+ env_vars:
+ PRECISION: avx-int8
+ SCRIPT: quickstart/run_multi_instance_realtime.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-int8/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-int8/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large avx-int8 Throughput inference
+ env_vars:
+ PRECISION: avx-int8
+ SCRIPT: quickstart/run_multi_instance_throughput.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-int8/throughput
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-int8/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large avx-int8 Accuracy
+ env_vars:
+ PRECISION: avx-int8
+ SCRIPT: quickstart/run_accuracy.sh
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-int8/accuracy
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-int8/accuracy
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large avx-fp32 Online inference
+ env_vars:
+ PRECISION: avx-fp32
+ SCRIPT: quickstart/run_multi_instance_realtime.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-fp32/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-fp32/real_time
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large avx-fp32 Throughput inference
+ env_vars:
+ PRECISION: avx-fp32
+ SCRIPT: quickstart/run_multi_instance_throughput.sh
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-fp32/throughput
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-fp32/throughput
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
+ - test_name: BERT Large avx-fp32 Accuracy
+ env_vars:
+ PRECISION: avx-fp32
+ SCRIPT: quickstart/run_accuracy.sh
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-fp32/accuracy
+ INT8_CONFIG: /workspace/pytorch-spr-bert-large-inference/quickstart/configure.json
+ EVAL_SCRIPT: /workspace/pytorch-spr-bert-large-inference/quickstart/transformers/examples/legacy/question-answering/run_squad.py
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ FINETUNED_MODEL: /localdisk/sramakr1/bert_squad_model
+ DOCKER_ARGS: --privileged --init --shm-size 8G -w /workspace/pytorch-spr-bert-large-inference
+ volumes:
+ OUTPUT_DIR: /output/pytorch-spr-bert-large-inference/avx-fp32/accuracy
+ EVAL_DATA_FILE: /localdisk/sramakr1/eval_data_file/dev-v1.1.json
+ PRETRAINED_MODEL: /localdisk/sramakr1/bert_squad_model
diff --git a/dockerfiles/dataset_containers/intel-tf-object-detection-preprocess-coco-val.Dockerfile b/dockerfiles/dataset_containers/intel-tf-object-detection-preprocess-coco-val.Dockerfile
deleted file mode 100644
index 32794e096..000000000
--- a/dockerfiles/dataset_containers/intel-tf-object-detection-preprocess-coco-val.Dockerfile
+++ /dev/null
@@ -1,131 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="1efe98bb8e8d98bbffc703a90d88df15fc2ce906"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="preprocess-coco-val"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-CMD scripts/preprocess_coco_val.sh
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/pytorch-flex-series-resnet50v1-5-inference.Dockerfile b/dockerfiles/gpu_model_containers/pytorch-flex-series-resnet50v1-5-inference.Dockerfile
deleted file mode 100644
index c53c8475b..000000000
--- a/dockerfiles/gpu_model_containers/pytorch-flex-series-resnet50v1-5-inference.Dockerfile
+++ /dev/null
@@ -1,71 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-flex"
-
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-flex-series-resnet50v1-5-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/pytorch-flex-series-ssd-mobilenet-inference.Dockerfile b/dockerfiles/gpu_model_containers/pytorch-flex-series-ssd-mobilenet-inference.Dockerfile
deleted file mode 100644
index 4c8a756c1..000000000
--- a/dockerfiles/gpu_model_containers/pytorch-flex-series-ssd-mobilenet-inference.Dockerfile
+++ /dev/null
@@ -1,101 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-flex"
-
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG PY_VERSION=3.10
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN pip install opencv-python
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' \
- pycocotools \
- opencv-python-headless \
- pandas \
- 'pillow>=9.3.0' \
- pycocotools \
- opencv-python-headless \
- pandas
-
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-flex-series-ssd-mobilenet-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/pytorch-max-series-bert-large-inference.Dockerfile b/dockerfiles/gpu_model_containers/pytorch-max-series-bert-large-inference.Dockerfile
deleted file mode 100644
index 2ad2cbdc3..000000000
--- a/dockerfiles/gpu_model_containers/pytorch-max-series-bert-large-inference.Dockerfile
+++ /dev/null
@@ -1,79 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-max"
-
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-max-series-bert-large-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ARG PACKAGE_NAME="pytorch-max-series-bert-large-inference"
-ARG MODEL_WORKSPACE
-
-RUN cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/language_modeling/pytorch/bert_large/inference/gpu && \
- pip install -r requirements.txt
-
-RUN cd -
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/pytorch-max-series-bert-large-training.Dockerfile b/dockerfiles/gpu_model_containers/pytorch-max-series-bert-large-training.Dockerfile
deleted file mode 100644
index ae41e48a3..000000000
--- a/dockerfiles/gpu_model_containers/pytorch-max-series-bert-large-training.Dockerfile
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-max"
-
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
-
-
-RUN curl -fsSL https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB | apt-key add -
-RUN echo "deb [trusted=yes] https://apt.repos.intel.com/oneapi all main " > /etc/apt/sources.list.d/oneAPI.list
-
-RUN apt-get update && \
- DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
- ca-certificates \
- intel-oneapi-mpi-devel=2021.8.0-25329 \
- intel-oneapi-ccl=2021.8.0-25371 \
- && \
- rm -rf /var/lib/apt/lists/*
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-max-series-bert-large-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ARG PACKAGE_NAME="pytorch-max-series-bert-large-training"
-ARG MODEL_WORKSPACE
-
-RUN pip install -r ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/language_modeling/pytorch/bert_large/training/gpu/requirements.txt
-
-RUN cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/language_modeling/pytorch/bert_large/training/gpu/data/ && \
- wget https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt && \
- mv bert-base-uncased-vocab.txt vocab. && \
- cd -
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/pytorch-max-series-resnet50v1-5-inference.Dockerfile b/dockerfiles/gpu_model_containers/pytorch-max-series-resnet50v1-5-inference.Dockerfile
deleted file mode 100644
index 7083fe234..000000000
--- a/dockerfiles/gpu_model_containers/pytorch-max-series-resnet50v1-5-inference.Dockerfile
+++ /dev/null
@@ -1,71 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-max"
-
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-max-series-resnet50v1-5-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/pytorch-max-series-resnet50v1-5-training.Dockerfile b/dockerfiles/gpu_model_containers/pytorch-max-series-resnet50v1-5-training.Dockerfile
deleted file mode 100644
index 4766c9f38..000000000
--- a/dockerfiles/gpu_model_containers/pytorch-max-series-resnet50v1-5-training.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_BASE_IMAGE="intel/intel-extension-for-pytorch"
-ARG PYTORCH_BASE_TAG="xpu-max"
-
-FROM ${PYTORCH_BASE_IMAGE}:${PYTORCH_BASE_TAG}
-
-RUN curl -fsSL https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB | apt-key add -
-RUN echo "deb [trusted=yes] https://apt.repos.intel.com/oneapi all main " > /etc/apt/sources.list.d/oneAPI.list
-
-RUN apt-get update && \
- DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
- ca-certificates \
- intel-oneapi-mpi-devel=2021.8.0-25329 \
- intel-oneapi-ccl=2021.8.0-25371 \
- && \
- rm -rf /var/lib/apt/lists/*
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-max-series-resnet50v1-5-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/tf-flex-series-resnet50v1-5-inference.Dockerfile b/dockerfiles/gpu_model_containers/tf-flex-series-resnet50v1-5-inference.Dockerfile
deleted file mode 100644
index d3686d9e7..000000000
--- a/dockerfiles/gpu_model_containers/tf-flex-series-resnet50v1-5-inference.Dockerfile
+++ /dev/null
@@ -1,71 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_BASE_IMAGE="intel/intel-extension-for-tensorflow"
-ARG TENSORFLOW_BASE_TAG="gpu-flex"
-
-FROM ${TENSORFLOW_BASE_IMAGE}:${TENSORFLOW_BASE_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-flex-series-resnet50v1-5-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/tf-flex-series-ssd-mobilenet-inference.Dockerfile b/dockerfiles/gpu_model_containers/tf-flex-series-ssd-mobilenet-inference.Dockerfile
deleted file mode 100644
index 106cc40f7..000000000
--- a/dockerfiles/gpu_model_containers/tf-flex-series-ssd-mobilenet-inference.Dockerfile
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_BASE_IMAGE="intel/intel-extension-for-tensorflow"
-ARG TENSORFLOW_BASE_TAG="gpu-flex"
-
-FROM ${TENSORFLOW_BASE_IMAGE}:${TENSORFLOW_BASE_TAG}
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG PY_VERSION=3.10
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-flex-series-ssd-mobilenet-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/tf-max-series-bert-large-inference.Dockerfile b/dockerfiles/gpu_model_containers/tf-max-series-bert-large-inference.Dockerfile
deleted file mode 100644
index 54583fda2..000000000
--- a/dockerfiles/gpu_model_containers/tf-max-series-bert-large-inference.Dockerfile
+++ /dev/null
@@ -1,71 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_BASE_IMAGE="intel/intel-extension-for-tensorflow"
-ARG TENSORFLOW_BASE_TAG="gpu-max"
-
-FROM ${TENSORFLOW_BASE_IMAGE}:${TENSORFLOW_BASE_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-max-series-bert-large-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/tf-max-series-bert-large-training.Dockerfile b/dockerfiles/gpu_model_containers/tf-max-series-bert-large-training.Dockerfile
deleted file mode 100644
index 43dc106b3..000000000
--- a/dockerfiles/gpu_model_containers/tf-max-series-bert-large-training.Dockerfile
+++ /dev/null
@@ -1,87 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_BASE_IMAGE="intel/intel-extension-for-tensorflow"
-ARG TENSORFLOW_BASE_TAG="gpu-max"
-
-FROM ${TENSORFLOW_BASE_IMAGE}:${TENSORFLOW_BASE_TAG}
-
-RUN curl -fsSL https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB | apt-key add -
-RUN echo "deb [trusted=yes] https://apt.repos.intel.com/oneapi all main " > /etc/apt/sources.list.d/oneAPI.list
-
-RUN apt-get update && \
- DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
- ca-certificates \
- intel-oneapi-mpi-devel=2021.8.0-25329 \
- intel-oneapi-ccl=2021.8.0-25371 \
- && \
- rm -rf /var/lib/apt/lists/*
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-max-series-bert-large-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ARG PACKAGE_NAME="tf-max-series-bert-large-training"
-ARG MODEL_WORKSPACE
-
-RUN git apply ${MODEL_WORKSPACE}/${PACKAGE_NAME}/quickstart/hvs_support.patch
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/tf-max-series-resnet50v1-5-inference.Dockerfile b/dockerfiles/gpu_model_containers/tf-max-series-resnet50v1-5-inference.Dockerfile
deleted file mode 100644
index db0bbb34b..000000000
--- a/dockerfiles/gpu_model_containers/tf-max-series-resnet50v1-5-inference.Dockerfile
+++ /dev/null
@@ -1,71 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_BASE_IMAGE="intel/intel-extension-for-tensorflow"
-ARG TENSORFLOW_BASE_TAG="gpu-max"
-
-FROM ${TENSORFLOW_BASE_IMAGE}:${TENSORFLOW_BASE_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-max-series-resnet50v1-5-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/gpu_model_containers/tf-max-series-resnet50v1-5-training.Dockerfile b/dockerfiles/gpu_model_containers/tf-max-series-resnet50v1-5-training.Dockerfile
deleted file mode 100644
index 294a483d5..000000000
--- a/dockerfiles/gpu_model_containers/tf-max-series-resnet50v1-5-training.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_BASE_IMAGE="intel/intel-extension-for-tensorflow"
-ARG TENSORFLOW_BASE_TAG="gpu-max"
-
-FROM ${TENSORFLOW_BASE_IMAGE}:${TENSORFLOW_BASE_TAG}
-
-RUN curl -fsSL https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB | apt-key add -
-RUN echo "deb [trusted=yes] https://apt.repos.intel.com/oneapi all main " > /etc/apt/sources.list.d/oneAPI.list
-
-RUN apt-get update && \
- DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
- ca-certificates \
- intel-oneapi-mpi-devel=2021.8.0-25329 \
- intel-oneapi-ccl=2021.8.0-25371 \
- && \
- rm -rf /var/lib/apt/lists/*
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-max-series-resnet50v1-5-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-[ -f /opt/intel/oneapi/setvars.sh ] && . /opt/intel/oneapi/setvars.sh\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/intel-tf-language-modeling.Dockerfile b/dockerfiles/intel-tf-language-modeling.Dockerfile
deleted file mode 100644
index ed2f5e000..000000000
--- a/dockerfiles/intel-tf-language-modeling.Dockerfile
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
diff --git a/dockerfiles/intel-tf-language-translation.Dockerfile b/dockerfiles/intel-tf-language-translation.Dockerfile
deleted file mode 100644
index ed2f5e000..000000000
--- a/dockerfiles/intel-tf-language-translation.Dockerfile
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
diff --git a/dockerfiles/intel-tf-object-detection.Dockerfile b/dockerfiles/intel-tf-object-detection.Dockerfile
deleted file mode 100644
index f140f1bed..000000000
--- a/dockerfiles/intel-tf-object-detection.Dockerfile
+++ /dev/null
@@ -1,84 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
diff --git a/dockerfiles/lpot/tensorflow/README.md b/dockerfiles/lpot/tensorflow/README.md
deleted file mode 100644
index 2d5eaa514..000000000
--- a/dockerfiles/lpot/tensorflow/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
- # LPOT Containers with Intel® Optimizations for TensorFlow
-
-The dockerfiles in this directory use the
-[intel/intel-optimized-tensorflow](https://hub.docker.com/r/intel/intel-optimized-tensorflow)
-images as their base, and include an install of the
-[Intel® Low Precision Optimization Tool](https://github.com/intel/lpot).
-The model-specific dockerfiles also include the pretrained model to allow running the
-[LPOT TensorFlow examples](https://github.com/intel/lpot/tree/master/examples/tensorflow)
-to demonstrate how the tool quantizes the frozen graph.
-
-## Building the containers
-
-If you would like to build your own LPOT container, this section has instructions
-on how to do that. The docker containers can be built using either the dockerfiles
-in this directory or the [model-builder](/tools/scripts/model-builder):
-
-* Build the LPOT container from the dockerfile using the following command:
- ```
- docker build \
- --build-arg http_proxy=$http_proxy \
- --build-arg https_proxy=$http_proxy \
- --build-arg TENSORFLOW_TAG=2.5.0-ubuntu-20.04 \
- --build-arg PY_VERSION=3.7 \
- -f intel-tf-lpot.Dockerfile \
- -t intel-optimized-tensorflow:2.5.0-ubuntu-20.04-lpot .
- ```
- To build the model-specific dockerfiles, substitute in the name the dockerfile
- that you want to build, and update the name in the `-t` arg to the name your container.
-
-* To build the LPOT containers using the model-builder, first follow the
- [instructions for getting your environment setup to run the script](https://github.com/IntelAI/models/tree/master/tools#model-builder-setup).
- After the setup is done, you can build all the LPOT containers using:
- ```
- model-builder --verbose build -f lpot
- ```
- To build a single container, specify the name of the spec like:
- ```
- model-builder --verbose build -f lpot
- ```
-
-## Running the container
-
-### Running the TensorFlow LPOT Container
-
-This container has Intel-optimized TensorFlow and LPOT installed, and it
-includes a clone of the [LPOT repo](https://github.com/intel/lpot/) at `/src/lpot`.
-There are [examples](https://github.com/intel/lpot/tree/master/examples/tensorflow)
-that you can run in the LPOT repo, or you can use this container to run
-quantization on your own model.
-
-For example, the command snippet below shows how to use this container to run the
-image recognition tuning script on a ResNet v1.5 frozen graph and config yaml file
-mounted from a directory on the system. The directory that has the model and config
-file are being mounted in the container as the `MODEL_DIR`. In addition to the model
-directory, the dataset directory and an output folder are also being mounted in the
-container. The tuning script is being run in the container with the parameters
-pointing to the model and config file in the `MODEL_DIR`.
-```
-MODEL_DIR=
-DATASET_DIR=
-OUTPUT_DIR=
-
-docker run \
- --env http_proxy=$http_proxy \
- --env https_proxy=$https_proxy \
- --env DATASET_DIR=${DATASET_DIR} \
- --env OUTPUT_DIR=${OUTPUT_DIR} \
- --env MODEL_DIR=${MODEL_DIR} \
- -v ${DATASET_DIR}:${DATASET_DIR} \
- -v ${OUTPUT_DIR}:${OUTPUT_DIR} \
- -v ${MODEL_DIR}:${MODEL_DIR} \
- -w /src/lpot/examples/tensorflow/image_recognition \
- -it intel-optimized-tensorflow:2.5.0-ubuntu-20.04-lpot \
- /bin/bash run_tuning.sh --config=${MODEL_DIR}/resnet50_v1_5.yaml \
- --input_model=${MODEL_DIR}/resnet50_v1.pb \
- --output_model=${OUTPUT_DIR}/lpot_resnet50_v15.pb
-```
-
-For more information on running LPOT, see the instructions and getting
-started links in the [LPOT repo](https://github.com/intel/lpot#getting-started).
diff --git a/dockerfiles/lpot/tensorflow/intel-tf-lpot-inceptionv3.Dockerfile b/dockerfiles/lpot/tensorflow/intel-tf-lpot-inceptionv3.Dockerfile
deleted file mode 100644
index 3fe4c7fc0..000000000
--- a/dockerfiles/lpot/tensorflow/intel-tf-lpot-inceptionv3.Dockerfile
+++ /dev/null
@@ -1,53 +0,0 @@
-# Copyright (c) 2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="2.5.0-ubuntu-20.04"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PY_VERSION="3.8"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN pip install lpot
-
-ARG LPOT_SOURCE_DIR=/src/lpot
-ARG LPOT_BRANCH=master
-
-ENV LPOT_SOURCE_DIR=$LPOT_SOURCE_DIR
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone --single-branch --branch ${LPOT_BRANCH} https://github.com/intel/lpot.git ${LPOT_SOURCE_DIR}
-
-WORKDIR ${LPOT_SOURCE_DIR}
-
-RUN apt-get install --no-install-recommends --fix-missing -y wget
-
-WORKDIR ${LPOT_SOURCE_DIR}/examples/tensorflow/image_recognition
-
-RUN wget https://storage.googleapis.com/intel-optimized-tensorflow/models/v1_6/inceptionv3_fp32_pretrained_model.pb
-ENV PRETRAINED_MODEL=${PWD}/inceptionv3_fp32_pretrained_model.pb
diff --git a/dockerfiles/ml/XGBoost/README.md b/dockerfiles/ml/XGBoost/README.md
deleted file mode 100644
index be6539f82..000000000
--- a/dockerfiles/ml/XGBoost/README.md
+++ /dev/null
@@ -1,4 +0,0 @@
-# XGBoost
-Here you can find Docker file for XGBoost
-
-It's based on XGBoost conda package from Intel channel
diff --git a/dockerfiles/ml/XGBoost/xgboost.Dockerfile b/dockerfiles/ml/XGBoost/xgboost.Dockerfile
deleted file mode 100644
index 3f8f7392c..000000000
--- a/dockerfiles/ml/XGBoost/xgboost.Dockerfile
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG UBUNTU_VERSION="20.04"
-
-FROM ubuntu:${UBUNTU_VERSION}
-
-ARG CONDA_INSTALL_PATH=/opt/conda
-
-ARG MINICONDA_VERSION="4.7.12"
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- wget \
- ca-certificates && \
- wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-${MINICONDA_VERSION}-Linux-x86_64.sh -O miniconda.sh && \
- bash miniconda.sh -b -p ${CONDA_INSTALL_PATH} && \
- rm miniconda.sh && \
- ln -s ${CONDA_INSTALL_PATH}/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \
- echo ". ${CONDA_INSTALL_PATH}/etc/profile.d/conda.sh" >> ~/.bashrc && \
- echo "conda activate base" >> ~/.bashrc
-
-ENV PATH="${CONDA_INSTALL_PATH}/bin:${PATH}"
-
-ARG PY_VERSION="3"
-ARG INTEL_PY_BUILD="2021.3.0"
-
-RUN conda config --add channels intel && \
- conda install -y -q intelpython${PY_VERSION}_core==${INTEL_PY_BUILD} python=${PY_VERSION}
-
-RUN conda config --add channels intel \
- && conda install -y -q xgboost \
- && conda clean --all
diff --git a/dockerfiles/ml/scikit-learn-databricks/README.md b/dockerfiles/ml/scikit-learn-databricks/README.md
deleted file mode 100644
index 5fd0ab9a6..000000000
--- a/dockerfiles/ml/scikit-learn-databricks/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Scikit-learn daal4py and TensorFlow
-Here you can find Docker file for Scikit-learn
-
-It's based on Scikit-learn and TensorFlow conda packages from Intel channel
-
-To build the container try this:
-```
-docker build -f scikit-learn-databricks.Dockerfile . -t intel/intel-optimized-ml:tf-2.4.0-scikit-learn
-```
-
-To run the workflow try this:
-```
-docker run -it intel/intel-optimized-ml:tf-2.4.0-scikit-learn bash
-```
diff --git a/dockerfiles/ml/scikit-learn-databricks/intel.yml b/dockerfiles/ml/scikit-learn-databricks/intel.yml
deleted file mode 100644
index 1b4e89ff5..000000000
--- a/dockerfiles/ml/scikit-learn-databricks/intel.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-name: intel
-channels:
- - intel
- - defaults
-dependencies:
- - intel::numpy=1.19.2
- - intel::python=3.7.9
- - intel::scikit-learn=0.23.2
- - ipykernel=5.1.4
- - ipython=7.12.0
- - pandas=1.0.5
- - pip=20.0.2
- - six=1.15.0
- - pip:
- - pyarrow==0.17.0
- - intel-tensorflow==2.4.0
diff --git a/dockerfiles/ml/scikit-learn-databricks/scikit-learn-databricks.Dockerfile b/dockerfiles/ml/scikit-learn-databricks/scikit-learn-databricks.Dockerfile
deleted file mode 100644
index f79595570..000000000
--- a/dockerfiles/ml/scikit-learn-databricks/scikit-learn-databricks.Dockerfile
+++ /dev/null
@@ -1,62 +0,0 @@
-# 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.
-#
-
-ARG UBUNTU_VERSION=18.04
-
-FROM ubuntu:${UBUNTU_VERSION}
-
-ARG CONDA_INSTALL_PATH=/databricks/conda
-
-ARG MINICONDA_VERSION=4.8.3
-
-# See https://github.com/databricks/containers/blob/master/ubuntu/minimal/Dockerfile
-RUN apt-get update && \
- apt-get install --yes --no-install-recommends --fix-missing \
- bash \
- ca-certificates \
- coreutils \
- iproute2 \
- libc6 \
- openjdk-8-jdk-headless \
- procps \
- sudo \
- wget && \
- /var/lib/dpkg/info/ca-certificates-java.postinst configure && \
- rm -rf /var/lib/apt/lists/*
-
-ENV PATH ${CONDA_INSTALL_PATH}/bin:$PATH
-
-RUN wget -q https://repo.continuum.io/miniconda/Miniconda3-py37_${MINICONDA_VERSION}-Linux-x86_64.sh -O miniconda.sh && \
- bash miniconda.sh -b -p /databricks/conda && \
- rm miniconda.sh && \
- # Source conda.sh for all login and interactive shells.
- ln -s ${CONDA_INSTALL_PATH}/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \
- echo ". /etc/profile.d/conda.sh" >> ~/.bashrc && \
- # Set always_yes for non-interactive shells.
- conda config --system --set always_yes True && \
- conda clean --all
-
-COPY intel.yml /tmp/env.yml
-
-RUN conda env create --file /tmp/env.yml && \
- rm -f /tmp/env.yml && \
- rm -rf $HOME/.cache/pip/*
-
-RUN conda install -n intel -c intel scipy=1.5.2 --force-reinstall
-
-ENV USE_DAAL4PY_SKLEARN=YES
-
-# Set an environment variable used by Databricks to decide which conda environment to activate by default.
-ENV DEFAULT_DATABRICKS_ROOT_CONDA_ENV=intel
diff --git a/dockerfiles/ml/scikit-learn/census_modin.py b/dockerfiles/ml/scikit-learn/census_modin.py
deleted file mode 100644
index 987e63422..000000000
--- a/dockerfiles/ml/scikit-learn/census_modin.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2018 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.
-#
-
-# Census with Modin and Intel® Data Analytics and Acceleration Library (DAAL) Accelerated Scikit-Learn
-
-# In this example we will be building an end to end machine learning workload with US census from 1970 to 2010.
-# It uses Modin with Ray as compute engine for ETL, and uses Ridge Regression from daal accelerated scikit-learn library
-# to train and predict the US total income according to the education.
-
-# Let's start by downloading census data to your local disk.
-# Go to https://usa.ipums.org/usa-action/extract_requests/download and download ipums_education2income_1970-2010.csv.gz.
-# You many need to register or login to your account to download.
-
-# The data can also be downloader from here: https://rapidsai-data.s3.us-east-2.amazonaws.com/datasets/ipums_education2income_1970-2010.csv.gz
-
-import os
-import numpy as np
-
-from sklearn import config_context
-from sklearn.metrics import mean_squared_error, r2_score
-
-
-# Import Modin and set Ray as the compute engine
-import modin.pandas as pd
-os.environ["MODIN_ENGINE"] = "ray"
-
-
-# Load daal accelerated sklearn patch and import packages from the patch
-import daal4py.sklearn
-daal4py.sklearn.patch_sklearn()
-
-from sklearn.model_selection import train_test_split
-import sklearn.linear_model as lm
-
-
-# Read the data from the downloaded archive file
-df = pd.read_csv('ipums_education2income_1970-2010.csv.gz', compression="gzip")
-
-# ETL
-# clean up unneeded features
-keep_cols = [
- "YEAR", "DATANUM", "SERIAL", "CBSERIAL", "HHWT",
- "CPI99", "GQ", "PERNUM", "SEX", "AGE",
- "INCTOT", "EDUC", "EDUCD", "EDUC_HEAD", "EDUC_POP",
- "EDUC_MOM", "EDUCD_MOM2", "EDUCD_POP2", "INCTOT_MOM", "INCTOT_POP",
- "INCTOT_MOM2", "INCTOT_POP2", "INCTOT_HEAD", "SEX_HEAD",
-]
-df = df[keep_cols]
-
-# clean up samples with invalid income, education, etc.
-df = df.query("INCTOT != 9999999")
-df = df.query("EDUC != -1")
-df = df.query("EDUCD != -1")
-
-# normalize income for inflation
-df["INCTOT"] = df["INCTOT"] * df["CPI99"]
-
-for column in keep_cols:
- df[column] = df[column].fillna(-1)
- df[column] = df[column].astype("float64")
-
-y = df["EDUC"]
-X = df.drop(columns=["EDUC", "CPI99"])
-
-
-# Train the model and predict the income
-# ML - training and inference
-clf = lm.Ridge()
-
-mse_values, cod_values = [], []
-N_RUNS = 50
-TRAIN_SIZE = 0.9
-random_state = 777
-
-X = np.ascontiguousarray(X, dtype=np.float64)
-y = np.ascontiguousarray(y, dtype=np.float64)
-
-# cross validation
-for i in range(N_RUNS):
- X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=TRAIN_SIZE,
- random_state=random_state)
- random_state += 777
-
- # training
- with config_context(assume_finite=True):
- model = clf.fit(X_train, y_train)
-
- # inference
- y_pred = model.predict(X_test)
-
- mse_values.append(mean_squared_error(y_test, y_pred))
- cod_values.append(r2_score(y_test, y_pred))
-
-
-# Check the regression results: mean squared error and r square score
-mean_mse = sum(mse_values)/len(mse_values)
-mean_cod = sum(cod_values)/len(cod_values)
-mse_dev = pow(sum([(mse_value - mean_mse)**2 for mse_value in mse_values])/(len(mse_values) - 1), 0.5)
-cod_dev = pow(sum([(cod_value - mean_cod)**2 for cod_value in cod_values])/(len(cod_values) - 1), 0.5)
-print("mean MSE ± deviation: {:.9f} ± {:.9f}".format(mean_mse, mse_dev))
-print("mean COD ± deviation: {:.9f} ± {:.9f}".format(mean_cod, cod_dev))
-
-
-# Here are our scores:
-# ```
-# mean MSE ± deviation: 0.032564569 ± 0.000041799
-# mean COD ± deviation: 0.995367533 ± 0.000005869
-# ```
-#
diff --git a/dockerfiles/ml/scikit-learn/scikit-learn.Dockerfile b/dockerfiles/ml/scikit-learn/scikit-learn.Dockerfile
deleted file mode 100644
index 84fa03323..000000000
--- a/dockerfiles/ml/scikit-learn/scikit-learn.Dockerfile
+++ /dev/null
@@ -1,62 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG UBUNTU_VERSION="20.04"
-
-FROM ubuntu:${UBUNTU_VERSION}
-
-ARG CONDA_INSTALL_PATH=/opt/conda
-
-ARG MINICONDA_VERSION="4.7.12"
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- wget \
- ca-certificates && \
- wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-${MINICONDA_VERSION}-Linux-x86_64.sh -O miniconda.sh && \
- bash miniconda.sh -b -p ${CONDA_INSTALL_PATH} && \
- rm miniconda.sh && \
- ln -s ${CONDA_INSTALL_PATH}/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \
- echo ". ${CONDA_INSTALL_PATH}/etc/profile.d/conda.sh" >> ~/.bashrc && \
- echo "conda activate base" >> ~/.bashrc
-
-ENV PATH="${CONDA_INSTALL_PATH}/bin:${PATH}"
-
-ARG PY_VERSION="3"
-ARG INTEL_PY_BUILD="2021.3.0"
-
-RUN conda config --add channels intel && \
- conda install -y -q intelpython${PY_VERSION}_core==${INTEL_PY_BUILD} python=${PY_VERSION}
-
-RUN conda install -y -q \
- daal4py \
- scikit-learn-intelex \
- threadpoolctl && \
- conda clean -y --all
-
-ENV PYTHONSTARTUP=${HOME}/.patch_sklearn.py
-
-RUN echo \
-'from sklearnex import patch_sklearn\n\
-from sklearnex import unpatch_sklearn\n\
-patch_sklearn()\n\
-print("To disable Intel(R) Extension for Scikit-learn*, you can run: unpatch_sklearn()")\n' \
->> ${PYTHONSTARTUP}
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-densenet169-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-densenet169-fp32-inference.Dockerfile
deleted file mode 100644
index a576ff3a0..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-densenet169-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="densenet169-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv3-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv3-fp32-inference.Dockerfile
deleted file mode 100644
index d1c5078b2..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv3-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="inceptionv3-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv3-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv3-int8-inference.Dockerfile
deleted file mode 100644
index 04b27dfc0..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv3-int8-inference.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="inceptionv3-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv4-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv4-fp32-inference.Dockerfile
deleted file mode 100644
index b328782bd..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv4-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="inceptionv4-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv4-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv4-int8-inference.Dockerfile
deleted file mode 100644
index 9e4f442df..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-inceptionv4-int8-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="inceptionv4-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-mobilenet-v1-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-mobilenet-v1-fp32-inference.Dockerfile
deleted file mode 100644
index 213e4bae6..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-mobilenet-v1-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,83 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="mobilenet-v1-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-mobilenet-v1-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-mobilenet-v1-int8-inference.Dockerfile
deleted file mode 100644
index 9be7dcfb1..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-mobilenet-v1-int8-inference.Dockerfile
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="mobilenet-v1-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet101-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet101-fp32-inference.Dockerfile
deleted file mode 100644
index c94447efd..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet101-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet101-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet101-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet101-int8-inference.Dockerfile
deleted file mode 100644
index c7c16f3c7..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet101-int8-inference.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet101-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50-fp32-inference.Dockerfile
deleted file mode 100644
index e7c317b85..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50-int8-inference.Dockerfile
deleted file mode 100644
index c5f7dbcf6..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50-int8-inference.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-bfloat16-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-bfloat16-inference.Dockerfile
deleted file mode 100644
index 97af2aa04..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-bfloat16-inference.Dockerfile
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50v1-5-bfloat16-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-bfloat16-training.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-bfloat16-training.Dockerfile
deleted file mode 100644
index 7ccb6a04a..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-bfloat16-training.Dockerfile
+++ /dev/null
@@ -1,139 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50v1-5-bfloat16-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-fp32-inference.Dockerfile
deleted file mode 100644
index 48da573e8..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,83 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50v1-5-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-fp32-training.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-fp32-training.Dockerfile
deleted file mode 100644
index 3206ca6f5..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-fp32-training.Dockerfile
+++ /dev/null
@@ -1,142 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50v1-5-fp32-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-int8-inference.Dockerfile
deleted file mode 100644
index 985fda18b..000000000
--- a/dockerfiles/model_containers/intel-tf-image-recognition-resnet50v1-5-int8-inference.Dockerfile
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="resnet50v1-5-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-segmentation-3d-unet-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-segmentation-3d-unet-fp32-inference.Dockerfile
deleted file mode 100644
index e5b3296c9..000000000
--- a/dockerfiles/model_containers/intel-tf-image-segmentation-3d-unet-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,88 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="3d-unet-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN pip install \
- 'Keras>=2.6.0rc3' \
- 'SimpleITK>=1.2.0' \
- 'nibabel>=2.3.3' \
- 'nilearn>=0.6.2' \
- 'numpy>=1.16.3' \
- 'tables>=3.4.4'
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-segmentation-maskrcnn-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-segmentation-maskrcnn-fp32-inference.Dockerfile
deleted file mode 100644
index 585146069..000000000
--- a/dockerfiles/model_containers/intel-tf-image-segmentation-maskrcnn-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,106 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="maskrcnn-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ARG MASK_RCNN_SOURCE_DIR=/workspace/Mask_RCNN
-
-ENV MODEL_SRC_DIR=${MASK_RCNN_SOURCE_DIR}
-
-RUN pip install \
- IPython[all] \
- 'Pillow>=9.3.0' \
- cython \
- h5py \
- imgaug \
- keras==2.0.8 \
- matplotlib \
- numpy==1.16.3 \
- opencv-python \
- pycocotools \
- scikit-image \
- scipy==1.2.0 && \
- apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- git \
- wget
-
-RUN git clone https://github.com/matterport/Mask_RCNN.git ${MODEL_SRC_DIR} && \
- ( cd ${MODEL_SRC_DIR} && \
- wget https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5 )
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-image-segmentation-unet-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-image-segmentation-unet-fp32-inference.Dockerfile
deleted file mode 100644
index b6b18dcd2..000000000
--- a/dockerfiles/model_containers/intel-tf-image-segmentation-unet-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,103 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG TF_UNET_BRANCH="cpu_optimized"
-
-ARG FETCH_PR="pull/276/head:cpu_optimized"
-
-ARG CODE_DIR=/tensorflow-unet
-
-ENV TF_UNET_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/jakeret/tf_unet.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "$FETCH_PR" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_UNET_BRANCH} )
-
-RUN pip install \
- 'Pillow>=9.3.0' \
- click \
- matplotlib \
- numpy==1.16.3
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="unet-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
-
-RUN apt-get install --no-install-recommends --fix-missing -y tar
diff --git a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-bfloat16-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-bfloat16-inference.Dockerfile
deleted file mode 100644
index 3f59912fe..000000000
--- a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-bfloat16-inference.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="bert-large-bfloat16-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN apt-get install --no-install-recommends --fix-missing -y unzip
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-bfloat16-training.Dockerfile b/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-bfloat16-training.Dockerfile
deleted file mode 100644
index 61edca5a8..000000000
--- a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-bfloat16-training.Dockerfile
+++ /dev/null
@@ -1,146 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="bert-large-bfloat16-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-fp32-inference.Dockerfile
deleted file mode 100644
index 4fbe41da5..000000000
--- a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="bert-large-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN apt-get install --no-install-recommends --fix-missing -y unzip
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-fp32-training.Dockerfile b/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-fp32-training.Dockerfile
deleted file mode 100644
index 1fbef891b..000000000
--- a/dockerfiles/model_containers/intel-tf-language-modeling-bert-large-fp32-training.Dockerfile
+++ /dev/null
@@ -1,146 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="bert-large-fp32-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-language-translation-mlperf-gnmt-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-language-translation-mlperf-gnmt-fp32-inference.Dockerfile
deleted file mode 100644
index c2c0f598e..000000000
--- a/dockerfiles/model_containers/intel-tf-language-translation-mlperf-gnmt-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,115 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="mlperf-gnmt-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-
-RUN apt-get update && apt-get install -y --no-install-recommends \
- build-essential \
- ca-certificates \
- curl \
- unzip \
- git \
- rsync \
- && \
- apt-get clean && \
- rm -rf /var/lib/apt/lists/*
-
-# Set up Bazel
-ENV BAZEL_VERSION 3.0.0
-WORKDIR /
-RUN mkdir /bazel && \
- cd /bazel && \
- curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -O https://github.com/bazelbuild/bazel/releases/download/$BAZEL_VERSION/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh && \
- curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" -fSsL -o /bazel/LICENSE.txt https://raw.githubusercontent.com/bazelbuild/bazel/master/LICENSE && \
- chmod +x bazel-*.sh && \
- ./bazel-$BAZEL_VERSION-installer-linux-x86_64.sh && \
- cd / && \
- rm -f /bazel/bazel-$BAZEL_VERSION-installer-linux-x86_64.sh
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN git clone --single-branch --branch=r0.5 https://github.com/tensorflow/addons.git && \
- (cd addons && \
- git apply ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/language_translation/tensorflow/mlperf_gnmt/gnmt-v0.5.2.patch && \
- echo "y" | bash configure.sh && \
- bazel build --enable_runfiles build_pip_pkg && \
- bazel-bin/build_pip_pkg artifacts && \
- pip install artifacts/tensorflow_addons-*.whl --no-deps) && \
- rm -rf ./addons
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-language-translation-transformer-lt-official-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-language-translation-transformer-lt-official-fp32-inference.Dockerfile
deleted file mode 100644
index bf4663776..000000000
--- a/dockerfiles/model_containers/intel-tf-language-translation-transformer-lt-official-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,53 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="transformer-lt-official-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN pip install Cython pandas
diff --git a/dockerfiles/model_containers/intel-tf-language-translation-transformer-mlperf-bfloat16-training.Dockerfile b/dockerfiles/model_containers/intel-tf-language-translation-transformer-mlperf-bfloat16-training.Dockerfile
deleted file mode 100644
index 6a3d065a0..000000000
--- a/dockerfiles/model_containers/intel-tf-language-translation-transformer-mlperf-bfloat16-training.Dockerfile
+++ /dev/null
@@ -1,139 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="transformer-mlperf-bfloat16-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-language-translation-transformer-mlperf-fp32-training.Dockerfile b/dockerfiles/model_containers/intel-tf-language-translation-transformer-mlperf-fp32-training.Dockerfile
deleted file mode 100644
index a3080e3a5..000000000
--- a/dockerfiles/model_containers/intel-tf-language-translation-transformer-mlperf-fp32-training.Dockerfile
+++ /dev/null
@@ -1,139 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="transformer-mlperf-fp32-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-faster-rcnn-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-faster-rcnn-fp32-inference.Dockerfile
deleted file mode 100644
index aba71430a..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-faster-rcnn-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,129 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="tags/v1.12.0"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="faster-rcnn-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-faster-rcnn-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-faster-rcnn-int8-inference.Dockerfile
deleted file mode 100644
index 5b4410841..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-faster-rcnn-int8-inference.Dockerfile
+++ /dev/null
@@ -1,131 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="tags/v1.12.0"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="faster-rcnn-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-rfcn-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-rfcn-fp32-inference.Dockerfile
deleted file mode 100644
index 8084f8a2a..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-rfcn-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,135 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="6c21084503b27a9ab118e1db25f79957d5ef540b"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="rfcn-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN cd ${TF_MODELS_DIR} && \
- git checkout 6c21084503b27a9ab118e1db25f79957d5ef540b && \
- git apply --ignore-space-change --ignore-whitespace ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/object_detection/tensorflow/rfcn/inference/tf-2.0.patch
-
-RUN apt-get install --no-install-recommends --fix-missing -y tar
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-rfcn-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-rfcn-int8-inference.Dockerfile
deleted file mode 100644
index 2dfed2292..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-rfcn-int8-inference.Dockerfile
+++ /dev/null
@@ -1,137 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="6c21084503b27a9ab118e1db25f79957d5ef540b"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="rfcn-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN cd ${TF_MODELS_DIR} && \
- git checkout 6c21084503b27a9ab118e1db25f79957d5ef540b && \
- git apply --ignore-space-change --ignore-whitespace ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/object_detection/tensorflow/rfcn/inference/tf-2.0.patch
-
-RUN apt-get install --no-install-recommends --fix-missing -y tar
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-mobilenet-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-mobilenet-fp32-inference.Dockerfile
deleted file mode 100644
index cc670727e..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-mobilenet-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,132 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-mobilenet-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-mobilenet-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-mobilenet-int8-inference.Dockerfile
deleted file mode 100644
index ea1ad3f9f..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-mobilenet-int8-inference.Dockerfile
+++ /dev/null
@@ -1,134 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-mobilenet-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-bfloat16-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-bfloat16-inference.Dockerfile
deleted file mode 100644
index 6f1660153..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-bfloat16-inference.Dockerfile
+++ /dev/null
@@ -1,151 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="f505cecde2d8ebf6fe15f40fb8bc350b2b1ed5dc"
-
-ARG FETCH_PR
-
-ARG CODE_DIR="/workspace/tf_models"
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libgl1-mesa-glx \
- libglib2.0-0
-
-RUN pip install opencv-python
-
-RUN pip install tensorflow-addons==0.17.1
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-resnet34-bfloat16-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
-
-ARG TF_BENCHMARKS_BRANCH="509b9d288937216ca7069f31cfb22aaa7db6a4a7"
-
-ARG TF_BENCHMARKS_DIR="/workspace/ssd-resnet-benchmarks"
-
-ENV TF_BENCHMARKS_DIR=${TF_BENCHMARKS_DIR}
-
-RUN apt-get install --no-install-recommends --fix-missing -y git && \
- git clone --single-branch https://github.com/tensorflow/benchmarks.git ${TF_BENCHMARKS_DIR} && \
- ( cd ${TF_BENCHMARKS_DIR} && \
- git checkout ${TF_BENCHMARKS_BRANCH} )
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-bfloat16-training.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-bfloat16-training.Dockerfile
deleted file mode 100644
index dd87168e1..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-bfloat16-training.Dockerfile
+++ /dev/null
@@ -1,198 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="8110bb64ca63c48d0caee9d565e5b4274db2220a"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python3-apt \
- software-properties-common
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- gcc-8 \
- g++-8 && \
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 8 && \
- update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 8
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing curl
-
-RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl && \
- chmod +x ./kubectl && \
- mv kubectl /usr/local/bin
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION="11c1389"
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-RUN apt-get update && \
- apt-get install -y cpio
-
-RUN pip install tensorflow-addons==0.17.1
-
-RUN pip install opencv-python
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-resnet34-bfloat16-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
-
-RUN cd ${TF_MODELS_DIR} && \
- git apply --ignore-space-change --ignore-whitespace ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/object_detection/tensorflow/ssd-resnet34/training/bfloat16/tf-2.0.diff
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-fp32-inference.Dockerfile
deleted file mode 100644
index 30e0742fe..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,152 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="f505cecde2d8ebf6fe15f40fb8bc350b2b1ed5dc"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libgl1-mesa-glx \
- libglib2.0-0
-
-RUN pip install opencv-python
-
-RUN pip install tensorflow-addons==0.17.1
-
-ARG TF_BENCHMARKS_BRANCH="509b9d288937216ca7069f31cfb22aaa7db6a4a7"
-
-ARG TF_BENCHMARKS_DIR="/tensorflow/ssd-resnet-benchmarks"
-
-ENV TF_BENCHMARKS_DIR=${TF_BENCHMARKS_DIR}
-
-RUN apt-get install --no-install-recommends --fix-missing -y git && \
- git clone --single-branch https://github.com/tensorflow/benchmarks.git ${TF_BENCHMARKS_DIR} && \
- ( cd ${TF_BENCHMARKS_DIR} && \
- git checkout ${TF_BENCHMARKS_BRANCH} )
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-resnet34-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-fp32-training.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-fp32-training.Dockerfile
deleted file mode 100644
index 1716f94c7..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-fp32-training.Dockerfile
+++ /dev/null
@@ -1,169 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="8110bb64ca63c48d0caee9d565e5b4274db2220a"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get update && \
- apt-get install -y cpio
-
-RUN pip install tensorflow-addons==0.17.1
-
-RUN pip install opencv-python
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- libopenmpi-dev \
- openmpi-bin \
- openmpi-common \
- openssh-client \
- openssh-server
-
-RUN apt-get install --no-install-recommends --fix-missing -y \
- openssh-client \
- openssh-server \
- systemd && \
- systemctl enable ssh
-
-ARG HOROVOD_VERSION=11c1389
-
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1
-
-# In case installing released versions of Horovod fail,and there is
-# a working commit replace next set of RUN commands with something like:
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- cmake \
- git
-RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-# RUN apt-get update && \
-# apt-get install -y --no-install-recommends --fix-missing \
-# cmake
-#
-# RUN pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-resnet34-fp32-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-int8-inference.Dockerfile
deleted file mode 100644
index 0d646f8c7..000000000
--- a/dockerfiles/model_containers/intel-tf-object-detection-ssd-resnet34-int8-inference.Dockerfile
+++ /dev/null
@@ -1,151 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG PY_VERSION="3.9"
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing \
- build-essential \
- python${PY_VERSION}-dev
-
-ARG TF_MODELS_BRANCH="f505cecde2d8ebf6fe15f40fb8bc350b2b1ed5dc"
-
-ARG FETCH_PR
-
-ARG CODE_DIR="/workspace/tf_models"
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- apt-get install --no-install-recommends --fix-missing -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=. && \
- apt-get remove -y \
- unzip \
- wget && \
- apt-get autoremove -y
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libgl1-mesa-glx \
- libglib2.0-0
-
-RUN pip install opencv-python
-
-RUN pip install tensorflow-addons==0.17.1
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ssd-resnet34-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
-
-ARG TF_BENCHMARKS_BRANCH="509b9d288937216ca7069f31cfb22aaa7db6a4a7"
-
-ARG TF_BENCHMARKS_DIR="/workspace/ssd-resnet-benchmarks"
-
-ENV TF_BENCHMARKS_DIR=${TF_BENCHMARKS_DIR}
-
-RUN apt-get install --no-install-recommends --fix-missing -y git && \
- git clone --single-branch https://github.com/tensorflow/benchmarks.git ${TF_BENCHMARKS_DIR} && \
- ( cd ${TF_BENCHMARKS_DIR} && \
- git checkout ${TF_BENCHMARKS_BRANCH} )
diff --git a/dockerfiles/model_containers/intel-tf-recommendation-ncf-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-recommendation-ncf-fp32-inference.Dockerfile
deleted file mode 100644
index 9650ab3e2..000000000
--- a/dockerfiles/model_containers/intel-tf-recommendation-ncf-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,108 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG TF_MODELS_BRANCH="r1.11"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-RUN pip install \
- google-api-python-client==1.6.7 \
- google-cloud-bigquery==0.31.0 \
- kaggle==1.3.9 \
- numpy==1.16.3 \
- oauth2client==4.1.2 \
- pandas \
- 'psutil>=5.6.7' \
- py-cpuinfo==3.3.0 \
- typing
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="ncf-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN apt-get install --no-install-recommends --fix-missing -y tar
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-fp32-inference.Dockerfile
deleted file mode 100644
index 7e2cea67c..000000000
--- a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,100 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get update && \
- apt-get install -y --no-install-recommends --fix-missing numactl
-
-ARG TF_MODELS_BRANCH="wide-deep-tf2"
-
-ARG FETCH_PR="pull/7461/head:wide-deep-tf2"
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="wide-deep-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN apt-get install --no-install-recommends --fix-missing -y tar
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-fp32-inference.Dockerfile
deleted file mode 100644
index 874cbe959..000000000
--- a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,89 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="wide-deep-large-ds-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python-pandas && \
- pip install pandas
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-fp32-training.Dockerfile b/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-fp32-training.Dockerfile
deleted file mode 100644
index 7cf6fb79f..000000000
--- a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-fp32-training.Dockerfile
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="latest"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="wide-deep-large-ds-fp32-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-int8-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-int8-inference.Dockerfile
deleted file mode 100644
index 820e0898c..000000000
--- a/dockerfiles/model_containers/intel-tf-recommendation-wide-deep-large-ds-int8-inference.Dockerfile
+++ /dev/null
@@ -1,89 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-RUN apt-get install --no-install-recommends --fix-missing -y google-perftools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="wide-deep-large-ds-int8-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- python-pandas && \
- pip install pandas
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/model_containers/intel-tf-text-to-speech-wavenet-fp32-inference.Dockerfile b/dockerfiles/model_containers/intel-tf-text-to-speech-wavenet-fp32-inference.Dockerfile
deleted file mode 100644
index 4ef37bd43..000000000
--- a/dockerfiles/model_containers/intel-tf-text-to-speech-wavenet-fp32-inference.Dockerfile
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="intel/intel-optimized-tensorflow"
-
-ARG TENSORFLOW_TAG="1.15.2"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ENV DEBIAN_FRONTEND=noninteractive
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y \
- libsm6 \
- libxext6 \
- python-tk && \
- pip install requests
-
-ARG TF_WAVENET_BRANCH="cpu_optimized"
-
-ARG FETCH_PR="pull/352/head:cpu_optimized"
-
-ARG CODE_DIR=/tensorflow-wavenet
-
-ENV TF_WAVENET_DIR=${CODE_DIR}
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y git && \
- git clone https://github.com/ibab/tensorflow-wavenet.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "$FETCH_PR" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_WAVENET_BRANCH} )
-
-RUN pip install librosa==0.5
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="wavenet-fp32-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN apt-get install --no-install-recommends --fix-missing -y tar
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-RUN apt-get update && \
- apt-get install --no-install-recommends --fix-missing -y gosu
-
-RUN echo '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/sbin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/notebook_containers/performance.Dockerfile b/dockerfiles/notebook_containers/performance.Dockerfile
deleted file mode 100644
index 95d436159..000000000
--- a/dockerfiles/notebook_containers/performance.Dockerfile
+++ /dev/null
@@ -1,101 +0,0 @@
-# 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.
-# ============================================================================
-
-ARG UBUNTU_VERSION=20.04
-
-FROM ubuntu:${UBUNTU_VERSION}
-
-ARG TF_VERSION=2.6.0
-ARG MODEL_ZOO_VERSION=v2.4.0
-
-RUN apt-get -y update && \
- apt-get install -y \
- python3-dev \
- python3-pip \
- git \
- wget \
- unzip \
- numactl
-
-RUN pip3 -q install pip --upgrade && \
- pip3 install -U virtualenv && \
- pip3 install jupyter
-
-# Since the notebook does a git patch, we will need to set the user name and email.
-# This can be dummy since it is within the container
-RUN git config --global user.email "you@example.com" && \
- git config --global user.name "Your Name"
-
-RUN git clone --single-branch --branch=${MODEL_ZOO_VERSION} https://github.com/IntelAI/models.git
-
-WORKDIR models/docs/notebooks/perf_analysis
-
-# Create a virtual environment for stock TF
-RUN virtualenv -p python3 ./venv-stock-tf
-
-# Install all the necessary libraries for stock TF
-RUN . ./venv-stock-tf/bin/activate && \
- pip install \
- cxxfilt \
- gitpython \
- tensorflow==${TF_VERSION} \
- ipykernel \
- matplotlib \
- pandas \
- 'psutil>=5.6.7' \
- pycocotools && \
- deactivate
-
-# Create a Jupyter notebook kernel for stock TF with the name stock-tensorflow
-RUN venv-stock-tf/bin/python -m ipykernel install --user --name=stock-tensorflow
-
-# Create a virtual environment for Intel TF
-RUN virtualenv -p python3 ./venv-intel-tf
-
-# Install all the necessary libraries for Intel TF environment
-RUN . ./venv-intel-tf/bin/activate && \
- pip install \
- cxxfilt \
- gitpython \
- intel-tensorflow==${TF_VERSION} \
- ipykernel \
- matplotlib \
- pandas \
- 'psutil>=5.6.7' \
- pycocotools && \
- deactivate
-
-# Create a Jupyter notebook kernel for Intel TF with the name intel-tensorflow
-RUN venv-intel-tf/bin/python -m ipykernel install --user --name=intel-tensorflow
-
-# Download protoc for object detection
-ARG RFCN_COMMIT=6c21084503b27a9ab118e1db25f79957d5ef540b
-RUN git clone https://github.com/tensorflow/models.git tensorflow-models-rfcn && \
- cd tensorflow-models-rfcn && \
- git reset --hard ${RFCN_COMMIT} && \
- git apply /models/models/object_detection/tensorflow/rfcn/inference/tf-2.0.patch && \
- git clone https://github.com/cocodataset/cocoapi.git && \
- cd research && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=.
-
-EXPOSE 8888
-
-ENV LISTEN_IP=localhost
-
-# Run Jupyter notebook
-CMD jupyter notebook --port=8888 --no-browser --ip=${LISTEN_IP} --allow-root
diff --git a/dockerfiles/pytorch/pytorch-ipex-spr.Dockerfile b/dockerfiles/pytorch/pytorch-ipex-spr.Dockerfile
deleted file mode 100644
index 37f79697e..000000000
--- a/dockerfiles/pytorch/pytorch-ipex-spr.Dockerfile
+++ /dev/null
@@ -1,116 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG BASE_IMAGE=centos:8
-
-FROM ${BASE_IMAGE} AS centos-intel-base
-SHELL ["/bin/bash", "-c"]
-
-# Fixe for “Error: Failed to download metadata for repo 'appstream': Cannot prepare internal mirrorlist: No URLs in mirrorlist"
-RUN sed -i.bak '/^mirrorlist=/s/mirrorlist=/#mirrorlist=/g' /etc/yum.repos.d/CentOS-Linux-* && \
- sed -i.bak 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-Linux-* && \
- yum distro-sync -y && \
- yum --disablerepo '*' --enablerepo=extras swap centos-linux-repos centos-stream-repos -y && \
- yum distro-sync -y && \
- yum clean all
-
-RUN yum update -y && yum install -y unzip
-
-FROM centos-intel-base as ipex-dev-base
-WORKDIR /workspace/installs/
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- numactl \
- nc \
- tar \
- patch && \
- wget --quiet https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz && \
- tar -xzf protobuf-2.6.1.tar.gz && \
- cd protobuf-2.6.1 && \
- ./configure && \
- make && \
- make install
-
-# Prepare the Conda environment
-RUN wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh && \
- chmod +x miniconda.sh && \
- ./miniconda.sh -b -p ~/conda && \
- rm ./miniconda.sh && \
- ~/conda/bin/conda create -yn pytorch python=3.7 && \
- export PATH=~/conda/bin/:${PATH} && \
- source activate pytorch && \
- pip install pip==21.0.1 && \
- conda config --add channels intel && \
- conda install -y ninja pyyaml setuptools cmake cffi typing intel-openmp psutil && \
- conda install -y mkl mkl-include numpy -c intel --no-update-deps
-
-ENV PATH ~/conda/bin/:${PATH}
-ENV LD_LIBRARY_PATH /lib64/:/usr/lib64/:/usr/local/lib64:/root/conda/envs/pytorch/lib:${LD_LIBRARY_PATH}
-
-# Install PyTorch and IPEX wheels
-ARG PYTORCH_WHEEL="torch-1.12.0a0+gitd2ae05f-cp37-cp37m-linux_x86_64.whl"
-ARG IPEX_WHEEL="intel_extension_for_pytorch-1.12.0+cpu-cp37-cp37m-linux_x86_64.whl"
-
-COPY ./whls/* /tmp/pip3/
-RUN source activate pytorch && \
- pip install /tmp/pip3/${IPEX_WHEEL} && \
- pip install /tmp/pip3/${PYTORCH_WHEEL}
-
-
-# Build Jemalloc
-ARG JEMALLOC_SHA=c8209150f9d219a137412b06431c9d52839c7272
-
-RUN source activate pytorch && \
- git clone https://github.com/jemalloc/jemalloc.git && \
- cd jemalloc && \
- git checkout ${JEMALLOC_SHA} && \
- ./autogen.sh && \
- mkdir /workspace/lib/ && \
- ./configure --prefix=/workspace/lib/jemalloc/ && \
- make && \
- make install
-
-FROM centos-intel-base AS release
-COPY --from=ipex-dev-base /root/conda /root/conda
-COPY --from=ipex-dev-base /workspace/lib /workspace/lib
-
-ENV LD_LIBRARY_PATH /lib64/:/usr/lib64/:/usr/local/lib64:/root/conda/envs/pytorch/lib:${LD_LIBRARY_PATH}
-ENV PATH="~/conda/bin:${PATH}"
-ENV DNNL_MAX_CPU_ISA=AVX512_CORE_AMX
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "source activate pytorch" >> /root/.bash_profile
-
-# Please see: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-0778
-RUN yum erase openssl -y && \
- yum clean all
diff --git a/dockerfiles/pytorch/pytorch-spr-bert-large-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-bert-large-inference.Dockerfile
deleted file mode 100644
index 7abdbf43a..000000000
--- a/dockerfiles/pytorch/pytorch-spr-bert-large-inference.Dockerfile
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-RUN source activate pytorch && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- mkdir -p /workspace/lib/ && \
- ./configure --prefix=/workspace/lib/tcmalloc/ && \
- make && \
- make install
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-bert-large-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN source activate pytorch && \
- cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/quickstart && \
- git clone https://github.com/huggingface/transformers.git && \
- cd transformers && \
- git checkout v4.18.0 && \
- git apply ../enable_ipex_for_squad.diff && \
- pip install -e ./ && \
- pip install -r examples/pytorch/language-modeling/requirements.txt && \
- pip install tensorboard && \
- conda install intel-openmp && \
- mkdir -p /root/.local
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/tcmalloc/lib/libtcmalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-bert-large-training.Dockerfile b/dockerfiles/pytorch/pytorch-spr-bert-large-training.Dockerfile
deleted file mode 100644
index b73ff55d6..000000000
--- a/dockerfiles/pytorch/pytorch-spr-bert-large-training.Dockerfile
+++ /dev/null
@@ -1,98 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-RUN source activate pytorch && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- mkdir -p /workspace/lib/ && \
- ./configure --prefix=/workspace/lib/tcmalloc/ && \
- make && \
- make install
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-bert-large-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ARG TRANSFORMERS_COMMIT="v4.18.0"
-
-RUN source activate pytorch && \
- pip install datasets==1.11.0 accelerate tfrecord && \
- conda install openblas && \
- conda install faiss-cpu -c pytorch && \
- conda install intel-openmp && \
- cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/quickstart && \
- git clone https://github.com/huggingface/transformers.git && \
- cd transformers && \
- git checkout ${TRANSFORMERS_COMMIT} && \
- git apply ../enable_optmization.diff && \
- python -m pip install --upgrade pip && \
- pip uninstall transformers -y && \
- pip install -e . && \
- pip install h5py && \
- mkdir -p /root/.local
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/tcmalloc/lib/libtcmalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-dlrm-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-dlrm-inference.Dockerfile
deleted file mode 100644
index 8a6b4fc4e..000000000
--- a/dockerfiles/pytorch/pytorch-spr-dlrm-inference.Dockerfile
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-dlrm-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN source activate pytorch && \
- pip install -r ${MODEL_WORKSPACE}/${PACKAGE_NAME}/quickstart/requirements.txt
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV KMP_AFFINITY="granularity=fine,compact,1,0"
-ENV KMP_BLOCKTIME=1
-ENV DNNL_PRIMITIVE_CACHE_CAPACITY=1024
-ENV KMP_SETTINGS=1
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-dlrm-training.Dockerfile b/dockerfiles/pytorch/pytorch-spr-dlrm-training.Dockerfile
deleted file mode 100644
index 46a5150cb..000000000
--- a/dockerfiles/pytorch/pytorch-spr-dlrm-training.Dockerfile
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-dlrm-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN source activate pytorch && \
- pip install -r ${MODEL_WORKSPACE}/${PACKAGE_NAME}/quickstart/requirements.txt
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV KMP_AFFINITY="granularity=fine,compact,1,0"
-ENV KMP_BLOCKTIME=1
-ENV DNNL_PRIMITIVE_CACHE_CAPACITY=1024
-ENV KMP_SETTINGS=1
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-maskrcnn-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-maskrcnn-inference.Dockerfile
deleted file mode 100644
index 12b1f9dca..000000000
--- a/dockerfiles/pytorch/pytorch-spr-maskrcnn-inference.Dockerfile
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-maskrcnn-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN source activate pytorch && \
- cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/object_detection/pytorch/maskrcnn/maskrcnn-benchmark && \
- python setup.py install && \
- pip install onnx
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-maskrcnn-training.Dockerfile b/dockerfiles/pytorch/pytorch-spr-maskrcnn-training.Dockerfile
deleted file mode 100644
index 1736835e8..000000000
--- a/dockerfiles/pytorch/pytorch-spr-maskrcnn-training.Dockerfile
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-maskrcnn-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN source activate pytorch && \
- cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/object_detection/pytorch/maskrcnn/maskrcnn-benchmark && \
- python setup.py install && \
- pip install onnx
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-resnet50-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-resnet50-inference.Dockerfile
deleted file mode 100644
index 83e19e6d5..000000000
--- a/dockerfiles/pytorch/pytorch-spr-resnet50-inference.Dockerfile
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-resnet50-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-resnet50-training.Dockerfile b/dockerfiles/pytorch/pytorch-spr-resnet50-training.Dockerfile
deleted file mode 100644
index 2c30a85cc..000000000
--- a/dockerfiles/pytorch/pytorch-spr-resnet50-training.Dockerfile
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-resnet50-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-resnext-32x16d-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-resnext-32x16d-inference.Dockerfile
deleted file mode 100644
index c1cd2e3fa..000000000
--- a/dockerfiles/pytorch/pytorch-spr-resnext-32x16d-inference.Dockerfile
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-resnext-32x16d-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-rnnt-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-rnnt-inference.Dockerfile
deleted file mode 100644
index 178359ea1..000000000
--- a/dockerfiles/pytorch/pytorch-spr-rnnt-inference.Dockerfile
+++ /dev/null
@@ -1,96 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-rnnt-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-
-RUN source activate pytorch && \
- cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/language_modeling/pytorch/rnnt/inference/cpu && \
- pip install -r requirements.txt && \
- pip install unidecode inflect && \
- yum install -y libsndfile && \
- mkdir -p /root/.local && \
- git clone https://github.com/HawkAaron/warp-transducer && \
- cd warp-transducer && \
- mkdir build && \
- cd build && \
- cmake .. && \
- make && \
- cd ../pytorch_binding && \
- python setup.py install
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-rnnt-training.Dockerfile b/dockerfiles/pytorch/pytorch-spr-rnnt-training.Dockerfile
deleted file mode 100644
index ee66dafa8..000000000
--- a/dockerfiles/pytorch/pytorch-spr-rnnt-training.Dockerfile
+++ /dev/null
@@ -1,97 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-rnnt-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN source activate pytorch && \
- cd ${MODEL_WORKSPACE}/${PACKAGE_NAME}/models/language_modeling/pytorch/rnnt/training/cpu && \
- pip install -r requirements.txt && \
- pip install unidecode inflect && \
- pip install --upgrade pip && \
- pip install librosa sox && \
- yum install -y libsndfile && \
- mkdir -p /root/.local && \
- git clone https://github.com/HawkAaron/warp-transducer && \
- cd warp-transducer && \
- mkdir build && \
- cd build && \
- cmake .. && \
- make && \
- cd ../pytorch_binding && \
- python setup.py install
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-ssd-resnet34-inference.Dockerfile b/dockerfiles/pytorch/pytorch-spr-ssd-resnet34-inference.Dockerfile
deleted file mode 100644
index dae3157f9..000000000
--- a/dockerfiles/pytorch/pytorch-spr-ssd-resnet34-inference.Dockerfile
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-# Build Torch Vision
-ARG TORCHVISION_VERSION="81fe60cc258f49ccfb0f9f32d78b4825754cff7b"
-
-RUN source activate pytorch && \
- git clone https://github.com/pytorch/vision && \
- cd vision && \
- git checkout ${TORCHVISION_VERSION} && \
- python setup.py install
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-ssd-resnet34-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/pytorch/pytorch-spr-ssd-resnet34-training.Dockerfile b/dockerfiles/pytorch/pytorch-spr-ssd-resnet34-training.Dockerfile
deleted file mode 100644
index e32f3c593..000000000
--- a/dockerfiles/pytorch/pytorch-spr-ssd-resnet34-training.Dockerfile
+++ /dev/null
@@ -1,105 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG PYTORCH_IMAGE="model-zoo"
-ARG PYTORCH_TAG="pytorch-ipex-spr"
-
-FROM ${PYTORCH_IMAGE}:${PYTORCH_TAG} AS intel-optimized-pytorch
-
-RUN yum --enablerepo=extras install -y epel-release && \
- yum install -y \
- ca-certificates \
- git \
- wget \
- make \
- cmake \
- gcc-c++ \
- gcc \
- autoconf \
- bzip2 \
- tar
-
-RUN source activate pytorch && \
- pip install matplotlib Pillow pycocotools && \
- pip install yacs opencv-python cityscapesscripts transformers && \
- conda install -y libopenblas && \
- mkdir -p /workspace/installs && \
- cd /workspace/installs && \
- wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7.90/gperftools-2.7.90.tar.gz && \
- tar -xzf gperftools-2.7.90.tar.gz && \
- cd gperftools-2.7.90 && \
- ./configure --prefix=$HOME/.local && \
- make && \
- make install && \
- rm -rf /workspace/installs/
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="pytorch-spr-ssd-resnet34-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum install -y libpng-devel \
- freetype-devel && \
- source activate pytorch && \
- pip install --upgrade pip && \
- pip install --no-cache-dir https://github.com/mlperf/logging/archive/9ea0afa.zip && \
- pip install --no-cache-dir \
- Cython==0.28.4 \
- git+http://github.com/NVIDIA/apex.git@9041a868a1a253172d94b113a963375b9badd030#egg=apex \
- mlperf-compliance==0.0.10 \
- cycler==0.10.0 \
- kiwisolver==1.0.1 \
- matplotlib==2.2.2 \
- Pillow>=9.3.0 \
- pyparsing==2.2.0 \
- python-dateutil==2.7.3 \
- pytz==2018.5 \
- six==1.11.0 \
- torchvision==0.2.1 \
- pycocotools==2.0.2
-
-FROM intel-optimized-pytorch AS release
-COPY --from=intel-optimized-pytorch /root/conda /root/conda
-COPY --from=intel-optimized-pytorch /workspace/lib/ /workspace/lib/
-COPY --from=intel-optimized-pytorch /root/.local/ /root/.local/
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-ENV PATH="~/conda/bin:${PATH}"
-ENV LD_PRELOAD="/workspace/lib/jemalloc/lib/libjemalloc.so:/root/conda/envs/pytorch/lib/libiomp5.so:$LD_PRELOAD"
-ENV MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:9000000000,muzzy_decay_ms:9000000000"
-ENV BASH_ENV=/root/.bash_profile
-WORKDIR /workspace/
-RUN yum install -y numactl mesa-libGL && \
- yum clean all && \
- echo "export LD_PRELOAD=${LD_PRELOAD%%:}" >> /root/.bash_profile && \
- echo "source activate pytorch" >> /root/.bash_profile
diff --git a/dockerfiles/tensorflow-spr/tensorflow-spr-3dunet.Dockerfile b/dockerfiles/tensorflow-spr/tensorflow-spr-3dunet.Dockerfile
deleted file mode 100644
index c8e068204..000000000
--- a/dockerfiles/tensorflow-spr/tensorflow-spr-3dunet.Dockerfile
+++ /dev/null
@@ -1,62 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG BASE_IMAGE=quay.io/centos/centos:stream8
-
-FROM ${BASE_IMAGE} AS centos-intel-base
-SHELL ["/bin/bash", "-c"]
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-# set env var as we moved from block format to native format
-ENV TF_ENABLE_MKL_NATIVE_FORMAT=1
-
-# See http://bugs.python.org/issue19846
-ENV LANG C.UTF-8
-ARG PYTHON=python3
-
-RUN yum update -y && yum install -y \
- ${PYTHON} \
- ${PYTHON}-pip \
- which && \
- yum clean all
-
-
-RUN ${PYTHON} -m pip --no-cache-dir install --upgrade \
- pip \
- setuptools
-
-# Some TF tools expect a "python" binary
-RUN ln -sf $(which ${PYTHON}) /usr/local/bin/python && \
- ln -sf $(which ${PYTHON}) /usr/local/bin/python3 && \
- ln -sf $(which ${PYTHON}) /usr/bin/python
-
-# Installs the latest version by default.
-ARG TF_WHEEL=tf_nightly-2.9.0.202212-cp38-cp38-linux_x86_64.whl
-
-COPY ./whls/${TF_WHEEL} /tmp/pip3/
-
-RUN python3 -m pip install --no-cache-dir /tmp/pip3/${TF_WHEEL}
-
-# fix keras-nightly and tf-estimator-nightly versions
-RUN pip uninstall -y keras-nightly tf-estimator-nightly
-RUN pip install tf-estimator-nightly==2.7.0.dev2021092408 \
- keras-nightly==2.7.0.dev2021100607
diff --git a/dockerfiles/tensorflow-spr/tensorflow-spr.Dockerfile b/dockerfiles/tensorflow-spr/tensorflow-spr.Dockerfile
deleted file mode 100644
index 4de924cdc..000000000
--- a/dockerfiles/tensorflow-spr/tensorflow-spr.Dockerfile
+++ /dev/null
@@ -1,81 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG BASE_IMAGE=centos:8
-
-FROM ${BASE_IMAGE} AS centos-intel-base
-SHELL ["/bin/bash", "-c"]
-
-# Fixe for “Error: Failed to download metadata for repo 'appstream': Cannot prepare internal mirrorlist: No URLs in mirrorlist"
-RUN sed -i.bak '/^mirrorlist=/s/mirrorlist=/#mirrorlist=/g' /etc/yum.repos.d/CentOS-Linux-* && \
- sed -i.bak 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-Linux-* && \
- yum distro-sync -y && \
- yum --disablerepo '*' --enablerepo=extras swap centos-linux-repos centos-stream-repos -y && \
- yum distro-sync -y && \
- yum clean all
-
-ENV DNNL_MAX_CPU_ISA="AVX512_CORE_AMX"
-
-# set env var as we moved from block format to native format
-ENV TF_ENABLE_MKL_NATIVE_FORMAT=1
-
-# See http://bugs.python.org/issue19846
-ENV LANG C.UTF-8
-ARG PY_VER="38"
-ARG PYTHON=python3
-
-RUN yum update -y && yum install -y \
- python${PY_VER} \
- python${PY_VER}-pip \
- which && \
- yum clean all
-
-RUN ${PYTHON} -m pip --no-cache-dir install --upgrade \
- pip \
- setuptools
-
-# Some TF tools expect a "python" binary
-RUN ln -sf $(which ${PYTHON}) /usr/local/bin/python && \
- ln -sf $(which ${PYTHON}) /usr/local/bin/python3 && \
- ln -sf $(which ${PYTHON}) /usr/bin/python
-
-# Installs the latest version by default.
-ARG TF_WHEEL="tf_nightly-2.10.0.202218-cp38-cp38-linux_x86_64.whl"
-ARG TF_ESTIMATOR_VER="2.10.0.dev2022042008"
-ARG KERAS_NIGHTLY_VER="2.10.0.dev2022042007"
-
-COPY ./whls/${TF_WHEEL} /tmp/pip3/
-
-RUN python -m pip install --no-cache-dir \
- "tf-estimator-nightly==${TF_ESTIMATOR_VER}" \
- "keras-nightly==${KERAS_NIGHTLY_VER}" \
- /tmp/pip3/${TF_WHEEL}
-
-RUN yum install -y https://extras.getpagespeed.com/release-el8-latest.rpm && \
- yum install -y gperftools && \
- yum erase -y getpagespeed-extras-release && \
- yum clean all
-
-ENV LD_PRELOAD="/usr/lib64/libtcmalloc.so":${LD_PRELOAD}
-
-# Please see: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-0778
-RUN yum erase openssl -y && \
- yum clean all
diff --git a/dockerfiles/tensorflow-spr/tf-spr-3d-unet-mlperf-inference.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-3d-unet-mlperf-inference.Dockerfile
deleted file mode 100644
index 01fd11ae3..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-3d-unet-mlperf-inference.Dockerfile
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-3d-unet-mlperf-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum update -y && yum install -y numactl
-
-RUN pip install \
- 'numpy>=1.19.5' \
- 'nilearn>=0.7.1' \
- 'tables>=3.6.1' \
- 'nibabel>=3.2.1' \
- 'SimpleITK>=2.0.2' \
- nnunet \
- torch \
- tqdm \
- dicom2nifti \
- scikit-image \
- medpy \
- scipy \
- batchgenerators \
- sklearn \
- pandas \
- matplotlib
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-bert-large-pretraining.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-bert-large-pretraining.Dockerfile
deleted file mode 100644
index e69611927..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-bert-large-pretraining.Dockerfile
+++ /dev/null
@@ -1,135 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PY_VER=38
-RUN yum install -y gcc gcc-c++ && \
- yum install -y python${PY_VER}-devel && \
- yum clean all
-
-RUN yum update -y && \
- yum install -y gcc gcc-c++ cmake python3-tkinter libXext libSM && \
- yum clean all
-
-# Install OpenMPI
-ARG OPENMPI_VERSION="openmpi-4.1.0"
-ARG OPENMPI_DOWNLOAD_URL="https://www.open-mpi.org/software/ompi/v4.1/downloads/openmpi-4.1.0.tar.gz"
-
-RUN mkdir /tmp/openmpi && \
- cd /tmp/openmpi && \
- curl -fSsL -O ${OPENMPI_DOWNLOAD_URL} && \
- tar zxf ${OPENMPI_VERSION}.tar.gz && \
- cd ${OPENMPI_VERSION} && \
- ./configure --enable-mpirun-prefix-by-default && \
- make -j $(nproc) all && \
- make install && \
- ldconfig && \
- cd / && \
- rm -rf /tmp/openmpi
-
-# Create a wrapper for OpenMPI to allow running as root by default
-RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
- echo '#!/bin/bash' > /usr/local/bin/mpirun && \
- echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
- chmod a+x /usr/local/bin/mpirun
-
-# Configure OpenMPI to run good defaults:
-RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
-
-# Install OpenSSH for MPI to communicate between containers
-RUN yum update -y && yum install -y \
- openssh-server \
- openssh-clients && \
- yum clean all
-
-ARG HOROVOD_VERSION=35b27e9
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1 \
- HOROVOD_CPU_OPERATIONS=MPI \
- HOROVOD_WITH_MPI=1 \
- HOROVOD_WITHOUT_GLOO=1
-
-# Install Horovod
-RUN yum update -y && yum install -y git cmake gcc-c++ && \
- yum clean all
-
-RUN python3 -m pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-bert-large-pretraining"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum update -y && yum install -y numactl
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-dien-training.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-dien-training.Dockerfile
deleted file mode 100644
index 7d51c0056..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-dien-training.Dockerfile
+++ /dev/null
@@ -1,116 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-dien-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum update -y && yum install -y numactl
-
-RUN yum update -y && \
- yum install -y gcc gcc-c++ cmake python3-tkinter libXext libSM && \
- yum clean all
-
-# Install OpenMPI
-ARG OPENMPI_VERSION="openmpi-4.1.0"
-ARG OPENMPI_DOWNLOAD_URL="https://www.open-mpi.org/software/ompi/v4.1/downloads/openmpi-4.1.0.tar.gz"
-
-RUN mkdir /tmp/openmpi && \
- cd /tmp/openmpi && \
- curl -fSsL -O ${OPENMPI_DOWNLOAD_URL} && \
- tar zxf ${OPENMPI_VERSION}.tar.gz && \
- cd ${OPENMPI_VERSION} && \
- ./configure --enable-mpirun-prefix-by-default && \
- make -j $(nproc) all && \
- make install && \
- ldconfig && \
- cd / && \
- rm -rf /tmp/openmpi
-
-# Create a wrapper for OpenMPI to allow running as root by default
-RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
- echo '#!/bin/bash' > /usr/local/bin/mpirun && \
- echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
- chmod a+x /usr/local/bin/mpirun
-
-# Configure OpenMPI to run good defaults:
-RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
-
-# Install OpenSSH for MPI to communicate between containers
-RUN yum update -y && yum install -y \
- openssh-server \
- openssh-clients && \
- yum clean all
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-resnet50v1-5-training.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-resnet50v1-5-training.Dockerfile
deleted file mode 100644
index 52aeb8219..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-resnet50v1-5-training.Dockerfile
+++ /dev/null
@@ -1,135 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PY_VER=38
-RUN yum install -y gcc gcc-c++ && \
- yum install -y python${PY_VER}-devel && \
- yum clean all
-
-RUN yum update -y && \
- yum install -y gcc gcc-c++ cmake python3-tkinter libXext libSM && \
- yum clean all
-
-# Install OpenMPI
-ARG OPENMPI_VERSION="openmpi-4.1.0"
-ARG OPENMPI_DOWNLOAD_URL="https://www.open-mpi.org/software/ompi/v4.1/downloads/openmpi-4.1.0.tar.gz"
-
-RUN mkdir /tmp/openmpi && \
- cd /tmp/openmpi && \
- curl -fSsL -O ${OPENMPI_DOWNLOAD_URL} && \
- tar zxf ${OPENMPI_VERSION}.tar.gz && \
- cd ${OPENMPI_VERSION} && \
- ./configure --enable-mpirun-prefix-by-default && \
- make -j $(nproc) all && \
- make install && \
- ldconfig && \
- cd / && \
- rm -rf /tmp/openmpi
-
-# Create a wrapper for OpenMPI to allow running as root by default
-RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
- echo '#!/bin/bash' > /usr/local/bin/mpirun && \
- echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
- chmod a+x /usr/local/bin/mpirun
-
-# Configure OpenMPI to run good defaults:
-RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
-
-# Install OpenSSH for MPI to communicate between containers
-RUN yum update -y && yum install -y \
- openssh-server \
- openssh-clients && \
- yum clean all
-
-ARG HOROVOD_VERSION=35b27e9
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1 \
- HOROVOD_CPU_OPERATIONS=MPI \
- HOROVOD_WITH_MPI=1 \
- HOROVOD_WITHOUT_GLOO=1
-
-# Install Horovod
-RUN yum update -y && yum install -y git cmake gcc-c++ && \
- yum clean all
-
-RUN python3 -m pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-resnet50v1-5-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum update -y && yum install -y numactl
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-ssd-mobilenet-inference.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-ssd-mobilenet-inference.Dockerfile
deleted file mode 100644
index f826c6d92..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-ssd-mobilenet-inference.Dockerfile
+++ /dev/null
@@ -1,129 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-ssd-mobilenet-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum update -y && \
- yum install -y \
- numactl \
- libXext \
- libSM \
- python3-tkinter && \
- pip install requests
-
-ARG PY_VER=38
-RUN yum install -y gcc gcc-c++ && \
- yum install -y python${PY_VER}-devel && \
- yum clean all
-
-ARG TF_MODELS_BRANCH
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN yum update -y && yum install -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- yum update -y && yum install -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=.
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-ssd-resnet34-inference.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-ssd-resnet34-inference.Dockerfile
deleted file mode 100644
index 2040c01e3..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-ssd-resnet34-inference.Dockerfile
+++ /dev/null
@@ -1,148 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-RUN yum update -y && \
- yum install -y \
- numactl \
- libXext \
- libSM \
- python3-tkinter && \
- pip install requests
-
-ARG PY_VER=38
-RUN yum install -y gcc gcc-c++ && \
- yum install -y python${PY_VER}-devel && \
- yum clean all
-
-ARG TF_MODELS_BRANCH="f505cecde2d8ebf6fe15f40fb8bc350b2b1ed5dc"
-
-ARG FETCH_PR
-
-ARG CODE_DIR="/workspace/tf_models"
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN yum update -y && yum install -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- yum update -y && yum install -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=.
-
-RUN yum update -y && yum install -y \
- mesa-libGL \
- glib2-devel
-
-RUN pip install opencv-python
-
-RUN pip install tensorflow-addons==0.18.0
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-ssd-resnet34-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
-
-ARG TF_BENCHMARKS_BRANCH="509b9d288937216ca7069f31cfb22aaa7db6a4a7"
-
-ARG TF_BENCHMARKS_DIR="/workspace/ssd-resnet-benchmarks"
-
-ENV TF_BENCHMARKS_DIR=${TF_BENCHMARKS_DIR}
-
-RUN yum update -y && yum install -y git && \
- git clone --single-branch https://github.com/tensorflow/benchmarks.git ${TF_BENCHMARKS_DIR} && \
- ( cd ${TF_BENCHMARKS_DIR} && \
- git checkout ${TF_BENCHMARKS_BRANCH} )
diff --git a/dockerfiles/tensorflow-spr/tf-spr-ssd-resnet34-training.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-ssd-resnet34-training.Dockerfile
deleted file mode 100644
index 5445459c7..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-ssd-resnet34-training.Dockerfile
+++ /dev/null
@@ -1,184 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-RUN yum update -y && \
- yum install -y \
- numactl \
- libXext \
- libSM \
- python3-tkinter && \
- pip install requests
-
-ARG PY_VER=38
-RUN yum install -y gcc gcc-c++ && \
- yum install -y python${PY_VER}-devel && \
- yum clean all
-
-RUN yum update -y && \
- yum install -y gcc gcc-c++ cmake python3-tkinter libXext libSM && \
- yum clean all
-
-# Install OpenMPI
-ARG OPENMPI_VERSION="openmpi-4.1.0"
-ARG OPENMPI_DOWNLOAD_URL="https://www.open-mpi.org/software/ompi/v4.1/downloads/openmpi-4.1.0.tar.gz"
-
-RUN mkdir /tmp/openmpi && \
- cd /tmp/openmpi && \
- curl -fSsL -O ${OPENMPI_DOWNLOAD_URL} && \
- tar zxf ${OPENMPI_VERSION}.tar.gz && \
- cd ${OPENMPI_VERSION} && \
- ./configure --enable-mpirun-prefix-by-default && \
- make -j $(nproc) all && \
- make install && \
- ldconfig && \
- cd / && \
- rm -rf /tmp/openmpi
-
-# Create a wrapper for OpenMPI to allow running as root by default
-RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
- echo '#!/bin/bash' > /usr/local/bin/mpirun && \
- echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
- chmod a+x /usr/local/bin/mpirun
-
-# Configure OpenMPI to run good defaults:
-RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
-
-# Install OpenSSH for MPI to communicate between containers
-RUN yum update -y && yum install -y \
- openssh-server \
- openssh-clients && \
- yum clean all
-
-ARG HOROVOD_VERSION=35b27e9
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1 \
- HOROVOD_CPU_OPERATIONS=MPI \
- HOROVOD_WITH_MPI=1 \
- HOROVOD_WITHOUT_GLOO=1
-
-# Install Horovod
-RUN yum update -y && yum install -y git cmake gcc-c++ && \
- yum clean all
-
-RUN python3 -m pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-RUN pip install opencv-python
-
-RUN yum update -y && yum install -y numactl
-
-RUN pip install tensorflow-addons==0.18.0
-
-ARG TF_MODELS_BRANCH="8110bb64ca63c48d0caee9d565e5b4274db2220a"
-
-ARG FETCH_PR
-
-ARG CODE_DIR=/tensorflow/models
-
-ENV TF_MODELS_DIR=${CODE_DIR}
-
-RUN yum update -y && yum install -y git && \
- git clone https://github.com/tensorflow/models.git ${CODE_DIR} && \
- ( cd ${CODE_DIR} && \
- if [ ! -z "${FETCH_PR}" ]; then git fetch origin ${FETCH_PR}; fi && \
- git checkout ${TF_MODELS_BRANCH} )
-
-ARG TF_MODELS_DIR=/tensorflow/models
-
-# Downloads protoc and runs it for object detection
-RUN cd ${TF_MODELS_DIR}/research && \
- yum update -y && yum install -y \
- unzip \
- wget && \
- wget --quiet -O protobuf.zip https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip && \
- unzip -o protobuf.zip && \
- rm protobuf.zip && \
- ./bin/protoc object_detection/protos/*.proto --python_out=.
-
-# Note pycocotools has to be install after the other requirements
-RUN pip install \
- Cython \
- contextlib2 \
- jupyter \
- lxml \
- matplotlib \
- numpy>=1.17.4 \
- 'pillow>=9.3.0' && \
- pip install pycocotools
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-ssd-resnet34-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-transformer-mlperf-inference.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-transformer-mlperf-inference.Dockerfile
deleted file mode 100644
index 9f70ccb0d..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-transformer-mlperf-inference.Dockerfile
+++ /dev/null
@@ -1,87 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-RUN yum update -y && \
- yum install -y \
- numactl \
- libXext \
- libSM \
- python3-tkinter && \
- pip install requests
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-transformer-mlperf-inference"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/dockerfiles/tensorflow-spr/tf-spr-transformer-mlperf-training.Dockerfile b/dockerfiles/tensorflow-spr/tf-spr-transformer-mlperf-training.Dockerfile
deleted file mode 100644
index bf9026f68..000000000
--- a/dockerfiles/tensorflow-spr/tf-spr-transformer-mlperf-training.Dockerfile
+++ /dev/null
@@ -1,135 +0,0 @@
-# Copyright (c) 2020-2021 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 IS A GENERATED DOCKERFILE.
-#
-# This file was assembled from multiple pieces, whose use is documented
-# throughout. Please refer to the TensorFlow dockerfiles documentation
-# for more information.
-
-ARG TENSORFLOW_IMAGE="model-zoo"
-
-ARG TENSORFLOW_TAG="tensorflow-spr"
-
-FROM ${TENSORFLOW_IMAGE}:${TENSORFLOW_TAG}
-
-ARG PY_VER=38
-RUN yum install -y gcc gcc-c++ && \
- yum install -y python${PY_VER}-devel && \
- yum clean all
-
-RUN yum update -y && \
- yum install -y gcc gcc-c++ cmake python3-tkinter libXext libSM && \
- yum clean all
-
-# Install OpenMPI
-ARG OPENMPI_VERSION="openmpi-4.1.0"
-ARG OPENMPI_DOWNLOAD_URL="https://www.open-mpi.org/software/ompi/v4.1/downloads/openmpi-4.1.0.tar.gz"
-
-RUN mkdir /tmp/openmpi && \
- cd /tmp/openmpi && \
- curl -fSsL -O ${OPENMPI_DOWNLOAD_URL} && \
- tar zxf ${OPENMPI_VERSION}.tar.gz && \
- cd ${OPENMPI_VERSION} && \
- ./configure --enable-mpirun-prefix-by-default && \
- make -j $(nproc) all && \
- make install && \
- ldconfig && \
- cd / && \
- rm -rf /tmp/openmpi
-
-# Create a wrapper for OpenMPI to allow running as root by default
-RUN mv /usr/local/bin/mpirun /usr/local/bin/mpirun.real && \
- echo '#!/bin/bash' > /usr/local/bin/mpirun && \
- echo 'mpirun.real --allow-run-as-root "$@"' >> /usr/local/bin/mpirun && \
- chmod a+x /usr/local/bin/mpirun
-
-# Configure OpenMPI to run good defaults:
-RUN echo "btl_tcp_if_exclude = lo,docker0" >> /usr/local/etc/openmpi-mca-params.conf
-
-# Install OpenSSH for MPI to communicate between containers
-RUN yum update -y && yum install -y \
- openssh-server \
- openssh-clients && \
- yum clean all
-
-ARG HOROVOD_VERSION=35b27e9
-ENV HOROVOD_WITHOUT_MXNET=1 \
- HOROVOD_WITHOUT_PYTORCH=1 \
- HOROVOD_WITH_TENSORFLOW=1 \
- HOROVOD_CPU_OPERATIONS=MPI \
- HOROVOD_WITH_MPI=1 \
- HOROVOD_WITHOUT_GLOO=1
-
-# Install Horovod
-RUN yum update -y && yum install -y git cmake gcc-c++ && \
- yum clean all
-
-RUN python3 -m pip install git+https://github.com/horovod/horovod.git@${HOROVOD_VERSION}
-
-ARG PACKAGE_DIR=model_packages
-
-ARG PACKAGE_NAME="tf-spr-transformer-mlperf-training"
-
-ARG MODEL_WORKSPACE
-
-# ${MODEL_WORKSPACE} and below needs to be owned by root:root rather than the current UID:GID
-# this allows the default user (root) to work in k8s single-node, multi-node
-RUN umask 002 && mkdir -p ${MODEL_WORKSPACE} && chgrp root ${MODEL_WORKSPACE} && chmod g+s+w,o+s+r ${MODEL_WORKSPACE}
-
-ADD --chown=0:0 ${PACKAGE_DIR}/${PACKAGE_NAME}.tar.gz ${MODEL_WORKSPACE}
-
-RUN chown -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chgrp -R root ${MODEL_WORKSPACE}/${PACKAGE_NAME} && chmod -R g+s+w ${MODEL_WORKSPACE}/${PACKAGE_NAME} && find ${MODEL_WORKSPACE}/${PACKAGE_NAME} -type d | xargs chmod o+r+x
-
-WORKDIR ${MODEL_WORKSPACE}/${PACKAGE_NAME}
-
-RUN yum update -y && yum install -y numactl
-
-ENV USER_ID=0
-
-ENV USER_NAME=root
-
-ENV GROUP_ID=0
-
-ENV GROUP_NAME=root
-
-ENV GOSU_VERSION=1.11
-RUN curl -o /tmp/gosu.key -SL "https://keys.openpgp.org/vks/v1/by-fingerprint/B42F6819007F00F88E364FD4036A9C25BF357DD4" \
- && gpg --import /tmp/gosu.key \
- && curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64" \
- && curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64.asc" \
- && gpg --verify /usr/local/bin/gosu.asc \
- && rm /usr/local/bin/gosu.asc \
- && rm -r /root/.gnupg/ \
- && rm /tmp/gosu.key \
- && chmod +x /usr/local/bin/gosu
-
-RUN echo -e '#!/bin/bash\n\
-USER_ID=$USER_ID\n\
-USER_NAME=$USER_NAME\n\
-GROUP_ID=$GROUP_ID\n\
-GROUP_NAME=$GROUP_NAME\n\
-if [[ $GROUP_NAME != root ]]; then\n\
- groupadd -r -g $GROUP_ID $GROUP_NAME\n\
-fi\n\
-if [[ $USER_NAME != root ]]; then\n\
- useradd --no-log-init -r -u $USER_ID -g $GROUP_NAME -s /bin/bash -M $USER_NAME\n\
-fi\n\
-exec /usr/local/bin/gosu $USER_NAME:$GROUP_NAME "$@"\n '\
->> /tmp/entrypoint.sh
-
-RUN chmod u+x,g+x /tmp/entrypoint.sh
-
-ENTRYPOINT ["/tmp/entrypoint.sh"]
diff --git a/docs/README.md b/docs/README.md
index bd59354e6..0d975d4dd 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,7 +4,7 @@
* Intel® Optimization for TensorFlow\*:
* [TensorFlow and the Model Zoo in the Intel® oneAPI AI Analytics Toolkit](/docs/general/tensorflow/AIKit.md)
- * [Installation Guide](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide)
+ * [Installation Guide](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html)
* [General Best Practices](/docs/general/tensorflow/GeneralBestPractices.md)
* Intel® Optimization for Tensorflow Serving\*:
* [Installation Guide](/docs/general/tensorflow_serving/InstallationGuide.md)
diff --git a/docs/container_portal/README.md b/docs/container_portal/README.md
index b93f9e65a..94e423749 100644
--- a/docs/container_portal/README.md
+++ b/docs/container_portal/README.md
@@ -1,4 +1,4 @@
# Container Documentation
-This directory contains documentation for the [Intel® oneContainer Portal](https://software.intel.com/containers).
+This directory contains documentation for the [Intel® oneContainer Portal](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html).
If you are adding a new container README, make a copy of the [Template.md](Template.md) and fill out all the required data and metadata.
\ No newline at end of file
diff --git a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow.md b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow.md
index 7c9c06fde..9d605c185 100644
--- a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow.md
+++ b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow.md
@@ -25,7 +25,7 @@ Includes the Python3 interpreter and the following wheel(s) and librarie(s) are
- [Github repo](https://github.com/Intel-tensorflow/tensorflow/tree/master)
- [README URL](https://github.com/Intel-tensorflow/tensorflow/blob/master/README.md)
- [Release Notes URL](https://github.com/Intel-tensorflow/tensorflow/releases)
-- [Get Started URL](https://software.intel.com/content/www/us/en/develop/articles/intel-optimization-for-tensorflow-installation-guide.html)
+- [Get Started URL](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html)
## License Agreement
diff --git a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_jupyter.md b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_jupyter.md
index b5edee7e4..408b42a8a 100644
--- a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_jupyter.md
+++ b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_jupyter.md
@@ -27,7 +27,7 @@ Includes the Python3 interpreter and the following wheel(s) and librarie(s) are
- [Github repo](https://github.com/Intel-tensorflow/tensorflow/tree/master)
- [README URL](https://github.com/Intel-tensorflow/tensorflow/blob/master/README.md)
- [Release Notes URL](https://github.com/Intel-tensorflow/tensorflow/releases)
-- [Get Started URL](https://software.intel.com/content/www/us/en/develop/articles/intel-optimization-for-tensorflow-installation-guide.html)
+- [Get Started URL](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html)
## License Agreement
diff --git a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod.md b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod.md
index 908710d5d..1cc85c38d 100644
--- a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod.md
+++ b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod.md
@@ -27,7 +27,7 @@ Includes the Python3 interpreter and the following wheel(s) and librarie(s) are
- [Github repo](https://github.com/Intel-tensorflow/tensorflow/tree/master)
- [README URL](https://github.com/Intel-tensorflow/tensorflow/blob/master/README.md)
- [Release Notes URL](https://github.com/Intel-tensorflow/tensorflow/releases)
-- [Get Started URL](https://software.intel.com/content/www/us/en/develop/articles/intel-optimization-for-tensorflow-installation-guide.html)
+- [Get Started URL](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html)
## License Agreement
diff --git a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod_jupyter.md b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod_jupyter.md
index f511147bc..582d1bcb4 100644
--- a/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod_jupyter.md
+++ b/docs/container_portal/dl/tensorflow/ubuntu/tensorflow_mpi_horovod_jupyter.md
@@ -29,7 +29,7 @@ Includes the Python3 interpreter and the following wheel(s) and librarie(s) are
- [Github repo](https://github.com/Intel-tensorflow/tensorflow/tree/master)
- [README URL](https://github.com/Intel-tensorflow/tensorflow/blob/master/README.md)
- [Release Notes URL](https://github.com/Intel-tensorflow/tensorflow/releases)
-- [Get Started URL](https://software.intel.com/content/www/us/en/develop/articles/intel-optimization-for-tensorflow-installation-guide.html)
+- [Get Started URL](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html)
## License Agreement
diff --git a/docs/container_portal/ml/python/intelpython3_core.md b/docs/container_portal/ml/python/intelpython3_core.md
index 913852afd..003ed2212 100644
--- a/docs/container_portal/ml/python/intelpython3_core.md
+++ b/docs/container_portal/ml/python/intelpython3_core.md
@@ -28,8 +28,8 @@ Includes the Python3 interpreter, Conda, and the following core packages:
- [DockerHub URL](https://hub.docker.com/r/intelpython/intelpython3_core)
- [Github repo](https://www.github.com/IntelPython/container-images)
- [README URL](https://github.com/IntelPython/container-images/blob/master/configs/intelpython3_core/README.md)
-- [Release Notes URL](https://software.intel.com/content/www/us/en/develop/articles/intel-distribution-for-python-release-notes.html)
-- [Get Started URL](https://software.intel.com/content/www/us/en/develop/tools/distribution-for-python/get-started.html)
+- [Release Notes URL](https://www.intel.com/content/www/us/en/developer/articles/release-notes/distribution-for-python-release-notes.html)
+- [Get Started URL](https://www.intel.com/content/www/us/en/developer/tools/oneapi/distribution-for-python.html#gs.34b15b)
## License Agreement
diff --git a/docs/container_portal/ml/python/intelpython3_full.md b/docs/container_portal/ml/python/intelpython3_full.md
index 10d22da17..9bb1b6a42 100644
--- a/docs/container_portal/ml/python/intelpython3_full.md
+++ b/docs/container_portal/ml/python/intelpython3_full.md
@@ -28,8 +28,8 @@ Includes the Python3 interpreter, Conda, the packages from Intel Python3 Core, a
- [DockerHub URL](https://hub.docker.com/r/intelpython/intelpython3_full)
- [Github repo](https://www.github.com/IntelPython/container-images)
- [README URL](https://github.com/IntelPython/container-images/blob/master/configs/intelpython3_full/README.md)
-- [Release Notes URL](https://software.intel.com/content/www/us/en/develop/articles/intel-distribution-for-python-release-notes.html)
-- [Get Started URL](https://software.intel.com/content/www/us/en/develop/tools/distribution-for-python/get-started.html)
+- [Release Notes URL](https://www.intel.com/content/www/us/en/developer/articles/release-notes/distribution-for-python-release-notes.html)
+- [Get Started URL](https://www.intel.com/content/www/us/en/developer/tools/oneapi/distribution-for-python.html#gs.34b237)
## License Agreement
diff --git a/docs/general/FLEX_DEVCATALOG.md b/docs/general/FLEX_DEVCATALOG.md
index d08f2da8e..3f805d148 100644
--- a/docs/general/FLEX_DEVCATALOG.md
+++ b/docs/general/FLEX_DEVCATALOG.md
@@ -6,8 +6,8 @@ This document provides links to step-by-step instructions on how to leverage Mod
| AI Framework | Extension | Documentation |
| -----------------------------| ------------- | ----------------- |
-| PyTorch | Intel® Extension for PyTorch* | [Intel® Extension for PyTorch Container](https://github.com/IntelAI/models/blob/master/quickstart/ipex-tool-container/gpu/devcatalog.md) |
-| TensorFlow | Intel® Extension for TensorFlow* | [Intel® Extension for TensorFlow Container](https://github.com/IntelAI/models/blob/master/quickstart/tf-tool-container/gpu/devcatalog.md)|
+| PyTorch | Intel® Extension for PyTorch* | [Intel® Extension for PyTorch Container](https://github.com/intel/intel-extension-for-pytorch/blob/v2.0.110%2Bxpu/docker/README.md) |
+| TensorFlow | Intel® Extension for TensorFlow* | [Intel® Extension for TensorFlow Container](https://github.com/intel/intel-extension-for-tensorflow/blob/v2.13.0.0/docker/README.md)|
## Optimized Workloads
@@ -16,8 +16,16 @@ The table below provides links to run each workload in a docker container. The c
| Model | Framework | Mode and Documentation | Dataset |
| ----------------------------| ---------- | ----------| ------------ |
-| [ResNet 50 v1.5](https://github.com/tensorflow/models/tree/v2.11.0/official/legacy/image_classification/resnet) | TensorFlow | [INT8 Inference](https://github.com/IntelAI/models/blob/master/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md) | [ImageNet 2012](https://github.com/IntelAI/models/tree/master/datasets/imagenet/README.md) |
-| [SSD-MobileNet](https://arxiv.org/pdf/1704.04861.pdf) | TensorFlow | [INT8 Inference](https://github.com/IntelAI/models/blob/master/quickstart/object_detection/tensorflow/ssd-mobilenet/inference/gpu/DEVCATALOG.md) | [COCO 2017 validation dataset](https://github.com/IntelAI/models/tree/master/datasets/coco#download-and-preprocess-the-coco-validation-images) |
-| [ResNet 50 v1.5](https://arxiv.org/pdf/1512.03385.pdf) | PyTorch | [INT8 Inference](https://github.com/IntelAI/models/blob/master/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md) | [ImageNet 2012](https://github.com/IntelAI/models/tree/master/datasets/imagenet/README.md) |
-| [SSD-MobileNet v1](https://arxiv.org/pdf/1704.04861.pdf) | PyTorch | [INT8 Inference](https://github.com/IntelAI/models/blob/master/quickstart/object_detection/pytorch/ssd-mobilenet/inference/gpu/DEVCATALOG.md) | [COCO 2017](https://github.com/IntelAI/models/blob/master/quickstart/object_detection/pytorch/ssd-mobilenet/inference/gpu/README.md#datasets) |
-| [YOLO v4](https://arxiv.org/pdf/1704.04861.pdf) | PyTorch | [INT8 Inference](https://github.com/IntelAI/models/blob/master/quickstart/object_detection/pytorch/yolov4/inference/gpu/DEVCATALOG.md) | [COCO 2017](https://github.com/IntelAI/models/blob/master/quickstart/object_detection/pytorch/ssd-mobilenet/inference/gpu/README.md#datasets) |
+| [ResNet 50 v1.5](https://github.com/tensorflow/models/tree/v2.12.1/official/legacy/image_classification/resnet) | TensorFlow | [INT8 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md) | [ImageNet 2012](https://github.com/IntelAI/models/tree/v2.12.1/datasets/imagenet/README.md) |
+| [MaskRCNN](https://arxiv.org/abs/1703.06870) | TensorFlow | [FP16 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/image_segmentation/tensorflow/maskrcnn/inference/gpu/DEVCATALOG.md) | [COCO 2017](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/image_segmentation/tensorflow/maskrcnn/inference/gpu/DEVCATALOG.md#download-dataset) |
+| [EfficientNet](https://arxiv.org/abs/1905.11946) B0,B3 | TensorFlow| [FP16 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/DEVCATALOG.md) | Dummy Image
+| [Stable Diffusion](https://arxiv.org/abs/2112.10752) | TensorFlow | [FP32,FP16 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/DEVCATALOG.md) | Text prompts |
+| [ResNet 50 v1.5](https://arxiv.org/pdf/1512.03385.pdf) | PyTorch | [INT8 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md) | [ImageNet 2012](https://github.com/IntelAI/models/tree/v2.12.1/datasets/imagenet/README.md) |
+| [YOLOv5](https://ui.adsabs.harvard.edu/abs/2021zndo...4679653J/abstract) | PyTorch | [FP16 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/object_detection/pytorch/yolov5/inference/gpu/DEVCATALOG.md) | Dummy Image |
+| [Stable Diffusion](https://arxiv.org/abs/2112.10752) | PyTorch | [FP32,FP16 Inference](https://github.com/IntelAI/models/blob/v2.12.1/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/DEVCATALOG.md) | Text prompts
+| [SSD-MobileNet](https://arxiv.org/pdf/1704.04861.pdf) | TensorFlow | [INT8 Inference](https://github.com/IntelAI/models/blob/v2.11.1/quickstart/object_detection/tensorflow/ssd-mobilenet/inference/gpu/DEVCATALOG.md) | [COCO 2017](https://github.com/IntelAI/models/tree/v2.11.1/datasets/coco#download-and-preprocess-the-coco-validation-images) |
+| [SSD-MobileNet v1](https://arxiv.org/pdf/1704.04861.pdf) | PyTorch | [INT8 Inference](https://github.com/IntelAI/models/blob/v2.11.1/quickstart/object_detection/pytorch/ssd-mobilenet/inference/gpu/DEVCATALOG.md) | [COCO 2017](https://github.com/IntelAI/models/blob/v2.11.1/quickstart/object_detection/pytorch/ssd-mobilenet/inference/gpu/README.md#datasets) |
+| [YOLOv4](https://arxiv.org/pdf/1704.04861.pdf) | PyTorch | [INT8 Inference](https://github.com/IntelAI/models/blob/v2.11.1/quickstart/object_detection/pytorch/yolov4/inference/gpu/DEVCATALOG.md) | [COCO 2017](https://github.com/IntelAI/models/blob/v2.11.1/quickstart/object_detection/pytorch/ssd-mobilenet/inference/gpu/README.md#datasets) |
+
+
+**Note**: SSD-MobileNet and YOLOv4 models are supported on older Intel® Extension for TensorFlow* v2.12 and Intel® Extension for PyTorch* 1.13.100+xpu versions. The other models in the list are validated on Intel® Extension for TensorFlow* v2.13 and Intel® Extension for PyTorch* 2.0.100+xpu versions.
diff --git a/docs/general/pytorch/BareMetalSetup.md b/docs/general/pytorch/BareMetalSetup.md
index 4cb212c84..4734f3fb9 100644
--- a/docs/general/pytorch/BareMetalSetup.md
+++ b/docs/general/pytorch/BareMetalSetup.md
@@ -1,26 +1,17 @@
# Install Intel® Extension for PyTorch
-pip install intel-extension-for-pytorch==2.0.0
+Prepare the environment, you may create a Python virtual enviromment `virtualenv` or `conda` prior to installing dependencies.
-## The following components are required by some PyTorch workloads. Only build them if indicated in the documentation for that workload.
+ # Install Intel® Extension for PyTorch
+ pip install intel-extension-for-pytorch
+ # Install torch,torchvision
+ python -m pip install torch torchvision
+
+## The following components are required by some PyTorch workloads. Only build them if indicated in the documentation for that workload.
-### Prepare the environment:
+ # Requirements:
gcc >= 5
Cmake >= 3.19.6
- wget https://repo.continuum.io/miniconda/Miniconda3-py38_4.12.0-Linux-x86_64.sh -O miniconda.sh
- chmod +x miniconda.sh
- ./miniconda.sh -b -p ~/miniconda
- ./miniconda/bin/conda create -yn pytorch
- export PATH=~/miniconda/bin:$PATH
- source ./miniconda/bin/activate pytorch
- pip install sklearn onnx
- pip install lark-parser hypothesis
- conda install numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses psutil
- export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
- export work_space=/home/sdp (you can get the summary.log in this path where the models performance and accuracy write)
-
- # Install torch,torchvision
- python -m pip install torch==2.0.0 torchvision==0.15.1
-
+
### Install jemalloc
Install jemalloc either using conda or from source
@@ -45,11 +36,6 @@ pip install intel-extension-for-pytorch==2.0.0
make
make install
-### Build vision
- cd ..
- git clone https://github.com/pytorch/vision
- cd vision
- python setup.py install
### Build torch-ccl
cd ..
@@ -58,4 +44,3 @@ pip install intel-extension-for-pytorch==2.0.0
git submodule sync
git submodule update --init --recursive
python setup.py install
-
diff --git a/docs/general/tensorflow/AIKit.md b/docs/general/tensorflow/AIKit.md
index 617b50e05..fcda5555c 100644
--- a/docs/general/tensorflow/AIKit.md
+++ b/docs/general/tensorflow/AIKit.md
@@ -1,7 +1,7 @@
# Using the Model Zoo in the Intel® oneAPI AI Analytics Toolkit
The Model Zoo is bundled as part of the
-[Intel® oneAPI AI Analytics Toolkit](https://software.intel.com/content/www/us/en/develop/tools/oneapi/ai-analytics-toolkit.html) (AI Kit).
+[Intel® oneAPI AI Analytics Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/ai-analytics-toolkit.html) (AI Kit).
Follow the instructions below to get your environment setup with AI Kit to run
TensorFlow models.
@@ -9,7 +9,7 @@ TensorFlow models.
Use the link below for instructions on how to install AI Kit or run the AI Kit
docker container:
-[https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-ai-linux/top.html](https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-ai-linux/top.html)
+[https://www.intel.com/content/www/us/en/docs/oneapi-ai-analytics-toolkit/get-started-guide-linux/2023-1/overview.html](https://www.intel.com/content/www/us/en/docs/oneapi-ai-analytics-toolkit/get-started-guide-linux/2023-1/overview.html)
## Activate a Conda Environment
diff --git a/docs/general/tensorflow/GeneralBestPractices.md b/docs/general/tensorflow/GeneralBestPractices.md
index 4760a327d..119b5905c 100644
--- a/docs/general/tensorflow/GeneralBestPractices.md
+++ b/docs/general/tensorflow/GeneralBestPractices.md
@@ -3,9 +3,9 @@
## Introduction
[TensorFlow*](https://www.tensorflow.org/) is one of the most popular deep learning frameworks for large-scale machine learning (ML) and deep learning (DL).
-Since 2016, Intel and Google engineers have been working together to [optimize TensorFlow performance](https://software.intel.com/en-us/ai-academy/frameworks/tensorflow) for deep learning training and inference on Intel® Xeon® processors using the [Intel® oneAPI Deep Neural Network Library (Intel® oneDNN)](https://github.com/oneapi-src/oneDNN), formerly called Intel MKL-DNN.
+Since 2016, Intel and Google engineers have been working together to [optimize TensorFlow performance](https://www.intel.com/content/www/us/en/developer/tools/frameworks/overview.html#gs.34b2dr) for deep learning training and inference on Intel® Xeon® processors using the [Intel® oneAPI Deep Neural Network Library (Intel® oneDNN)](https://github.com/oneapi-src/oneDNN), formerly called Intel MKL-DNN.
The Intel oneDNN primitives library includes convolution, normalization, activation, and other primitives.
-Please see the [install guide](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide) for how to set up Intel® Optimization for TensorFlow on your system for accelerated TensorFlow execution on CPU platforms with no code changes.
+Please see the [install guide](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html) for how to set up Intel® Optimization for TensorFlow on your system for accelerated TensorFlow execution on CPU platforms with no code changes.
## Performance Metrics
@@ -19,7 +19,7 @@ However, if you want to prioritize one metric over the other or further tune Ten
## TensorFlow Configuration Settings
-These are the parameters you need to set when running TensorFlow with Intel oneDNN. A more complete description of these settings can be found in the [performance considerations article](https://software.intel.com/en-us/articles/maximize-TensorFlow-performance-on-cpu-considerations-and-recommendations-for-inference).
+These are the parameters you need to set when running TensorFlow with Intel oneDNN. A more complete description of these settings can be found in the [performance considerations article](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html).
### TensorFlow Runtime Settings
@@ -27,7 +27,7 @@ These are the parameters you need to set when running TensorFlow with Intel oneD
* ***intra_op_parallelism_threads*** is the number of threads in each threadpool to use for a TensorFlow session. This should be set to the number of physical cores may be different from the number of logical cores or CPUs and can be found in Linux with the `lscpu` command.
-* ***Data Format*** specifies the way data is stored and accesed in memory. We recommend using channels-first (NCHW) format. Please see the [data format section of performance doc](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference#inpage-nav-2-2) for more information.
+* ***Data Format*** specifies the way data is stored and accesed in memory. We recommend using channels-first (NCHW) format. Please see the [data format section of performance doc](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html#inpage-nav-2-2) for more information.
### Environment Variables
diff --git a/docs/image_recognition/tensorflow/Tutorial.md b/docs/image_recognition/tensorflow/Tutorial.md
index 72845dbe3..5ed214bed 100644
--- a/docs/image_recognition/tensorflow/Tutorial.md
+++ b/docs/image_recognition/tensorflow/Tutorial.md
@@ -76,7 +76,7 @@ Below are the set of run-time options recommended by Intel on ResNet50, ResNet10
-*Note: Refer to the [link](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference) here to learn more about the run time options.*
+*Note: Refer to the [link](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html) here to learn more about the run time options.*
Run the following commands to get your processor information
@@ -144,7 +144,7 @@ You can refer to [ImageNet](/datasets/imagenet) or [Coco Dataset](http://cocodat
### Run inference
1. Pull the relevant Intel-optimized TensorFlow Docker image. We'll be running the pretrained model to infer on Docker container.
-[Click here](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide) to find all the available Docker images.
+[Click here](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html) to find all the available Docker images.
```bash
docker pull intel/intel-optimized-tensorflow:latest
```
diff --git a/docs/language_modeling/tensorflow/InferenceTutorial.md b/docs/language_modeling/tensorflow/InferenceTutorial.md
index 1ac3be165..6e76b2fb8 100644
--- a/docs/language_modeling/tensorflow/InferenceTutorial.md
+++ b/docs/language_modeling/tensorflow/InferenceTutorial.md
@@ -32,7 +32,7 @@ Below are the set of run-time options tested empirically on BERT Large and recom
|KMP_SETTINGS| 1 |
|OMP_NUM_THREADS |# physical cores - 1 or # physical cores - 2|
-Note 1: Refer to this [link](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference) to learn more about the run-time options.
+Note 1: Refer to this [link](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html) to learn more about the run-time options.
Note 2: You can remove `verbose` from `KMP_AFFINITY` setting to avoid verbose output at runtime.
@@ -100,7 +100,7 @@ This directory will be passed as the `--checkpoint` location when running infere
4. Install [Docker](https://docs.docker.com/v17.09/engine/installation/) since the tutorial runs in a Docker container.
5. Pull the relevant Intel-optimized TensorFlow Docker image.
-[Click here](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide) to find all the available Docker images.
+[Click here](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html) to find all the available Docker images.
```bash
docker pull intel/intel-optimized-tensorflow:latest
```
diff --git a/docs/language_modeling/tensorflow/TrainingTutorial.md b/docs/language_modeling/tensorflow/TrainingTutorial.md
index 9ddce4c88..92bb6a2ad 100644
--- a/docs/language_modeling/tensorflow/TrainingTutorial.md
+++ b/docs/language_modeling/tensorflow/TrainingTutorial.md
@@ -30,7 +30,7 @@ Below are the set of run-time options tested empirically on BERT Large and recom
|KMP_BLOCKTIME| 1 |
|OMP_NUM_THREADS |physical cores|
-Note 1: Refer to this [link](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference) to learn more about the run time options.
+Note 1: Refer to this [link](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html) to learn more about the run time options.
Note 2: You can remove `verbose` from `KMP_AFFINITY` setting to avoid verbose output at runtime.
diff --git a/docs/language_translation/tensorflow/Tutorial.md b/docs/language_translation/tensorflow/Tutorial.md
index d9c420b47..4b18ca57e 100644
--- a/docs/language_translation/tensorflow/Tutorial.md
+++ b/docs/language_translation/tensorflow/Tutorial.md
@@ -33,7 +33,7 @@ Below are the set of run-time options tested empirically on Transformer-LT and r
|KMP_BLOCKTIME| 1 |
|OMP_NUM_THREADS |physical cores|
-Note 1: Refer to this [link](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference) to learn more about the run time options.
+Note 1: Refer to this [link](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html) to learn more about the run time options.
Note 2: You can remove `verbose` from `KMP_AFFINITY` setting to avoid verbose output at runtime.
@@ -123,7 +123,7 @@ Or, if you have your own model/data, ensure the folder structure following the s
### Run inference
1. Pull the relevant Intel-optimized TensorFlow Docker image.
- [Click here](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide) to find all the available Docker images.
+ [Click here](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html) to find all the available Docker images.
```bash
docker pull docker.io/intel/intel-optimized-tensorflow:latest
```
diff --git a/docs/notebooks/perf_analysis/README.md b/docs/notebooks/perf_analysis/README.md
index 5868488a3..830685b96 100755
--- a/docs/notebooks/perf_analysis/README.md
+++ b/docs/notebooks/perf_analysis/README.md
@@ -32,7 +32,7 @@ There are two different analysis type.
> NOTE: No action required if users use Intel DevCloud as their environment or the container for performance comparison with Jupyter Notebooks.
- Please refer to [Intel oneAPI DevCloud](https://intelsoftwaresites.secure.force.com/devcloud/oneapi) for Intel DevCloud.
- - Please refer to [Intel® oneContainer Portal](https://software.intel.com/content/www/us/en/develop/tools/containers.html) for the docker container.
+ - Please refer to [Intel® oneContainer Portal](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html) for the docker container.
1. **Python3 Environment**
Choose one of:
diff --git a/docs/recommendation/tensorflow/Tutorial.md b/docs/recommendation/tensorflow/Tutorial.md
index c95880e5e..e5327342a 100644
--- a/docs/recommendation/tensorflow/Tutorial.md
+++ b/docs/recommendation/tensorflow/Tutorial.md
@@ -43,7 +43,7 @@ Note that while tuning these important run-time parameters, do not over/under us
|KMP_BLOCKTIME| 1 |
|OMP_NUM_THREADS | 1 to physical cores |
-*Note: Refer to [this article](https://software.intel.com/en-us/articles/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference) to learn more about the run time options.*
+*Note: Refer to [this article](https://www.intel.com/content/www/us/en/developer/articles/technical/maximize-tensorflow-performance-on-cpu-considerations-and-recommendations-for-inference.html) to learn more about the run time options.*
Intel's data science team trained and published a Wide and Deep model on Kaggle's Display Advertising Challenge dataset, and has empirically tested and identified the best run-time settings
to run inference, which is illustrated below in the hands-on-tutorial section.
@@ -147,7 +147,7 @@ Follow the instructions below to download and prepare the dataset.
### Run inference
1. Pull the relevant Intel Optimizations for TensorFlow Docker image. We'll be running the pretrained model to infer in a Docker container.
- [Click here](https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide) to find all the available Docker images.
+ [Click here](https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html) to find all the available Docker images.
```bash
docker pull intel/intel-optimized-tensorflow:latest
```
diff --git a/models/generative-ai/pytorch/stable_diffusion/inference/gpu/main.py b/models/generative-ai/pytorch/stable_diffusion/inference/gpu/main.py
new file mode 100644
index 000000000..f2b5b829b
--- /dev/null
+++ b/models/generative-ai/pytorch/stable_diffusion/inference/gpu/main.py
@@ -0,0 +1,266 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2023 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 os
+import time
+import sys
+import torch
+from diffusers import StableDiffusionPipeline
+import argparse
+import numpy as np
+from scipy.linalg import sqrtm
+from PIL import Image
+import pytorch_fid
+
+parser = argparse.ArgumentParser(description='PyTorch StableDiffusion TexttoImage')
+parser.add_argument("--arch", type=str, default='CompVis/stable-diffusion-v1-4', help="model name")
+parser.add_argument('--prompt', default=[
+ "a photo of an astronaut riding a horse on mars",
+ "a photo of a cat skates in Square",
+ "A painting of a squirrel eating a burger",
+ "A photo of dog in the room"], type=list, help='prompt')
+parser.add_argument('--batch_size', default=1, type=int, help='batch size')
+parser.add_argument('--idx_start', default=0, type=int, help='select the start index of image')
+parser.add_argument('--precision', default="fp32", type=str, help='precision')
+parser.add_argument('--amp', action='store_true', default=False, help='use amp in model')
+parser.add_argument('--jit', action='store_true', default=False, help='enable JIT')
+parser.add_argument('--iteration', default=5, type=int, help='test iterations')
+parser.add_argument('--warmup_iter', default=2, type=int, help='test warmup')
+parser.add_argument('--device', default='xpu', type=str, help='cpu, cuda or xpu')
+parser.add_argument('--save_image', action='store_true', default=False, help='save image')
+parser.add_argument('--save_tensor', action='store_true', default=False, help='save tensor')
+parser.add_argument('--accuracy', action='store_true', default=False, help='compare the result with cuda')
+parser.add_argument('--wei_path', default='CompVis/stable-diffusion-v1-4', type=str, metavar='PATH',
+ help='path to model structure or weight')
+parser.add_argument('--ref_path', default='', type=str, metavar='PATH',
+ help='path to reference image (default: none)')
+parser.add_argument('--save_path', default='./xpu_result', type=str, help='output image dir')
+parser.add_argument('--num_inference_steps', default=50, type=int, help='number of unet step')
+parser.add_argument('--channels_last', action='store_true', default=False, help='use channels last in inference')
+args = parser.parse_args()
+print(args)
+
+def compare(xpu_res, ref_res):
+ xpu = torch.tensor(xpu_res)
+ ref = torch.tensor(ref_res)
+
+ diff_value = torch.abs((xpu - ref))
+ max_diff = torch.max(diff_value)
+
+ shape = 1
+ for i in range(xpu.dim()):
+ shape = shape * xpu.shape[i]
+
+ value = diff_value > 0.1
+ num = torch.sum(value.contiguous().view(-1))
+ ratio1 = num / shape
+ print("difference larger than 0.1, ratio = {}".format(ratio1))
+
+ value = diff_value > 0.01
+ num = torch.sum(value.contiguous().view(-1))
+ ratio2 = num / shape
+ print("difference larger than 0.01, ratio = {}".format(ratio2))
+
+ value = diff_value > 0.001
+ num = torch.sum(value.contiguous().view(-1))
+ ratio3 = num / shape
+ print("difference larger than 0.001, ratio = {}".format(ratio3))
+
+ if ratio1 < 0.01 and ratio2 < 0.08 and ratio3 < 0.4:
+ print("accuracy pass")
+ else:
+ print("accuracy fail")
+
+def compare_pil_images(ref_res, cur_res):
+ xpu = torch.tensor(np.array(cur_res))
+ ref = torch.tensor(np.array(ref_res))
+
+ diff_value = torch.abs((xpu - ref))
+ max_diff = torch.max(diff_value)
+
+ shape = 1
+ for i in range(xpu.dim()):
+ shape = shape * xpu.shape[i]
+
+ value = diff_value > 0.1
+ num = torch.sum(value.contiguous().view(-1))
+ ratio1 = num / shape
+ print("difference larger than 0.1, ratio = {}".format(ratio1))
+
+ value = diff_value > 0.01
+ num = torch.sum(value.contiguous().view(-1))
+ ratio2 = num / shape
+ print("difference larger than 0.01, ratio = {}".format(ratio2))
+
+ value = diff_value > 0.001
+ num = torch.sum(value.contiguous().view(-1))
+ ratio3 = num / shape
+ print("difference larger than 0.001, ratio = {}".format(ratio3))
+
+ if ratio1 < 0.01 and ratio2 < 0.08 and ratio3 < 0.4:
+ print("accuracy pass")
+ else:
+ print("accuracy fail")
+
+def main():
+ profiling = os.environ.get("PROFILE", "OFF").upper() in ["1", "Y", "ON", "YES", "TRUE"]
+
+ # prompt = ["A painting of a squirrel eating a burger"]
+ seed = 666
+ if args.device == "xpu":
+ import intel_extension_for_pytorch as ipex
+ idx = torch.xpu.current_device()
+ generator = torch.xpu.default_generators[idx]
+ generator.manual_seed(seed)
+ elif args.device == "cuda":
+ generator = torch.Generator(device=args.device).manual_seed(seed)
+ else:
+ generator = torch.Generator(device=args.device)
+
+ if args.precision == "fp32":
+ datatype = torch.float
+ elif args.precision == "fp16":
+ datatype = torch.float16
+ elif args.precision == "bf16":
+ datatype = torch.bfloat16
+ else:
+ print("unsupported datatype")
+ sys.exit()
+
+ if args.precision == "fp32":
+ pipe = StableDiffusionPipeline.from_pretrained(args.wei_path)
+ else:
+ pipe = StableDiffusionPipeline.from_pretrained(args.wei_path, torch_dtype=datatype, revision=args.precision)
+ if args.channels_last:
+ pipe.unet = pipe.unet.to(memory_format=torch.channels_last)
+ pipe.vae.to(memory_format=torch.channels_last)
+ print("---- Use NHWC model.")
+
+ pipe = pipe.to(args.device)
+ if args.amp:
+ pipe.unet = torch.xpu.optimize(model=pipe.unet, dtype=datatype)
+
+ out_type = "pil"
+ if args.accuracy or args.save_tensor:
+ out_type = "tensor"
+
+ total_time = 0
+ print("output type is: ", out_type)
+ with torch.no_grad():
+ for step in range(args.warmup_iter):
+ idx1 = args.idx_start + int(step * args.batch_size)
+ idx2 = args.idx_start + int((step + 1) * args.batch_size)
+ input = args.prompt[idx1:idx2]
+ if args.device == "xpu":
+ if args.amp:
+ with torch.xpu.amp.autocast(enabled=True, dtype=datatype):
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ else:
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ torch.xpu.synchronize()
+ elif args.device == "cuda":
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ torch.cuda.synchronize()
+ else:
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+
+ image_before = []
+ iter = 0
+ for step in range(args.iteration):
+ print("Iteration = {}".format(step))
+ step = 0
+ idx1 = args.idx_start + int(step * args.batch_size)
+ idx2 = args.idx_start + int((step + 1) * args.batch_size)
+ print("idx1={}".format(idx1))
+ print("idx2={}".format(idx2))
+ input = args.prompt[idx1:idx2]
+ print("input is : ", input)
+
+
+ if args.device == "xpu":
+ with torch.autograd.profiler_legacy.profile(profiling, use_xpu=True, record_shapes=True) as prof:
+ try:
+ import memory_check
+ memory_check.display_mem("xpu:0")
+ except:
+ pass
+ start_time = time.time()
+ if args.amp:
+ with torch.xpu.amp.autocast(enabled=True, dtype=datatype):
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ else:
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ torch.xpu.synchronize()
+ end_time = time.time()
+ if profiling:
+ torch.save(prof.key_averages().table(sort_by="self_xpu_time_total"), 'profile.pt')
+ torch.save(prof.table(sort_by="id", row_limit=-1), 'profile_detailed.pt')
+ prof.export_chrome_trace('./profile_trace.json')
+ elif args.device == "cuda":
+ start_time = time.time()
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ torch.cuda.synchronize()
+ end_time = time.time()
+ else:
+ start_time = time.time()
+ images = pipe(input, generator=generator, num_inference_steps=args.num_inference_steps, output_type=out_type).images
+ end_time = time.time()
+
+
+ iter_time = end_time - start_time
+ total_time += iter_time
+ # latency = total_time / (step + 1)
+ # throughput = args.batch_size / latency
+ # print("---latency={} s".format(latency))
+ # print("---throughput={} fps".format(throughput))
+
+ if args.accuracy:
+ for i in range(args.batch_size):
+ name = "result_{}_{}.png".format(idx1 + i, iter) if args.save_image else "result_{}_{}.pt".format(idx1 + i, iter)
+ name = os.path.join(args.ref_path, name)
+ if args.save_image:
+ ref_image = Image.open(name)
+ compare_pil_images(ref_image, images[i])
+ else:
+ ref_pt = torch.load(name)
+ compare(ref_pt, images[i])
+
+ if not os.path.exists(args.save_path):
+ os.mkdir(args.save_path)
+
+ if args.save_tensor:
+ for i in range(args.batch_size):
+ file_name = "./result_{}_{}.pt".format(idx1 + i, iter)
+ save_path = os.path.join(args.save_path, file_name)
+ torch.save(images[i], save_path)
+
+ if args.save_image:
+ for i in range(args.batch_size):
+ file_name = "./result_{}_{}.png".format(idx1 + i, iter)
+ save_path = os.path.join(args.save_path, file_name)
+ images[i].save(save_path)
+ iter += 1
+
+ total_sample = args.iteration * args.batch_size
+ latency = total_time / total_sample * 1000
+ throughput = total_sample / total_time
+ print("inference Latency: {} ms".format(latency))
+ print("inference Throughput: {} samples/s".format(throughput))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/keras_fid.py b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/keras_fid.py
new file mode 100644
index 000000000..46c627003
--- /dev/null
+++ b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/keras_fid.py
@@ -0,0 +1,77 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+
+# example of calculating the frechet inception distance in Keras
+import numpy as np
+from numpy import cov
+from numpy import trace
+from numpy import iscomplexobj
+from numpy import asarray
+from numpy.random import randint
+from scipy.linalg import sqrtm
+from keras.applications.inception_v3 import InceptionV3
+from keras.applications.inception_v3 import preprocess_input
+from skimage.transform import resize
+
+
+# scale an array of images to a new size
+def scale_images(images, new_shape):
+ images_list = list()
+ for image in images:
+ # resize with nearest neighbor interpolation
+ new_image = resize(image, new_shape, 0)
+ # store
+ images_list.append(new_image)
+ return asarray(images_list)
+
+
+def calculate_fid(model, images1, images2):
+ act1 = model.predict(images1)
+ act2 = model.predict(images2)
+ mu1, sigma1 = act1.mean(axis=0), cov(act1, rowvar=False)
+ mu2, sigma2 = act2.mean(axis=0), cov(act2, rowvar=False)
+ ssdiff = np.sum((mu1 - mu2) ** 2.0)
+ covmean = sqrtm(sigma1.dot(sigma2))
+ if iscomplexobj(covmean):
+ covmean = covmean.real
+ fid = ssdiff + trace(sigma1 + sigma2 - 2.0 * covmean)
+ return fid
+
+
+def fid(images1, images2):
+ if images1.shape[0] == 1:
+ images1 = np.repeat(images1, 2, axis=0)
+ if images2.shape[0] == 1:
+ images2 = np.repeat(images2, 2, axis=0)
+ assert(images1.shape == images2.shape)
+ # convert integer to floating point values
+ images1 = images1.astype("float32")
+ images2 = images2.astype("float32")
+ H, W, C = images1.shape[1], images1.shape[2], images1.shape[3]
+ # pre-process images
+ images1 = preprocess_input(images1)
+ images2 = preprocess_input(images2)
+ # fid between images1 and images1
+ model = InceptionV3(include_top=False, pooling="avg", input_shape=(H, W, C))
+ fid = calculate_fid(model, images1, images2)
+ return fid
+
diff --git a/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/patch b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/patch
new file mode 100644
index 000000000..8f5b5d4f2
--- /dev/null
+++ b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/patch
@@ -0,0 +1,365 @@
+diff --git a/keras_cv/models/stable_diffusion/__internal__/layers/attention_block.py b/keras_cv/models/stable_diffusion/__internal__/layers/attention_block.py
+index e7e1896..21fba0c 100644
+--- a/keras_cv/models/stable_diffusion/__internal__/layers/attention_block.py
++++ b/keras_cv/models/stable_diffusion/__internal__/layers/attention_block.py
+@@ -14,6 +14,12 @@
+
+ import tensorflow as tf
+ from tensorflow import keras
++try:
++ import intel_extension_for_tensorflow as itex
++ keras.layers.GroupNormalization = itex.ops.GroupNormalization
++except:
++ pass
++
+
+ from keras_cv.models.stable_diffusion.__internal__.layers.padded_conv2d import (
+ PaddedConv2D,
+diff --git a/keras_cv/models/stable_diffusion/__internal__/layers/resnet_block.py b/keras_cv/models/stable_diffusion/__internal__/layers/resnet_block.py
+index 29aeaaa..11d4be6 100644
+--- a/keras_cv/models/stable_diffusion/__internal__/layers/resnet_block.py
++++ b/keras_cv/models/stable_diffusion/__internal__/layers/resnet_block.py
+@@ -13,6 +13,13 @@
+ # limitations under the License.
+
+ from tensorflow import keras
++try:
++ import intel_extension_for_tensorflow as itex
++ keras.layers.GroupNormalization = itex.ops.GroupNormalization
++except:
++ pass
++
++
+
+ from keras_cv.models.stable_diffusion.__internal__.layers.padded_conv2d import (
+ PaddedConv2D,
+diff --git a/keras_cv/models/stable_diffusion/decoder.py b/keras_cv/models/stable_diffusion/decoder.py
+index fe619d3..ccc4b5b 100644
+--- a/keras_cv/models/stable_diffusion/decoder.py
++++ b/keras_cv/models/stable_diffusion/decoder.py
+@@ -13,6 +13,12 @@
+ # limitations under the License.
+
+ from tensorflow import keras
++try:
++ import intel_extension_for_tensorflow as itex
++ keras.layers.GroupNormalization = itex.ops.GroupNormalization
++except:
++ pass
++
+
+ from keras_cv.models.stable_diffusion.__internal__.layers.attention_block import ( # noqa: E501
+ AttentionBlock,
+diff --git a/keras_cv/models/stable_diffusion/diffusion_model.py b/keras_cv/models/stable_diffusion/diffusion_model.py
+index 25b5241..dafdcbc 100644
+--- a/keras_cv/models/stable_diffusion/diffusion_model.py
++++ b/keras_cv/models/stable_diffusion/diffusion_model.py
+@@ -14,7 +14,14 @@
+
+ import tensorflow as tf
+ from tensorflow import keras
+-
++try:
++ import intel_extension_for_tensorflow as itex
++ keras.layers.GroupNormalization = itex.ops.GroupNormalization
++ keras.layers.LayerNormalization = itex.ops.LayerNormalization
++except:
++ pass
++
++
+ from keras_cv.models.stable_diffusion.__internal__.layers.padded_conv2d import (
+ PaddedConv2D,
+ )
+@@ -302,6 +309,26 @@ class CrossAttention(keras.layers.Layer):
+ self.num_heads = num_heads
+ self.head_size = head_size
+ self.out_proj = keras.layers.Dense(num_heads * head_size)
++
++ def naive_scaled_dot_product_attention(self, query, key, value):
++ i_dtype = query.dtype
++ atten_scores = tf.matmul(query, key, transpose_b=True)
++ atten_scores = tf.multiply(atten_scores, tf.cast(self.scale, i_dtype))
++ atten_probs = tf.nn.softmax(atten_scores)
++ # `atten_output` = [B, N, F, H]
++ atten_output = tf.matmul(atten_probs, value)
++ # `atten_output` = [B, F, N, H]
++ atten_output = tf.transpose(a=atten_output, perm=[0, 2, 1, 3])
++ return atten_output
++
++
++ def sdp(self, q, k, v):
++ try:
++ from intel_extension_for_tensorflow.python.ops.multi_head_attention import scaled_dot_product_attention
++ output = scaled_dot_product_attention(q, k, v, use_fast_attention=True)
++ except ImportError:
++ output = self.naive_scaled_dot_product_attention(q, k, v)
++ return output
+
+ def call(self, inputs):
+ inputs, context = inputs
+@@ -316,17 +343,10 @@ class CrossAttention(keras.layers.Layer):
+ )
+
+ q = tf.transpose(q, (0, 2, 1, 3)) # (bs, num_heads, time, head_size)
+- k = tf.transpose(k, (0, 2, 3, 1)) # (bs, num_heads, head_size, time)
++ k = tf.transpose(k, (0, 2, 1, 3)) # (bs, num_heads, head_size, time)
+ v = tf.transpose(v, (0, 2, 1, 3)) # (bs, num_heads, time, head_size)
+
+- score = td_dot(q, k) * self.scale
+- weights = keras.activations.softmax(
+- score
+- ) # (bs, num_heads, time, time)
+- attn = td_dot(weights, v)
+- attn = tf.transpose(
+- attn, (0, 2, 1, 3)
+- ) # (bs, time, num_heads, head_size)
++ attn = self.sdp(q, k, v)
+ out = tf.reshape(
+ attn, (-1, inputs.shape[1], self.num_heads * self.head_size)
+ )
+@@ -352,10 +372,11 @@ class GEGLU(keras.layers.Layer):
+ def call(self, inputs):
+ x = self.dense(inputs)
+ x, gate = x[..., : self.output_dim], x[..., self.output_dim :]
+- tanh_res = keras.activations.tanh(
+- gate * 0.7978845608 * (1 + 0.044715 * (gate**2))
+- )
+- return x * 0.5 * gate * (1 + tanh_res)
++ # tanh_res = keras.activations.tanh(
++ # gate * 0.7978845608 * (1 + 0.044715 * (gate**2))
++ # )
++ # return x * 0.5 * gate * (1 + tanh_res)
++ return x * tf.keras.activations.gelu(gate, approximate=True)
+
+
+ def td_dot(a, b):
+diff --git a/keras_cv/models/stable_diffusion/image_encoder.py b/keras_cv/models/stable_diffusion/image_encoder.py
+index 614b11d..8212389 100644
+--- a/keras_cv/models/stable_diffusion/image_encoder.py
++++ b/keras_cv/models/stable_diffusion/image_encoder.py
+@@ -13,6 +13,12 @@
+ # limitations under the License.
+
+ from tensorflow import keras
++try:
++ import intel_extension_for_tensorflow as itex
++ keras.layers.GroupNormalization = itex.ops.GroupNormalization
++except:
++ pass
++
+
+ from keras_cv.models.stable_diffusion.__internal__.layers.attention_block import ( # noqa: E501
+ AttentionBlock,
+diff --git a/keras_cv/models/stable_diffusion/stable_diffusion.py b/keras_cv/models/stable_diffusion/stable_diffusion.py
+index 31752e8..b252e02 100644
+--- a/keras_cv/models/stable_diffusion/stable_diffusion.py
++++ b/keras_cv/models/stable_diffusion/stable_diffusion.py
+@@ -29,7 +29,8 @@ import math
+ import numpy as np
+ import tensorflow as tf
+ from tensorflow import keras
+-
++from keras import backend as K
++import os
+ from keras_cv.models.stable_diffusion.clip_tokenizer import SimpleTokenizer
+ from keras_cv.models.stable_diffusion.constants import _ALPHAS_CUMPROD
+ from keras_cv.models.stable_diffusion.constants import _UNCONDITIONAL_TOKENS
+@@ -51,6 +52,7 @@ class StableDiffusionBase:
+ img_height=512,
+ img_width=512,
+ jit_compile=False,
++ precision="fp32",
+ ):
+ # UNet requires multiples of 2**7 = 128
+ img_height = round(img_height / 128) * 128
+@@ -66,6 +68,7 @@ class StableDiffusionBase:
+ self._tokenizer = None
+
+ self.jit_compile = jit_compile
++ self.to_fp16 = (precision == "fp16")
+
+ def text_to_image(
+ self,
+@@ -207,18 +210,21 @@ class StableDiffusionBase:
+
+ # Iterative reverse diffusion stage
+ timesteps = tf.range(1, 1000, 1000 // num_steps)
++ t_embs_lst = self._get_timesteps_embedding(timesteps, batch_size)
++ contexts = tf.concat((unconditional_context, context), 0)
++
+ alphas, alphas_prev = self._get_initial_alphas(timesteps)
+ progbar = keras.utils.Progbar(len(timesteps))
+ iteration = 0
+ for index, timestep in list(enumerate(timesteps))[::-1]:
+ latent_prev = latent # Set aside the previous latent vector
+- t_emb = self._get_timestep_embedding(timestep, batch_size)
+- unconditional_latent = self.diffusion_model.predict_on_batch(
+- [latent, t_emb, unconditional_context]
+- )
+- latent = self.diffusion_model.predict_on_batch(
+- [latent, t_emb, context]
+- )
++ latents = tf.concat((latent, latent), 0)
++ t_embs = t_embs_lst[index]
++
++ pred_latent = self.diffusion_model.predict_on_batch(
++ [latents, t_embs, contexts])
++ unconditional_latent, latent = tf.split(pred_latent, 2)
++
+ latent = unconditional_latent + unconditional_guidance_scale * (
+ latent - unconditional_latent
+ )
+@@ -304,6 +310,23 @@ class StableDiffusionBase:
+ self._tokenizer = SimpleTokenizer()
+ return self._tokenizer
+
++ def _get_timesteps_embedding(
++ self, timesteps, batch_size, dim=320, max_period=10000
++ ):
++ half = dim // 2
++ freqs = tf.math.exp(
++ -math.log(max_period) * tf.range(0, half, dtype=tf.float32) / half
++ )
++ # timesteps shape: [num_steps]
++ args = tf.cast(tf.reshape(timesteps, [-1, 1]), dtype=tf.float32) * freqs
++ # embeddings shape:(steps, half)
++ embeddings = tf.concat([tf.math.cos(args), tf.math.sin(args)], axis=1)
++ embeddings = tf.expand_dims(embeddings, axis=1)
++ if self.to_fp16:
++ embeddings = tf.cast(embeddings, tf.float16)
++ # 2 is to concatenate the embedding of two forward pass
++ return tf.repeat(embeddings, batch_size * 2, axis=1)
++
+ def _get_timestep_embedding(
+ self, timestep, batch_size, dim=320, max_period=10000
+ ):
+@@ -314,6 +337,8 @@ class StableDiffusionBase:
+ args = tf.convert_to_tensor([timestep], dtype=tf.float32) * freqs
+ embedding = tf.concat([tf.math.cos(args), tf.math.sin(args)], 0)
+ embedding = tf.reshape(embedding, [1, -1])
++ if self.to_fp16:
++ embedding = tf.cast(embedding, tf.float16)
+ return tf.repeat(embedding, batch_size, axis=0)
+
+ def _get_initial_alphas(self, timesteps):
+@@ -324,14 +349,25 @@ class StableDiffusionBase:
+
+ def _get_initial_diffusion_noise(self, batch_size, seed):
+ if seed is not None:
+- return tf.random.stateless_normal(
+- (batch_size, self.img_height // 8, self.img_width // 8, 4),
+- seed=[seed, seed],
+- )
++ if self.to_fp16:
++ return tf.random.stateless_normal(
++ (batch_size, self.img_height // 8, self.img_width // 8, 4),
++ seed=[seed, seed], dtype=tf.float16
++ )
++ else:
++ return tf.random.stateless_normal(
++ (batch_size, self.img_height // 8, self.img_width // 8, 4),
++ seed=[seed, seed],
++ )
+ else:
+- return tf.random.normal(
+- (batch_size, self.img_height // 8, self.img_width // 8, 4)
+- )
++ if self.to_fp16:
++ return tf.random.normal(
++ (batch_size, self.img_height // 8, self.img_width // 8, 4), dtype=tf.float16
++ )
++ else:
++ return tf.random.normal(
++ (batch_size, self.img_height // 8, self.img_width // 8, 4)
++ )
+
+ @staticmethod
+ def _get_pos_ids():
+@@ -390,8 +426,9 @@ class StableDiffusion(StableDiffusionBase):
+ img_height=512,
+ img_width=512,
+ jit_compile=False,
++ precision="fp32",
+ ):
+- super().__init__(img_height, img_width, jit_compile)
++ super().__init__(img_height, img_width, jit_compile, precision)
+ print(
+ "By using this model checkpoint, you acknowledge that its usage is "
+ "subject to the terms of the CreativeML Open RAIL-M license at "
+@@ -405,7 +442,20 @@ class StableDiffusion(StableDiffusionBase):
+ needs to be modified.
+ """
+ if self._text_encoder is None:
+- self._text_encoder = TextEncoder(MAX_PROMPT_LENGTH)
++ if self.to_fp16:
++ self._text_encoder_fp32 = TextEncoder(MAX_PROMPT_LENGTH)
++ weights_fp32 = self._text_encoder_fp32.get_weights()
++ print("text_encoder before: ", np.unique(
++ [w.dtype for w in weights_fp32]), flush=True)
++ K.set_floatx('float16')
++ weights_fp16 = [w.astype(K.floatx()) for w in weights_fp32]
++ self._text_encoder = TextEncoder(
++ MAX_PROMPT_LENGTH, download_weights=False)
++ self._text_encoder.set_weights(weights_fp16)
++ print("text_encoder after: ", np.unique(
++ [w.dtype for w in self._text_encoder.get_weights()]), flush=True)
++ else:
++ self._text_encoder = TextEncoder(MAX_PROMPT_LENGTH)
+ if self.jit_compile:
+ self._text_encoder.compile(jit_compile=True)
+ return self._text_encoder
+@@ -420,6 +470,10 @@ class StableDiffusion(StableDiffusionBase):
+ self._diffusion_model = DiffusionModel(
+ self.img_height, self.img_width, MAX_PROMPT_LENGTH
+ )
++ wb = self._diffusion_model.get_weights()
++ print("text_encoder before: ", np.unique(
++ [w.dtype for w in wb]), flush=True)
++
+ if self.jit_compile:
+ self._diffusion_model.compile(jit_compile=True)
+ return self._diffusion_model
+@@ -475,8 +529,9 @@ class StableDiffusionV2(StableDiffusionBase):
+ img_height=512,
+ img_width=512,
+ jit_compile=False,
++ precision="fp32",
+ ):
+- super().__init__(img_height, img_width, jit_compile)
++ super().__init__(img_height, img_width, jit_compile, precision)
+ print(
+ "By using this model checkpoint, you acknowledge that its usage is "
+ "subject to the terms of the CreativeML Open RAIL++-M license at "
+@@ -490,7 +545,20 @@ class StableDiffusionV2(StableDiffusionBase):
+ needs to be modified.
+ """
+ if self._text_encoder is None:
+- self._text_encoder = TextEncoderV2(MAX_PROMPT_LENGTH)
++ if self.to_fp16:
++ self._text_encoder_fp32 = TextEncoderV2(MAX_PROMPT_LENGTH)
++ weights_fp32 = self._text_encoder_fp32.get_weights()
++ print("text_encoder before: ", np.unique(
++ [w.dtype for w in weights_fp32]), flush=True)
++ K.set_floatx('float16')
++ weights_fp16 = [w.astype(K.floatx()) for w in weights_fp32]
++ self._text_encoder = TextEncoderV2(
++ MAX_PROMPT_LENGTH, download_weights=False)
++ self._text_encoder.set_weights(weights_fp16)
++ print("text_encoder after: ", np.unique(
++ [w.dtype for w in self._text_encoder.get_weights()]), flush=True)
++ else:
++ self._text_encoder = TextEncoderV2(MAX_PROMPT_LENGTH)
+ if self.jit_compile:
+ self._text_encoder.compile(jit_compile=True)
+ return self._text_encoder
+@@ -505,6 +573,10 @@ class StableDiffusionV2(StableDiffusionBase):
+ self._diffusion_model = DiffusionModelV2(
+ self.img_height, self.img_width, MAX_PROMPT_LENGTH
+ )
++ wb = self._diffusion_model.get_weights()
++ print("diffusion_model before: ", np.unique(
++ [w.dtype for w in wb]), flush=True)
++
+ if self.jit_compile:
+ self._diffusion_model.compile(jit_compile=True)
+ return self._diffusion_model
diff --git a/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_accuracy.py b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_accuracy.py
new file mode 100644
index 000000000..6e95ea036
--- /dev/null
+++ b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_accuracy.py
@@ -0,0 +1,143 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+import time
+from keras_cv.models.stable_diffusion import StableDiffusion, StableDiffusionV2
+from tensorflow import keras
+import matplotlib.pyplot as plt
+import tensorflow as tf
+import argparse
+from keras_fid import fid
+import os
+import numpy as np
+from numpy import cov
+from numpy import trace
+from numpy import iscomplexobj
+from numpy.random import random
+from scipy.linalg import sqrtm
+
+
+parser = argparse.ArgumentParser("Stable Diffusion inference with TensorFlow")
+parser.add_argument(
+ "--use_xla",
+ action="store_true",
+ default=False,
+ help="whether to enable XLA compilation",
+)
+parser.add_argument(
+ "--num_steps", default=50, type=int, help="number of diffusion steps"
+)
+parser.add_argument(
+ "--precision", default="fp32", type=str, help="precision, only support(fp32, fp16)"
+)
+parser.add_argument(
+ "--load_ref_result", default=False, action="store_true", help="whether to load reference result"
+)
+parser.add_argument(
+ "--ref_result_dir", required=True, type=str, help="path to load/store refence result array"
+)
+parser.add_argument(
+ "--store_result_dir",required=True, type=str, help="path to store the result image"
+)
+args = parser.parse_args()
+
+
+def text2image(plot=False):
+ model = StableDiffusion(
+ img_width=512,
+ img_height=512,
+ jit_compile=args.use_xla,
+ precision=args.precision,
+ )
+
+ prompt_lst = [
+ "a photo of an astronaut riding a horse on mars",
+ "hyper realistic photo of very friendly and dystopian crater",
+ "ramen carved out of fractal rose ebony, in the style of hudson river school",
+ "ultrasaurus holding a black bean taco in the woods, near an identical cheneosaurus",
+ "a thundering retro robot crane inks on parchment with a droopy french bulldog",
+ "portrait painting of a shimmering greek hero, next to a loud frill-necked lizard",
+ "an astronaut standing on a engaging white rose, in the midst of by ivory cherry blossoms",
+ ]
+ seed = 65537
+ batch_size = 1
+
+ if args.load_ref_result and args.ref_result_dir:
+ print(f"loading reference result from {args.ref_result_dir}")
+ real_img_lst = np.reshape(np.loadtxt(args.ref_result_dir, dtype=np.int_), [len(prompt_lst), 512, 512, 3])
+ else:
+ print("regenerating real images")
+ real_img_lst = []
+ for prompt in prompt_lst:
+ real_image = model.text_to_image(
+ prompt=prompt,
+ batch_size=batch_size,
+ num_steps=args.num_steps,
+ seed=seed,
+ )
+ real_img_lst.append(real_image)
+ real_img_lst = np.concatenate(real_img_lst, axis=0)
+ np.savetxt(args.ref_result_dir, np.reshape(real_img_lst, -1), fmt='%d')
+
+ fake_img_lst = []
+ for prompt in prompt_lst:
+ fake_image = model.text_to_image(
+ prompt=prompt,
+ batch_size=batch_size,
+ num_steps=args.num_steps,
+ seed=seed,
+ )
+ fake_img_lst.append(fake_image)
+ fake_img_lst = np.concatenate(fake_img_lst, axis=0)
+
+ fid_score = fid(real_img_lst, fake_img_lst)
+ required_fid_score = -922.2165474372248
+ if np.allclose([fid_score], [required_fid_score], rtol=6, atol=1e-3):
+ print(f"accuray passed, required fid score is {required_fid_score}, and actual fid score is {fid_score}")
+ else:
+ print(f"accuray failed, required fid score is {required_fid_score}, and actual fid score is {fid_score}")
+
+ if plot:
+ plot_images("gpu_real", real_img_lst)
+ plot_images("gpu_fake", fake_img_lst)
+ print(f"for given {len(prompt_lst)} prompts, Fid is {fid_score}")
+
+
+
+def plot_images(comments, images):
+ path = args.store_result_dir
+ if not os.path.isdir(path):
+ os.mkdir(path)
+ png_name = "{}/{}_{}_imgs_{}steps.png".format(path,
+ comments, args.precision, args.num_steps
+ )
+ print("Start plotting the generated images to %s" % (png_name))
+ plt.figure(figsize=(20, 20))
+ for i in range(len(images)):
+ ax = plt.subplot(1, len(images), i + 1)
+ plt.imshow(images[i])
+ plt.axis("off")
+ plt.savefig(png_name)
+
+
+
+if __name__ == "__main__":
+ text2image(plot=True)
diff --git a/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_inference.py b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_inference.py
new file mode 100644
index 000000000..17db983e7
--- /dev/null
+++ b/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_inference.py
@@ -0,0 +1,110 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+import time
+from keras_cv.models.stable_diffusion import StableDiffusion, StableDiffusionV2
+from tensorflow import keras
+import matplotlib.pyplot as plt
+import tensorflow as tf
+import argparse
+from keras_fid import fid
+import os
+import numpy as np
+from numpy import cov
+from numpy import trace
+from numpy import iscomplexobj
+from numpy.random import random
+from scipy.linalg import sqrtm
+
+
+parser = argparse.ArgumentParser("Stable Diffusion inference with TensorFlow")
+parser.add_argument(
+ "--batch_size", default=1, type=int, help="number of images generated at one time"
+)
+parser.add_argument(
+ "--use_xla",
+ action="store_true",
+ default=False,
+ help="whether to enable XLA compilation",
+)
+parser.add_argument(
+ "--num_steps", default=50, type=int, help="number of diffusion steps"
+)
+parser.add_argument(
+ "--prompt",
+ default="a photo of an astronaut riding a horse on mars",
+ type=str,
+ help="the text prompt list to put into the text encoder",
+)
+parser.add_argument(
+ "--precision", default="fp32", type=str, help="precision, only support(fp32, fp16)"
+)
+parser.add_argument("--iterations", type=int, default=2, help="number of iterations")
+parser.add_argument(
+ "--store_result_dir",required=True, type=str, help="path to store the result image"
+)
+args = parser.parse_args()
+
+
+def text2image():
+ model = StableDiffusion(
+ img_width=512,
+ img_height=512,
+ jit_compile=args.use_xla,
+ precision=args.precision,
+ )
+ seed = 65537
+ print("Start Warmup")
+ model.text_to_image(
+ "warming up the model", batch_size=args.batch_size, num_steps=args.num_steps
+ )
+ # Start inference
+ print("Start running inference and generating images")
+ start = time.time()
+ for i in range(args.iterations):
+ images = model.text_to_image(prompt=args.prompt, batch_size=args.batch_size, seed=seed)
+ end = time.time()
+ latency = (end - start) / args.iterations / args.num_steps
+ throughput = 1 / latency
+ print("latency {} ms, throughput {} it/s".format(latency * 1000, throughput))
+ return images
+
+
+def plot_images(images):
+ path = args.store_result_dir
+ if not os.path.isdir(path):
+ os.mkdir(path)
+ png_name = "{}/{}_imgs_{}steps.png".format(path,
+ args.precision, args.num_steps
+ )
+ print("Start plotting the generated images to %s" % (png_name))
+ plt.figure(figsize=(20, 20))
+ for i in range(len(images)):
+ ax = plt.subplot(1, len(images), i + 1)
+ plt.imshow(images[i])
+ plt.axis("off")
+ plt.savefig(png_name)
+
+
+
+if __name__ == "__main__":
+ images = text2image()
+ plot_images(images)
diff --git a/models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py b/models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py
index c41784283..2c2526bc9 100644
--- a/models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py
+++ b/models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py
@@ -83,6 +83,11 @@
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
+# for convergence
+converged = False
+final_top1_acc = 0.0
+final_top5_acc = 0.0
+
cwd = os.path.dirname(os.path.abspath(__file__))
hub = os.path.expanduser("~/.cache/torch/intel")
if not os.path.exists(hub):
@@ -100,6 +105,8 @@
help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=90, type=int, metavar='N',
help='number of total epochs to run')
+parser.add_argument('--eval-start-epoch', default=0, type=int, metavar='N',
+ help='epoch start to run validation')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
@@ -156,15 +163,32 @@
metavar='N', help='mini-batch size for calibration')
parser.add_argument('--perchannel-weight', default=False,
help='do calibration with weight per channel quantization')
+parser.add_argument('--non-blocking', default=False, action='store_true',
+ help='non blocking H2D for input and target, default False')
parser.add_argument('--channels-last', action='store_true', help='enable channels last')
parser.add_argument('--num-iterations', default=0, type=int)
-parser.add_argument('--tensorboard', default=None, action='store_true',
- help='Use Tensorboard to visualize the training metrics')
+parser.add_argument('--converge', default=None, action='store_true',
+ help='Run convergence and use Tensorboard to visualize the training metrics')
parser.add_argument('--step-size', default=30, type=int, help='LR decay step size')
-parser.add_argument('--decay-epoch', default=66, type=int, help='LR half at specified epoch number')
+parser.add_argument('--step-gamma', default=0.1, type=float, help='set the step gamma')
+parser.add_argument('--last-step-boundary', default=80, type=int, help='last epoch to decay the LR')
+parser.add_argument('--warm-up-epoch', default=0, type=int, help='warm up epochs number for convergence')
+parser.add_argument('--decay-epochs', default=33, type=int, metavar='N',
+ help='number of decay epochs to run for lars')
+parser.add_argument('--lars', default=False, action='store_true', help='use lars for training')
+parser.add_argument('--lars-eta', default=0.0, type=float, help='set the lars epsilon')
+parser.add_argument('--skip-checkpoint', default=False, action='store_true', help='skip checkpoint saving')
+parser.add_argument('--skip-tensorboard', default=False, action='store_true', help='skip tensorboard')
parser.add_argument('--label-smoothing', default=0.0, type=float)
-parser.add_argument("--dummy", action="store_true", help='use dummy data for '
+parser.add_argument('--dummy', action="store_true", help='use dummy data for '
'benchmark training or val')
+parser.add_argument('--lr-scheduler', default='step', type=str,
+ help='choose lr scheduler, default step, can choose pow')
+parser.add_argument('--power-factor', default=1.0, type=float,
+ help='power factor for lr decay policy')
+parser.add_argument('--eval-period', default=1, type=int, help='period for doing online evaluation')
+parser.add_argument('--eval-offset', default=0, type=int, help='offset for doing online evaluation')
+parser.add_argument('--sota-target', default=75.9, type=float, help='set the lars epsilon')
parser.add_argument('--multiprocessing-distributed', action='store_true',
help='Use multi-processing distributed training to launch '
'N processes per node, which has N GPUs. This is the '
@@ -174,12 +198,56 @@
'performance, move H2D out of E2E time')
parser.add_argument("--save", help='Path to save entile model, save infernce mode, training is not available')
parser.add_argument("--load", help='Path to load entile inference model')
+parser.add_argument('--end-lr', type=float, default=1e-4,
+ help='the end learning rate')
# used for record best accrucy after validation
-best_acc1 = torch.zeros(1)
+best_acc1 = 0.0
+tensorboard_data = {'epoch': 0,
+ 'train': {'loss': 0.0, 'top1': 0.0, 'top5': 0.0},
+ 'eval': {'loss': 0.0, 'top1': 0.0, 'top5': 0.0}}
+global_lr = 0.0
+global_num_iter = 0
def main():
args = parser.parse_args()
+ if args.converge:
+ print('[info] ------------------ converge arguments ------------------')
+ print('running model: ', args.arch)
+ print('workers: ', args.workers)
+ print('running bf16: ', args.bf16)
+ print('total epochs: ', args.epochs)
+ print('warm up epoch: ', args.warm_up_epoch)
+ print('eval epoch: ', args.eval_start_epoch)
+ print('batch size: ', args.batch_size)
+ print('initial lr: ', args.lr)
+ print('lr scheduler: ', args.lr_scheduler)
+ if args.lr_scheduler == 'step':
+ print('lr step size: ', args.step_size)
+ print('lr step gamma: ', args.step_gamma)
+ print('lr step boundary:', args.last_step_boundary)
+ elif args.lr_scheduler == 'pow':
+ print('lr pow factor: ', args.power_factor)
+ else:
+ pass
+ if args.lars:
+ print('using lars: ', 'True')
+ print('choose lars eta:', args.lars_eta)
+ print("decay epochs:", args.decay_epochs)
+ else:
+ print('using sgd: ', 'True')
+ print('label smoothing:', args.label_smoothing)
+ print('momentum: ', args.momentum)
+ print('weight decay: ', args.weight_decay)
+ print('seed: ', args.seed)
+ print('eval period: ', args.eval_period)
+ print('eval offset: ', args.eval_offset)
+ print('sota target: ', args.sota_target)
+ print('skip ckpt: ', args.skip_checkpoint)
+ print('disable broadcast: ', args.disable_broadcast_buffers)
+ print('large 1st bucket: ', args.large_first_bucket)
+ print('use grad as bucket view: ', args.use_gradient_as_bucket_view)
+ print('[info] --------------------------------------------------------')
if args.xpu is not None and args.gpu is not None:
print('You need to choose running on NV GPU or XPU.')
@@ -215,11 +283,7 @@ def main():
'you need to pass -e and --xpu [dev_id] in your command')
sys.exit()
- if args.int8 and args.channels_last:
- print('For int8 quantization, channels last is not supported for now')
- sys.exit()
-
- if args.tensorboard is not None:
+ if args.converge is not None:
from torch.utils.tensorboard import SummaryWriter
global writer
writer = SummaryWriter(log_dir='./tensorboard_log')
@@ -230,6 +294,8 @@ def main():
print('Setting the seed: ', args.seed)
random.seed(args.seed)
torch.manual_seed(args.seed)
+ if args.xpu is not None:
+ torch.xpu.manual_seed(args.seed)
if torch.cuda.is_available():
cudnn.deterministic = True
warnings.warn('You have chosen to seed training. '
@@ -424,6 +490,13 @@ def main_worker(ngpus_per_node, args):
optimizer = torch.optim.SGD(model.parameters(), lr=args.lr,
momentum=args.momentum, weight_decay=args.weight_decay)
+ if args.lars:
+ eeta = args.lars_eta
+ print('using lars, eeta = ', eeta)
+ optimizer = torch.xpu.optim.Lars(model.parameters(), lr=args.lr,
+ momentum=args.momentum, weight_decay=args.weight_decay,
+ eeta=eeta)
+
# TODO: when change the oob of auto channels last function, here need change
using_block_layout = os.environ.get("IPEX_XPU_ONEDNN_LAYOUT", "OFF").upper() in ["1", "Y", "ON", "YES", "TRUE"]
if using_block_layout:
@@ -460,7 +533,8 @@ def main_worker(ngpus_per_node, args):
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.xpu], broadcast_buffers=False if args.disable_broadcast_buffers else True, bucket_cap_mb=args.bucket_cap, gradient_as_bucket_view=args.use_gradient_as_bucket_view)
"""Sets the learning rate to the initial LR decayed by 10 every configured epochs"""
- scheduler = StepLR(optimizer, step_size=args.step_size, gamma=0.1)
+ scheduler = StepLR(optimizer=optimizer, step_size=args.step_size, gamma=args.step_gamma)
+
if not args.evaluate:
print('Using StepLR for training, step size ', args.step_size)
@@ -481,7 +555,7 @@ def main_worker(ngpus_per_node, args):
checkpoint = torch.load(args.resume, map_location=args.xpu)
args.start_epoch = checkpoint['epoch']
# keep best_acc1 on cpu for comparing acc after validation
- best_acc1 = checkpoint['best_acc1'].cpu()
+ best_acc1 = checkpoint['best_acc1']
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
scheduler.load_state_dict(checkpoint['scheduler'])
@@ -492,14 +566,14 @@ def main_worker(ngpus_per_node, args):
cudnn.benchmark = True
# Data loading code
- #traindir = os.path.join(args.data, 'train')
+ traindir = os.path.join(args.data, 'train')
valdir = os.path.join(args.data, 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
if args.dummy:
print("Dummy data is used!")
- #train_dataset = datasets.FakeData(1281167, (3, 224, 224), 1000, transforms.ToTensor())
+ train_dataset = datasets.FakeData(1281167, (3, 224, 224), 1000, transforms.ToTensor())
val_dataset_size = args.num_iterations * args.batch_size if (args.dummy and args.num_iterations) else 50000
val_dataset = datasets.FakeData(val_dataset_size, (3, 224, 224), 1000, transforms.ToTensor())
else:
@@ -525,7 +599,7 @@ def main_worker(ngpus_per_node, args):
]))
if args.distributed:
- train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
+ #train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset, shuffle=False, drop_last=True)
else:
train_sampler = None
@@ -553,7 +627,7 @@ def main_worker(ngpus_per_node, args):
# calibration dataloader
val_loader_calib = torch.utils.data.DataLoader(
val_dataset, batch_size=args.calib_bs, shuffle=False,
- num_workers=args.workers, pin_memory=True)
+ num_workers=args.workers, pin_memory=True, pin_memory_device="xpu")
# do calibration and return quant model
if args.load:
@@ -564,7 +638,7 @@ def main_worker(ngpus_per_node, args):
torch.jit.save(model_calib, args.save)
val_loader_inf = torch.utils.data.DataLoader(
val_dataset, batch_size=args.batch_size, shuffle=False,
- num_workers=args.workers, pin_memory=True)
+ num_workers=args.workers, pin_memory=True, pin_memory_device="xpu")
print('doing int8 inference')
validate_quantization(val_loader_inf, model_calib, criterion, profiling, args)
@@ -576,42 +650,54 @@ def main_worker(ngpus_per_node, args):
global_start_time = time.time()
# warm up for convergence
- if args.tensorboard and not args.resume:
- warm_up_epoch = 5
+ if args.converge and not args.resume and args.warm_up_epoch > 0:
+ warm_up_epoch = args.warm_up_epoch
warm_up_portion = args.lr / float(warm_up_epoch)
for epoch in range(0, warm_up_epoch):
- optimizer.param_groups[0]['lr'] = (epoch + 1) * warm_up_portion
- train(train_loader, model, criterion, optimizer, epoch, profiling, use_autocast, args)
+ if args.lars == False:
+ optimizer.param_groups[0]['lr'] = (epoch + 1) * warm_up_portion
+ train(train_loader, model, criterion, optimizer, epoch, profiling, use_autocast, args, mode='warming')
print('Warmup [', (epoch + 1), '][', warm_up_epoch, '] lr = ', optimizer.param_groups[0]['lr'])
- # recover the initial lr
- optimizer.param_groups[0]['lr'] = args.lr
+ last_acc = best_acc1
for epoch in range(args.start_epoch, args.epochs):
epoch_start_time = time.time()
+
+ global global_lr
+ global_lr = optimizer.param_groups[0]['lr']
+
if not args.distributed or (args.distributed and args.rank == 0):
print('[info] Epoch[', epoch, '] start time = ', time.asctime(time.localtime(epoch_start_time)))
if args.distributed:
train_sampler.set_epoch(epoch)
+ if epoch == args.last_step_boundary and args.lr_scheduler == 'step':
+ optimizer.param_groups[0]['lr'] *= args.step_gamma
+
if not args.distributed or (args.distributed and args.rank == 0):
print('[info] Epoch[', epoch, '] lr = ', optimizer.param_groups[0]['lr'])
# train for one epoch
- train(train_loader, model, criterion, optimizer, epoch, profiling, use_autocast, args)
+ train(train_loader, model, criterion, optimizer, epoch, profiling, use_autocast, args, mode='training')
# evaluate on validation set
- acc1 = validate(val_loader, model, criterion, epoch, profiling, use_autocast, args)
+ acc1 = last_acc
+ if (epoch >= args.eval_start_epoch) and (epoch % args.eval_period == args.eval_offset):
+ print('epoch: ', epoch, ' is doing evaluation')
+ acc1 = validate(val_loader, model, criterion, epoch, profiling, use_autocast, args)
+ last_acc = acc1
# update the LR
- scheduler.step()
+ if args.lars == False:
+ scheduler.step()
# remember best acc@1 and save checkpoint
is_best = acc1 > best_acc1
best_acc1 = max(acc1, best_acc1)
- if not args.multiprocessing_distributed or (args.multiprocessing_distributed
- and args.rank % ngpus_per_node == 0):
+ if not args.skip_checkpoint and \
+ (not args.multiprocessing_distributed or (args.multiprocessing_distributed and args.rank % ngpus_per_node == 0)):
save_checkpoint(state={
'epoch': epoch + 1,
'arch': args.arch,
@@ -627,16 +713,25 @@ def main_worker(ngpus_per_node, args):
print('[info] Epoch[', epoch, '] end time = ', time.asctime(time.localtime(epoch_end_time)))
print('[info] Epoch[', epoch, '] consume time = ', ((epoch_end_time - epoch_start_time) / 3600.0), ' hours')
+ if converged:
+ break
+
if not args.distributed or (args.distributed and args.rank == 0):
global_end_time = time.time()
print('[info] Global start time = ', time.asctime(time.localtime(global_start_time)))
print('[info] Global end time = ', time.asctime(time.localtime(global_end_time)))
print('[info] Global consume time = ', ((global_end_time - global_start_time) / (3600.0)), ' hours')
+ if converged:
+ print('[Successful] Reach convergence, final top1 acc: ', final_top1_acc)
+ print('[Successful] Reach convergence, final top5 acc: ', final_top5_acc)
+ else:
+ print('[Failed] Miss convergence')
- if args.tensorboard:
- writer.close()
+ if args.converge and not args.skip_tensorboard:
+ if not args.distributed or (args.distributed and args.rank == 0):
+ writer.close()
-def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autocast, args):
+def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autocast, args, mode='training'):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
@@ -646,6 +741,7 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
len(train_loader),
[batch_time, data_time, losses, top1, top5],
prefix="Epoch: [{}]".format(epoch))
+ global global_num_iter
# switch to train mode
model.train()
@@ -653,8 +749,13 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
# record time
duration_total = 0.0
+ non_blocking = False
+ if args.non_blocking:
+ non_blocking = True
+
data_start = time.time()
for i, (images, target) in enumerate(train_loader):
+ global_num_iter +=1
# measure data loading time
data_time.update(time.time() - data_start)
@@ -662,13 +763,18 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
print('input to channels last')
images = images.to(memory_format=torch.channels_last)
- start_time = time.time()
if args.xpu is not None:
# TODO: later the knieto will be used
with torch.autograd.profiler_legacy.profile(enabled=profiling, use_xpu=True, record_shapes=False) as prof:
- images = images.to(args.xpu)
- target = target.to(args.xpu)
+ try:
+ import memory_check
+ memory_check.display_mem("xpu:0")
+ except:
+ pass
+ start_time = time.time()
+ images = images.to(args.xpu, non_blocking=non_blocking)
+ target = target.to(args.xpu, non_blocking=non_blocking)
with torch.xpu.amp.autocast(enabled=use_autocast, dtype=torch.bfloat16):
# compute output
@@ -678,17 +784,15 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
# compute gradient and do SGD step
optimizer.zero_grad(set_to_none=True)
loss.backward()
+ if args.lars:
+ # Update LR for Lars
+ MLPerfLRScheduler(optimizer, global_num_iter, len(train_loader), args)
optimizer.step()
# D2H
- if args.xpu is not None:
- loss = loss.cpu()
- output = output.cpu()
- target = target.cpu()
-
- # sync for time measurement on XPU
- if args.xpu is not None:
- torch.xpu.synchronize(args.xpu)
+ loss = loss.cpu()
+ output = output.cpu()
+ target = target.cpu()
if profiling:
profile_name = 'fp32'
@@ -701,6 +805,7 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
torch.save(prof.key_averages().table(sort_by="self_xpu_time_total"), './profiling.' + profile_name + '.train.pt')
torch.save(prof.table(sort_by="id", row_limit=100000), './profiling.' + profile_name + '.train.detailed.pt')
else:
+ start_time = time.time()
activities = None
prof_sort = None
if profiling:
@@ -712,8 +817,8 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
with torch.profiler.profile(activities=activities, record_shapes=False) as prof:
if args.gpu is not None:
- images = images.cuda(args.gpu, non_blocking=True)
- target = target.cuda(args.gpu, non_blocking=True)
+ images = images.cuda(args.gpu, non_blocking=non_blocking)
+ target = target.cuda(args.gpu, non_blocking=non_blocking)
# compute output
output = model(images)
@@ -758,14 +863,22 @@ def train(train_loader, model, criterion, optimizer, epoch, profiling, use_autoc
elif args.num_iterations == 0 and i == len(train_loader) - 1:
print('Training performance: batch size:%d, throughput:%.2f image/sec'
% (args.batch_size, (args.batch_size / (duration_total / (len(train_loader) - 4)))))
- if args.tensorboard is None:
+ if args.converge is None:
sys.exit(0)
- if args.tensorboard:
- draw_tensorboard(epoch, losses.avg, top1.avg, top5.avg, 'train', args)
+ if args.converge and not args.skip_tensorboard and mode == 'training':
+ global tensorboard_data
+ tensorboard_data['epoch'] = epoch
+ tensorboard_data['train']['loss'] = losses.avg
+ tensorboard_data['train']['top1'] = top1.avg
+ tensorboard_data['train']['top5'] = top5.avg
def validate(val_loader, model, criterion, epoch, profiling, use_autocast, args):
+ non_blocking = False
+ if args.non_blocking:
+ non_blocking = True
+
def run_validate(loader, model, autocast_dtype, base_progress=0):
# record time
@@ -779,11 +892,16 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
images = images.to(memory_format=torch.channels_last)
print('images convert to channels last')
- start_time = time.time()
if args.xpu:
with torch.autograd.profiler_legacy.profile(enabled=profiling, use_xpu=True, record_shapes=False) as prof:
- images = images.to(args.xpu)
+ try:
+ import memory_check
+ memory_check.display_mem("xpu:0")
+ except:
+ pass
+ start_time = time.time()
+ images = images.to(args.xpu, non_blocking=non_blocking)
if args.jit_trace:
# compute output
@@ -794,7 +912,7 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
output = model(images)
# sync for time measurement
- if args.xpu is not None:
+ if not args.converge:
torch.xpu.synchronize(args.xpu)
if profiling:
@@ -806,6 +924,7 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
torch.save(prof.key_averages().table(sort_by="self_xpu_time_total"), './profiling.' + profile_name + '.inf.pt')
torch.save(prof.table(sort_by="id", row_limit=100000), './profiling.' + profile_name + '.inf.detailed.pt')
else:
+ start_time = time.time()
activities = None
prof_sort = None
if profiling:
@@ -817,7 +936,7 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
with torch.profiler.profile(activities=activities, record_shapes=False) as prof:
if args.gpu is not None:
- images = images.cuda(args.gpu, non_blocking=True)
+ images = images.cuda(args.gpu, non_blocking=non_blocking)
# compute output
output = model(images)
@@ -848,7 +967,7 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
progress.display(i + 1)
# exclude first iteration for calculating througput
- if i >= 1 and not (args.num_iterations == 0 and i == len(val_loader) - 1):
+ if i >= 1 and not (args.num_iterations == 0 and i == len(val_loader) - 1):
duration_total += duration_eval
if i == (args.num_iterations - 1) and args.num_iterations >= 2:
@@ -856,9 +975,20 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
% (args.batch_size, (args.batch_size / (duration_total / (args.num_iterations - 1))), top1.avg, top5.avg))
sys.exit(0)
elif args.num_iterations == 0 and i == len(val_loader) - 1:
+ if args.converge and args.distributed:
+ top1.all_reduce()
+ top5.all_reduce()
print('Evalution performance: batch size:%d, throughput:%.2f image/sec, Acc@1:%.2f, Acc@5:%.2f'
% (args.batch_size, (args.batch_size / (duration_total / (len(val_loader) - 2))), top1.avg, top5.avg))
- if args.tensorboard is None:
+ if args.converge:
+ global final_top1_acc
+ global final_top5_acc
+ global converged
+ final_top1_acc = top1.avg
+ final_top5_acc = top5.avg
+ if final_top1_acc >= args.sota_target:
+ converged = True
+ else:
sys.exit(0)
batch_time = AverageMeter('Time', ':6.3f', Summary.NONE)
@@ -894,10 +1024,17 @@ def run_validate(loader, model, autocast_dtype, base_progress=0):
progress.display_summary()
- if args.tensorboard:
- draw_tensorboard(epoch, None, top1.avg, top5.avg, 'val', args)
+ if args.converge and not args.skip_tensorboard:
+ global tensorboard_data
+ tensorboard_data['eval']['loss'] = losses.avg
+ tensorboard_data['eval']['top1'] = final_top1_acc
+ tensorboard_data['eval']['top5'] = final_top5_acc
+ draw_tensorboard(args)
- return top1.avg
+ if args.distributed:
+ return final_top1_acc
+ else:
+ return top1.avg
def validate_quantization(val_loader, model, criterion, profiling, args):
batch_time = AverageMeter('Time', ':6.3f', Summary.NONE)
@@ -915,16 +1052,26 @@ def validate_quantization(val_loader, model, criterion, profiling, args):
# record time
duration_total = 0.0
+ non_blocking = False
+ if args.non_blocking:
+ non_blocking = True
+
with torch.inference_mode():
for i, (images, target) in enumerate(val_loader):
if args.xpu is not None and args.benchmark == 1:
- images = images.to(args.xpu)
+ images = images.to(args.xpu, non_blocking=non_blocking)
- start = time.time()
with torch.autograd.profiler_legacy.profile(enabled=profiling, use_xpu=True, record_shapes=False) as prof:
-
+ try:
+ import memory_check
+ memory_check.display_mem("xpu:0")
+ except:
+ pass
+ start = time.time()
if args.xpu is not None and args.benchmark == 0:
- images = images.to(args.xpu)
+ images = images.to(args.xpu, non_blocking=non_blocking)
+ if args.channels_last:
+ images = images.to(memory_format=torch.channels_last)
# compute output
output = model(images)
@@ -1102,15 +1249,38 @@ def accuracy(output, target, topk=(1,)):
res.append(correct_k.mul_(100.0 / batch_size))
return res
-def draw_tensorboard(num_epoch, avg_loss, avg_acc1, avg_acc5, mode, args):
- if mode == 'train':
- writer.add_scalar('training: learning rate', args.lr, num_epoch)
- writer.add_scalar('training: loss', avg_loss, num_epoch)
- writer.add_scalar('training: top1 acc', avg_acc1, num_epoch)
- writer.add_scalar('training: top5 acc', avg_acc5, num_epoch)
+def MLPerfLRScheduler(optimizer, step, iteration, args):
+ global global_lr
+ warmup_iter = args.warm_up_epoch * iteration
+ decay_steps = args.decay_epochs * iteration
+ power = 2
+ if step <= warmup_iter:
+ lr_rate = args.lr * (step / warmup_iter)
else:
- writer.add_scalar('val: top1 acc', avg_acc1, num_epoch)
- writer.add_scalar('val: top5 acc', avg_acc5, num_epoch)
+ lr_step = min((step - warmup_iter), decay_steps)
+ lr_rate = ((args.lr - args.end_lr) * (1-(lr_step/decay_steps)) ** power) + args.end_lr
+ global_lr = lr_rate
+ optimizer.param_groups[0]['lr'] = global_lr
+
+def draw_tensorboard(args):
+ global tensorboard_data
+ global global_lr
+ if not args.distributed or (args.distributed and args.rank == 0):
+ epoch = tensorboard_data['epoch']
+
+ train_loss = tensorboard_data['train']['loss']
+ eval_loss = tensorboard_data['eval']['loss']
+
+ train_top1 = tensorboard_data['train']['top1']
+ eval_top1 = tensorboard_data['eval']['top1']
+
+ train_top5 = tensorboard_data['train']['top5']
+ eval_top5 = tensorboard_data['eval']['top5']
+
+ writer.add_scalars('top1 acc', {'train acc': train_top1, 'eval acc': eval_top1}, epoch)
+ writer.add_scalars('top5 acc', {'train acc': train_top5, 'eval acc': eval_top5}, epoch)
+ writer.add_scalar('learning rate', global_lr, epoch)
+ writer.add_scalars('loss value', {'train loss': train_loss, 'eval loss': eval_loss}, epoch)
if __name__ == '__main__':
main()
diff --git a/models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py b/models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py
new file mode 100644
index 000000000..d885922a2
--- /dev/null
+++ b/models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py
@@ -0,0 +1,106 @@
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+import numpy as np
+import argparse
+import time
+import tensorflow as tf
+import tensorflow.keras.applications as tka
+from tensorflow.keras.preprocessing import image
+from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
+
+@tf.function
+def tf_function_model_predict(model, x_input):
+ return model(x_input, training = False)
+
+def main(args):
+ from tensorflow.keras import mixed_precision
+ policy = mixed_precision.Policy('mixed_float16')
+ #policy = mixed_precision.Policy('mixed_bfloat16')
+ mixed_precision.set_global_policy(policy)
+
+ img_size = None
+ if args.model == "EfficientNetB0":
+ img_size = (224, 224)
+ elif args.model == "EfficientNetB3":
+ img_size = (300, 300)
+ elif args.model == "EfficientNetB4":
+ img_size = (380, 380)
+ else:
+ assert (False and "error model name")
+
+ print("load data ......")
+ img_path = args.image_file
+ img = image.load_img(img_path, target_size=img_size)
+ x = image.img_to_array(img)
+ x = np.expand_dims(x, axis=0)
+ x = preprocess_input(x)#.astype(np.float32)
+
+ rep = np.array([args.batch_size,], dtype = np.int32)
+ x = tf.repeat(x, rep, axis = 0)
+
+ print("input shape", x.shape)
+
+ model = getattr(tka, args.model)(weights='imagenet')
+ model.trainable = False
+ print("Creating model finished.")
+
+ total_iter = 50
+ warmup_iter = 20
+ total_time = 0
+ total_count = 0
+ preds = None
+ for step in range(total_iter):
+ start = time.time()
+ #preds = model.predict(x)
+ #preds = model(x, training=False)
+ preds = tf_function_model_predict(model, x)
+ end = time.time()
+ if step >= warmup_iter:
+ total_time += (end - start)
+ total_count += 1
+ """
+ # resnet50 result
+ # decode the results into a list of tuples (class, description, probability)
+ # (one such list for each sample in the batch)
+ print('Predicted:', decode_predictions(preds, top=3)[0])
+ # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)
+ """
+ print("Batchsize is", args.batch_size)
+ avg_time = total_time / total_count
+ print("Avg time:", avg_time, "s.")
+ print("Throughput:", args.batch_size/avg_time, "img/s.")
+
+def parse_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-m", "--model", dest="model", required=True, help="model name")
+ #parser.add_argument("-d", "--dtype", dest="dtype", required=True, help="data type")
+ #parser.add_argument("-l", "--layout", dest="layout", required=True, help="data layout")
+ parser.add_argument("-b", "--batch_size", dest="batch_size", type=int, required=True, help="batch size")
+ parser.add_argument("-i", "--image_file", dest="image_file", required=True, help="input ImageNet image")
+
+ args = parser.parse_args()
+
+ return args
+
+if __name__ == "__main__":
+ args = parse_args()
+ main(args)
diff --git a/models/image_recognition/tensorflow/resnet50v1_5/inference/gpu/int8/eval_image_classifier_inference.py b/models/image_recognition/tensorflow/resnet50v1_5/inference/gpu/int8/eval_image_classifier_inference.py
index 81ce52061..0958824df 100644
--- a/models/image_recognition/tensorflow/resnet50v1_5/inference/gpu/int8/eval_image_classifier_inference.py
+++ b/models/image_recognition/tensorflow/resnet50v1_5/inference/gpu/int8/eval_image_classifier_inference.py
@@ -24,6 +24,7 @@
import tensorflow as tf
from tensorflow.python.tools.optimize_for_inference_lib import optimize_for_inference
+from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.framework import dtypes
import datasets
@@ -107,7 +108,10 @@ def __init__(self):
arg_parser.add_argument("--benchmark",
help='Run in benchmark mode.',
dest='benchmark', action='store_true')
-
+ arg_parser.add_argument("--onednn-graph",
+ dest='onednn_graph',
+ help='enable OneDNN Graph',
+ action='store_true')
self.args = arg_parser.parse_args()
# validate the arguements
self.validate_args()
@@ -147,6 +151,8 @@ def run(self):
infer_config = tf.compat.v1.ConfigProto()
infer_config.intra_op_parallelism_threads = self.args.num_intra_threads
infer_config.inter_op_parallelism_threads = self.args.num_inter_threads
+ if self.args.onednn_graph:
+ infer_config.graph_options.rewrite_options.constant_folding = rewriter_config_pb2.RewriterConfig.OFF
infer_config.use_per_session_threads = 1
data_graph = tf.Graph()
diff --git a/models/image_segmentation/tensorflow/maskrcnn/inference/gpu/EnableInference.patch b/models/image_segmentation/tensorflow/maskrcnn/inference/gpu/EnableInference.patch
new file mode 100644
index 000000000..7c95b6625
--- /dev/null
+++ b/models/image_segmentation/tensorflow/maskrcnn/inference/gpu/EnableInference.patch
@@ -0,0 +1,158 @@
+diff --git a/TensorFlow2/Segmentation/MaskRCNN/main.py b/TensorFlow2/Segmentation/MaskRCNN/main.py
+index 53b59d6e..859396a6 100644
+--- a/TensorFlow2/Segmentation/MaskRCNN/main.py
++++ b/TensorFlow2/Segmentation/MaskRCNN/main.py
+@@ -17,12 +17,12 @@ import os
+ from argparse import Namespace
+
+ from mrcnn_tf2.runtime.run import run_training, run_inference, run_evaluation
+-from mrcnn_tf2.utils.dllogger import LoggingBackend
++# from mrcnn_tf2.utils.dllogger import LoggingBackend
+
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
+ os.environ["TF_CPP_VMODULE"] = 'non_max_suppression_op=0,generate_box_proposals_op=0,executor=0'
+
+-import dllogger
++# import dllogger
+
+ from mrcnn_tf2.arguments import PARSER
+ from mrcnn_tf2.config import CONFIG
+@@ -48,11 +48,14 @@ def main():
+ logging.getLogger('tensorflow').handlers.clear()
+
+ # setup dllogger
++ '''
+ dllogger.init(backends=[
+ dllogger.JSONStreamBackend(verbosity=dllogger.Verbosity.VERBOSE, filename=params.log_file),
+ LoggingBackend(verbosity=dllogger.Verbosity.VERBOSE)
+ ])
+ dllogger.log(step='PARAMETER', data=vars(params))
++ '''
++ print(vars(params), flush=True)
+
+ # setup dataset
+ dataset = Dataset(params)
+diff --git a/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/callbacks.py b/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/callbacks.py
+index 4e7b56c9..8ffbcdc5 100644
+--- a/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/callbacks.py
++++ b/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/callbacks.py
+@@ -23,7 +23,7 @@ class DLLoggerMetricsCallback(KerasCallback):
+ Keras callback that saves metrics using DLLogger.
+ """
+
+- def __init__(self, dllogger, log_every=10, log_learning_rate=False):
++ def __init__(self, log_every=10, log_learning_rate=False):
+ """
+ Args:
+ dllogger (DLLogger): DLLogger instance.
+@@ -32,7 +32,7 @@ class DLLoggerMetricsCallback(KerasCallback):
+ Cannot be used with AMP enabled as the used hack fails with AMP.
+ """
+ super().__init__()
+- self._dllogger = dllogger
++ # self._dllogger = dllogger
+ self._log_every = log_every
+ self._log_learning_rate = log_learning_rate
+
+@@ -68,7 +68,8 @@ class DLLoggerMetricsCallback(KerasCallback):
+ if not logs:
+ return
+
+- self._dllogger.log(step=step, data=logs)
++ # self._dllogger.log(step=step, data=logs)
++ print(step, {k: v for k, v in logs.items()}, flush=True)
+
+
+ class DLLoggerPerfCallback(KerasCallback):
+@@ -76,9 +77,9 @@ class DLLoggerPerfCallback(KerasCallback):
+ Keras callback that measures performance and logs it using DLLogger.
+ """
+
+- def __init__(self, dllogger, batch_sizes, warmup_steps=0, log_every=None):
++ def __init__(self, batch_sizes, warmup_steps=0, log_every=None):
+ super().__init__()
+- self._dllogger = dllogger
++ # self._dllogger = dllogger
+ self._batch_sizes = batch_sizes
+ self._warmup_steps = warmup_steps
+ self._log_every = log_every
+@@ -124,6 +125,17 @@ class DLLoggerPerfCallback(KerasCallback):
+
+ def _log_perf(self, deltas, mode, step=tuple()):
+ deltas = np.array(deltas)
++ data={
++ f'{mode}_throughput': self._calculate_throughput(deltas, self._batch_sizes[mode]),
++ f'{mode}_latency': self._calculate_latency(deltas),
++ f'{mode}_latency_90': self._calculate_latency_confidence(deltas, 90.0),
++ f'{mode}_latency_95': self._calculate_latency_confidence(deltas, 95.0),
++ f'{mode}_latency_99': self._calculate_latency_confidence(deltas, 99.0),
++ f'{mode}_time': self._calculate_total_time(self._start_timestamps[mode], time.time())
++ }
++ print(step, data, flush=True)
++
++ '''
+ self._dllogger.log(
+ step=step,
+ data={
+@@ -135,6 +147,7 @@ class DLLoggerPerfCallback(KerasCallback):
+ f'{mode}_time': self._calculate_total_time(self._start_timestamps[mode], time.time())
+ }
+ )
++ '''
+
+ @staticmethod
+ def _calculate_throughput(deltas, batch_size):
+diff --git a/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/run.py b/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/run.py
+index d7b001b3..2fecc57c 100644
+--- a/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/run.py
++++ b/TensorFlow2/Segmentation/MaskRCNN/mrcnn_tf2/runtime/run.py
+@@ -2,7 +2,7 @@ import logging
+ import os
+
+ import tensorflow as tf
+-import dllogger
++# import dllogger
+
+ from mrcnn_tf2.model.mask_rcnn import MaskRCNN
+ from mrcnn_tf2.runtime.callbacks import DLLoggerMetricsCallback, DLLoggerPerfCallback, PretrainedWeightsLoadingCallback
+@@ -80,10 +80,14 @@ def run_evaluation(dataset, params):
+ include_mask=params.include_mask
+ )
+
++ '''
+ dllogger.log(
+ step=tuple(),
+ data={k: float(v) for k, v in eval_results.items()}
+ )
++ '''
++
++ print(tuple(), {k: float(v) for k, v in eval_results.items()}, flush=True)
+
+
+ def run_inference(dataset, params):
+@@ -112,8 +116,8 @@ def setup(params):
+ logging.info('XLA is activated')
+
+ if params.amp:
+- policy = tf.keras.mixed_precision.experimental.Policy("mixed_float16", loss_scale="dynamic")
+- tf.keras.mixed_precision.experimental.set_policy(policy)
++ policy = tf.keras.mixed_precision.Policy("mixed_float16")
++ tf.keras.mixed_precision.set_global_policy(policy)
+ logging.info('AMP is activated')
+
+
+@@ -143,12 +147,12 @@ def create_model(params):
+
+ def create_callbacks(params):
+ yield DLLoggerMetricsCallback(
+- dllogger=dllogger,
++ # dllogger=dllogger,
+ log_every=params.log_every
+ )
+
+ yield DLLoggerPerfCallback(
+- dllogger=dllogger,
++ # dllogger=dllogger,
+ batch_sizes={
+ 'train': params.train_batch_size * getattr(params, 'replicas', 1),
+ 'test': params.eval_batch_size * getattr(params, 'replicas', 1),
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/detect.py b/models/object_detection/pytorch/yolov5/inference/gpu/detect.py
new file mode 100644
index 000000000..ca2d486b5
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/detect.py
@@ -0,0 +1,370 @@
+
+# Copyright (c) 2023 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 IS A GENERATED DOCKERFILE.
+#
+# This file was assembled from multiple pieces, whose use is documented
+# throughout. Please refer to the TensorFlow dockerfiles documentation
+# for more information.
+
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Run inference on images, videos, directories, streams, etc.
+
+Usage - sources:
+ $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam
+ img.jpg # image
+ vid.mp4 # video
+ path/ # directory
+ 'path/*.jpg' # glob
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
+
+Usage - formats:
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
+ yolov5s.torchscript # TorchScript
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
+ yolov5s.xml # OpenVINO
+ yolov5s.engine # TensorRT
+ yolov5s.mlmodel # CoreML (macOS-only)
+ yolov5s_saved_model # TensorFlow SavedModel
+ yolov5s.pb # TensorFlow GraphDef
+ yolov5s.tflite # TensorFlow Lite
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
+"""
+
+import argparse
+import os
+import platform
+import sys
+import time
+from pathlib import Path
+
+import torch
+import intel_extension_for_pytorch
+import torch.backends.cudnn as cudnn
+from torch.jit._recursive import wrap_cpp_module
+
+FILE = Path(__file__).resolve()
+ROOT = FILE.parents[0] # YOLOv5 root directory
+if str(ROOT) not in sys.path:
+ sys.path.append(str(ROOT)) # add ROOT to PATH
+ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
+
+from models.common import DetectMultiBackend
+from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
+from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
+ increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
+from utils.plots import Annotator, colors, save_one_box
+from utils.torch_utils import select_device, smart_inference_mode
+
+
+@smart_inference_mode()
+def run(
+ weights=ROOT / 'yolov5m.pt', # model.pt path(s)
+ source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
+ imgsz=(640, 640), # inference size (height, width)
+ conf_thres=0.25, # confidence threshold
+ iou_thres=0.45, # NMS IOU threshold
+ max_det=1000, # maximum detections per image
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
+ view_img=False, # show results
+ save_txt=False, # save results to *.txt
+ save_conf=False, # save confidences in --save-txt labels
+ save_crop=False, # save cropped prediction boxes
+ nosave=False, # do not save images/videos
+ classes=None, # filter by class: --class 0, or --class 0 2 3
+ agnostic_nms=False, # class-agnostic NMS
+ augment=False, # augmented inference
+ visualize=False, # visualize features
+ update=False, # update all models
+ project=ROOT / 'runs/detect', # save results to project/name
+ name='exp', # save results to project/name
+ exist_ok=False, # existing project/name ok, do not increment
+ line_thickness=3, # bounding box thickness (pixels)
+ hide_labels=False, # hide labels
+ hide_conf=False, # hide confidences
+ half=False, # use FP16 half-precision inference
+ dnn=False, # use OpenCV DNN for ONNX inference
+ benchmark=0, # use benchmark mode
+ dummy=0, # use dummy data
+ bs=1, # dummy bs
+ iters=50, # iteration number
+):
+ dtype = "fp32"
+ if half:
+ dtype = "half"
+ source = str(source)
+ save_img = not nosave and not source.endswith('.txt') # save inference images
+ is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
+ is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
+ webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
+ if is_url and is_file:
+ source = check_file(source) # download
+
+ # Directories
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
+
+ # Load model
+ device = select_device(device)
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
+ stride, names, pt = model.stride, model.names, model.pt
+ imgsz = check_img_size(imgsz, s=stride) # check image size
+
+ # Dataloader
+ if webcam:
+ view_img = check_imshow()
+ cudnn.benchmark = True # set True to speed up constant image size inference
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
+ bs = len(dataset) # batch_size
+ else:
+ dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
+
+ if dummy == 0:
+ bs = 1 # batch_size
+
+ model = model.to("xpu")
+ if half:
+ model = model.half()
+
+ jit_img = None
+ for path, im, im0s, vid_cap, s in dataset:
+ im = torch.from_numpy(im).to("xpu")
+ im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
+ im /= 255 # 0 - 255 to 0.0 - 1.0
+ if len(im.shape) == 3:
+ im = im[None] # expand for batch dim
+
+ torch._C._jit_set_profiling_mode(False)
+ torch._C._jit_set_profiling_executor(False)
+
+ if half:
+ datatype = torch.half
+ else:
+ datatype = torch.float
+ with torch.no_grad():
+ with torch.xpu.amp.autocast(enabled=True, dtype=datatype, cache_enabled=False):
+ model = torch.jit.trace(model, im, check_trace=False)
+
+ model = wrap_cpp_module(torch._C._jit_pass_fold_convbn(model._c))
+
+
+ vid_path, vid_writer = [None] * bs, [None] * bs
+
+ profiling = os.environ.get("PROFILE", "OFF").upper() in ["1", "Y", "ON", "YES", "TRUE"]
+
+ # Run inference
+ # model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
+ seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
+ warmup_iters = 3
+ if benchmark == 0:
+ iters = warmup_iters + 1
+ else:
+ if bs == 1:
+ iters = 5000
+ else:
+ iters = 500
+ total = 0
+ acc = 0
+ for iter in range(iters):
+ for path, im, im0s, vid_cap, s in dataset:
+ if dummy == 0:
+ im = torch.from_numpy(im).to(device)
+ im = im.half() if half else im.float() # uint8 to fp16/32
+ im /= 255 # 0 - 255 to 0.0 - 1.0
+ if len(im.shape) == 3:
+ im = im[None] # expand for batch dim
+ else:
+ im = torch.randn(bs, 3, 640, 640)
+ # Inference
+ visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
+ with torch.autograd.profiler_legacy.profile(enabled=profiling, use_xpu=True, record_shapes=False) as prof:
+ start = time.time()
+ im = im.to("xpu")
+ if half:
+ im = im.half()
+ with torch.no_grad():
+ pred = model(im)
+ # NMS
+ pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
+ # D2H
+ pred = [x.to("cpu") for x in pred]
+ torch.xpu.synchronize()
+ end = time.time()
+
+ latency = end - start
+ print("Inference: {:>5} E2E Time: {}".format(iter,latency))
+
+ if iter < warmup_iters:
+ continue
+ else:
+ total += latency
+
+ if profiling and iter==iters-1:
+ title = "/yolov5_inference_"
+ title += dtype + "_"
+ title += "bs" + str(bs) + "_"
+
+ profiling_path = os.getenv('PROFILE_PATH')
+ if not profiling_path:
+ profiling_path = './'
+ torch.save(prof.key_averages().table(sort_by="self_xpu_time_total"), profiling_path + title + 'profiling.pt')
+ torch.save(prof.table(sort_by="id", row_limit=100000), profiling_path + title + 'profiling_detailed.pt')
+ prof.export_chrome_trace(profiling_path + title + 'profiling.json')
+ print(prof.key_averages().table(sort_by="self_xpu_time_total"))
+
+ if benchmark == 0:
+ # Second-stage classifier (optional)
+ # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
+
+ # Process predictions
+ for i, det in enumerate(pred): # per image
+ seen += 1
+ if webcam: # batch_size >= 1
+ p, im0, frame = path[i], im0s[i].copy(), dataset.count
+ s += f'{i}: '
+ else:
+ p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
+
+ p = Path(p) # to Path
+ save_path = str(save_dir / p.name) # im.jpg
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
+ s += '%gx%g ' % im.shape[2:] # print string
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
+ imc = im0.copy() if save_crop else im0 # for save_crop
+ annotator = Annotator(im0, line_width=line_thickness, example=str(names))
+ if len(det):
+ # Rescale boxes from img_size to im0 size
+ det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
+
+ # Print results
+ for c in det[:, -1].unique():
+ n = (det[:, -1] == c).sum() # detections per class
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
+
+ # Write results
+ max_person_conf = 0
+ for *xyxy, conf, cls in reversed(det):
+ if save_txt: # Write to file
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
+ with open(f'{txt_path}.txt', 'a') as f:
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
+
+ if save_img or save_crop or view_img: # Add bbox to image
+ c = int(cls) # integer class
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
+ if label[:6] == "person":
+ max_person_conf = max(max_person_conf, float(label[7:]))
+ annotator.box_label(xyxy, label, color=colors(c, True))
+ if save_crop:
+ save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
+ acc = max_person_conf
+ if dummy == 1:
+ continue
+ # Stream results
+ im0 = annotator.result()
+ if view_img:
+ if platform.system() == 'Linux' and p not in windows:
+ windows.append(p)
+ cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
+ cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
+ cv2.imshow(str(p), im0)
+ cv2.waitKey(1) # 1 millisecond
+
+ # Save results (image with detections)
+ if save_img:
+ if dataset.mode == 'image':
+ cv2.imwrite(save_path, im0)
+ else: # 'video' or 'stream'
+ if vid_path[i] != save_path: # new video
+ vid_path[i] = save_path
+ if isinstance(vid_writer[i], cv2.VideoWriter):
+ vid_writer[i].release() # release previous video writer
+ if vid_cap: # video
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+ else: # stream
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
+ save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
+ vid_writer[i].write(im0)
+
+ # Print results
+ t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
+ if save_txt or save_img:
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
+ if update:
+ strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
+
+ avg_latency = total / (iters - warmup_iters)
+ print("Latency:", avg_latency)
+ print("Throughput:", bs / avg_latency)
+ if benchmark == 0:
+ print("Accuracy:", acc) # Pre-add accuracy output format, accuracy for real data to be enabled
+
+
+def parse_opt():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5m.pt', help='model path(s)')
+ parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
+ parser.add_argument('--view-img', action='store_true', help='show results')
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
+ parser.add_argument('--update', action='store_true', help='update all models')
+ parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
+ parser.add_argument('--name', default='exp', help='save results to project/name')
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
+ parser.add_argument('--benchmark', type=int, default=0, help='benchmark for inference')
+ parser.add_argument('--dummy', type=int, default=0, help='use dummy data')
+ parser.add_argument('--bs', type=int, default=8, help='dummy batch size')
+ parser.add_argument('--iters', type=int, default=500, help='iteration number')
+ opt = parser.parse_args()
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
+ print_args(vars(opt))
+ return opt
+
+
+def main(opt):
+ check_requirements(exclude=('tensorboard', 'thop'))
+ run(**vars(opt))
+
+
+if __name__ == "__main__":
+ opt = parse_opt()
+ main(opt)
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/export.py b/models/object_detection/pytorch/yolov5/inference/gpu/export.py
new file mode 100644
index 000000000..7b398fdc4
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/export.py
@@ -0,0 +1,616 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
+
+Format | `export.py --include` | Model
+--- | --- | ---
+PyTorch | - | yolov5s.pt
+TorchScript | `torchscript` | yolov5s.torchscript
+ONNX | `onnx` | yolov5s.onnx
+OpenVINO | `openvino` | yolov5s_openvino_model/
+TensorRT | `engine` | yolov5s.engine
+CoreML | `coreml` | yolov5s.mlmodel
+TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
+TensorFlow GraphDef | `pb` | yolov5s.pb
+TensorFlow Lite | `tflite` | yolov5s.tflite
+TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
+TensorFlow.js | `tfjs` | yolov5s_web_model/
+
+Requirements:
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
+
+Usage:
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
+
+Inference:
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
+ yolov5s.torchscript # TorchScript
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
+ yolov5s.xml # OpenVINO
+ yolov5s.engine # TensorRT
+ yolov5s.mlmodel # CoreML (macOS-only)
+ yolov5s_saved_model # TensorFlow SavedModel
+ yolov5s.pb # TensorFlow GraphDef
+ yolov5s.tflite # TensorFlow Lite
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
+
+TensorFlow.js:
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
+ $ npm install
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
+ $ npm start
+"""
+
+import argparse
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+import warnings
+from pathlib import Path
+
+import pandas as pd
+import torch
+import yaml
+from torch.utils.mobile_optimizer import optimize_for_mobile
+
+FILE = Path(__file__).resolve()
+ROOT = FILE.parents[0] # YOLOv5 root directory
+if str(ROOT) not in sys.path:
+ sys.path.append(str(ROOT)) # add ROOT to PATH
+if platform.system() != 'Windows':
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
+
+from models.experimental import attempt_load
+from models.yolo import Detect
+from utils.dataloaders import LoadImages
+from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, check_yaml,
+ colorstr, file_size, print_args, url2file)
+from utils.torch_utils import select_device, smart_inference_mode
+
+
+def export_formats():
+ # YOLOv5 export formats
+ x = [
+ ['PyTorch', '-', '.pt', True, True],
+ ['TorchScript', 'torchscript', '.torchscript', True, True],
+ ['ONNX', 'onnx', '.onnx', True, True],
+ ['OpenVINO', 'openvino', '_openvino_model', True, False],
+ ['TensorRT', 'engine', '.engine', False, True],
+ ['CoreML', 'coreml', '.mlmodel', True, False],
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
+ ['TensorFlow GraphDef', 'pb', '.pb', True, True],
+ ['TensorFlow Lite', 'tflite', '.tflite', True, False],
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
+ ['TensorFlow.js', 'tfjs', '_web_model', False, False],]
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
+
+
+def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
+ # YOLOv5 TorchScript model export
+ try:
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
+ f = file.with_suffix('.torchscript')
+
+ ts = torch.jit.trace(model, im, strict=False)
+ d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
+ else:
+ ts.save(str(f), _extra_files=extra_files)
+
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'{prefix} export failure: {e}')
+
+
+def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
+ # YOLOv5 ONNX export
+ try:
+ check_requirements(('onnx',))
+ import onnx
+
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
+ f = file.with_suffix('.onnx')
+
+ torch.onnx.export(
+ model.cpu() if dynamic else model, # --dynamic only compatible with cpu
+ im.cpu() if dynamic else im,
+ f,
+ verbose=False,
+ opset_version=opset,
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
+ do_constant_folding=not train,
+ input_names=['images'],
+ output_names=['output'],
+ dynamic_axes={
+ 'images': {
+ 0: 'batch',
+ 2: 'height',
+ 3: 'width'}, # shape(1,3,640,640)
+ 'output': {
+ 0: 'batch',
+ 1: 'anchors'} # shape(1,25200,85)
+ } if dynamic else None)
+
+ # Checks
+ model_onnx = onnx.load(f) # load onnx model
+ onnx.checker.check_model(model_onnx) # check onnx model
+
+ # Metadata
+ d = {'stride': int(max(model.stride)), 'names': model.names}
+ for k, v in d.items():
+ meta = model_onnx.metadata_props.add()
+ meta.key, meta.value = k, str(v)
+ onnx.save(model_onnx, f)
+
+ # Simplify
+ if simplify:
+ try:
+ cuda = torch.cuda.is_available()
+ check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1'))
+ import onnxsim
+
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
+ model_onnx, check = onnxsim.simplify(model_onnx)
+ assert check, 'assert check failed'
+ onnx.save(model_onnx, f)
+ except Exception as e:
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'{prefix} export failure: {e}')
+
+
+def export_openvino(model, file, half, prefix=colorstr('OpenVINO:')):
+ # YOLOv5 OpenVINO export
+ try:
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
+ import openvino.inference_engine as ie
+
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
+ f = str(file).replace('.pt', f'_openvino_model{os.sep}')
+
+ cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f} --data_type {'FP16' if half else 'FP32'}"
+ subprocess.check_output(cmd.split()) # export
+ with open(Path(f) / file.with_suffix('.yaml').name, 'w') as g:
+ yaml.dump({'stride': int(max(model.stride)), 'names': model.names}, g) # add metadata.yaml
+
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+
+
+def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
+ # YOLOv5 CoreML export
+ try:
+ check_requirements(('coremltools',))
+ import coremltools as ct
+
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
+ f = file.with_suffix('.mlmodel')
+
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
+ bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
+ if bits < 32:
+ if platform.system() == 'Darwin': # quantization only supported on macOS
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
+ else:
+ print(f'{prefix} quantization only supported on macOS, skipping...')
+ ct_model.save(f)
+
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return ct_model, f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+ return None, None
+
+
+def export_engine(model, im, file, train, half, dynamic, simplify, workspace=4, verbose=False):
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
+ prefix = colorstr('TensorRT:')
+ try:
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
+ try:
+ import tensorrt as trt
+ except Exception:
+ if platform.system() == 'Linux':
+ check_requirements(('nvidia-tensorrt',), cmds=('-U --index-url https://pypi.ngc.nvidia.com',))
+ import tensorrt as trt
+
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
+ grid = model.model[-1].anchor_grid
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
+ export_onnx(model, im, file, 12, train, dynamic, simplify) # opset 12
+ model.model[-1].anchor_grid = grid
+ else: # TensorRT >= 8
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
+ export_onnx(model, im, file, 13, train, dynamic, simplify) # opset 13
+ onnx = file.with_suffix('.onnx')
+
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
+ f = file.with_suffix('.engine') # TensorRT engine file
+ logger = trt.Logger(trt.Logger.INFO)
+ if verbose:
+ logger.min_severity = trt.Logger.Severity.VERBOSE
+
+ builder = trt.Builder(logger)
+ config = builder.create_builder_config()
+ config.max_workspace_size = workspace * 1 << 30
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
+
+ flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
+ network = builder.create_network(flag)
+ parser = trt.OnnxParser(network, logger)
+ if not parser.parse_from_file(str(onnx)):
+ raise RuntimeError(f'failed to load ONNX file: {onnx}')
+
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
+ LOGGER.info(f'{prefix} Network Description:')
+ for inp in inputs:
+ LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
+ for out in outputs:
+ LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
+
+ if dynamic:
+ if im.shape[0] <= 1:
+ LOGGER.warning(f"{prefix}WARNING: --dynamic model requires maximum --batch-size argument")
+ profile = builder.create_optimization_profile()
+ for inp in inputs:
+ profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape)
+ config.add_optimization_profile(profile)
+
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine in {f}')
+ if builder.platform_has_fast_fp16 and half:
+ config.set_flag(trt.BuilderFlag.FP16)
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
+ t.write(engine.serialize())
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+
+
+def export_saved_model(model,
+ im,
+ file,
+ dynamic,
+ tf_nms=False,
+ agnostic_nms=False,
+ topk_per_class=100,
+ topk_all=100,
+ iou_thres=0.45,
+ conf_thres=0.25,
+ keras=False,
+ prefix=colorstr('TensorFlow SavedModel:')):
+ # YOLOv5 TensorFlow SavedModel export
+ try:
+ import tensorflow as tf
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
+
+ from models.tf import TFDetect, TFModel
+
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
+ f = str(file).replace('.pt', '_saved_model')
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
+
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
+ keras_model.trainable = False
+ keras_model.summary()
+ if keras:
+ keras_model.save(f, save_format='tf')
+ else:
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
+ m = tf.function(lambda x: keras_model(x)) # full model
+ m = m.get_concrete_function(spec)
+ frozen_func = convert_variables_to_constants_v2(m)
+ tfm = tf.Module()
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
+ tfm.__call__(im)
+ tf.saved_model.save(tfm,
+ f,
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
+ if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return keras_model, f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+ return None, None
+
+
+def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
+ try:
+ import tensorflow as tf
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
+
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
+ f = file.with_suffix('.pb')
+
+ m = tf.function(lambda x: keras_model(x)) # full model
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
+ frozen_func = convert_variables_to_constants_v2(m)
+ frozen_func.graph.as_graph_def()
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
+
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+
+
+def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
+ # YOLOv5 TensorFlow Lite export
+ try:
+ import tensorflow as tf
+
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
+ f = str(file).replace('.pt', '-fp16.tflite')
+
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
+ converter.target_spec.supported_types = [tf.float16]
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
+ if int8:
+ from models.tf import representative_dataset_gen
+ dataset = LoadImages(check_dataset(check_yaml(data))['train'], img_size=imgsz, auto=False)
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
+ converter.target_spec.supported_types = []
+ converter.inference_input_type = tf.uint8 # or tf.int8
+ converter.inference_output_type = tf.uint8 # or tf.int8
+ converter.experimental_new_quantizer = True
+ f = str(file).replace('.pt', '-int8.tflite')
+ if nms or agnostic_nms:
+ converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
+
+ tflite_model = converter.convert()
+ open(f, "wb").write(tflite_model)
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+
+
+def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
+ try:
+ cmd = 'edgetpu_compiler --version'
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
+ if subprocess.run(f'{cmd} >/dev/null', shell=True).returncode != 0:
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
+ for c in (
+ 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
+ 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
+
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
+
+ cmd = f"edgetpu_compiler -s -d -k 10 --out_dir {file.parent} {f_tfl}"
+ subprocess.run(cmd.split(), check=True)
+
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+
+
+def export_tfjs(file, prefix=colorstr('TensorFlow.js:')):
+ # YOLOv5 TensorFlow.js export
+ try:
+ check_requirements(('tensorflowjs',))
+ import re
+
+ import tensorflowjs as tfjs
+
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
+ f = str(file).replace('.pt', '_web_model') # js dir
+ f_pb = file.with_suffix('.pb') # *.pb path
+ f_json = f'{f}/model.json' # *.json path
+
+ cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
+ f'--output_node_names=Identity,Identity_1,Identity_2,Identity_3 {f_pb} {f}'
+ subprocess.run(cmd.split())
+
+ with open(f_json) as j:
+ json = j.read()
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
+ subst = re.sub(
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
+ r'"Identity_1": {"name": "Identity_1"}, '
+ r'"Identity_2": {"name": "Identity_2"}, '
+ r'"Identity_3": {"name": "Identity_3"}}}', json)
+ j.write(subst)
+
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
+ return f
+ except Exception as e:
+ LOGGER.info(f'\n{prefix} export failure: {e}')
+
+
+@smart_inference_mode()
+def run(
+ data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
+ weights=ROOT / 'yolov5s.pt', # weights path
+ imgsz=(640, 640), # image (height, width)
+ batch_size=1, # batch size
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
+ include=('torchscript', 'onnx'), # include formats
+ half=False, # FP16 half-precision export
+ inplace=False, # set YOLOv5 Detect() inplace=True
+ train=False, # model.train() mode
+ keras=False, # use Keras
+ optimize=False, # TorchScript: optimize for mobile
+ int8=False, # CoreML/TF INT8 quantization
+ dynamic=False, # ONNX/TF/TensorRT: dynamic axes
+ simplify=False, # ONNX: simplify model
+ opset=12, # ONNX: opset version
+ verbose=False, # TensorRT: verbose log
+ workspace=4, # TensorRT: workspace size (GB)
+ nms=False, # TF: add NMS to model
+ agnostic_nms=False, # TF: add agnostic NMS to model
+ topk_per_class=100, # TF.js NMS: topk per class to keep
+ topk_all=100, # TF.js NMS: topk for all classes to keep
+ iou_thres=0.45, # TF.js NMS: IoU threshold
+ conf_thres=0.25, # TF.js NMS: confidence threshold
+):
+ t = time.time()
+ include = [x.lower() for x in include] # to lowercase
+ fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
+ flags = [x in include for x in fmts]
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
+
+ # Load PyTorch model
+ device = select_device(device)
+ if half:
+ assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
+ assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
+ model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
+
+ # Checks
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
+ if optimize:
+ assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'
+
+ # Input
+ gs = int(max(model.stride)) # grid size (max stride)
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
+
+ # Update model
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
+ for k, m in model.named_modules():
+ if isinstance(m, Detect):
+ m.inplace = inplace
+ m.onnx_dynamic = dynamic
+ m.export = True
+
+ for _ in range(2):
+ y = model(im) # dry runs
+ if half and not coreml:
+ im, model = im.half(), model.half() # to FP16
+ shape = tuple((y[0] if isinstance(y, tuple) else y).shape) # model output shape
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
+
+ # Exports
+ f = [''] * 10 # exported filenames
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
+ if jit:
+ f[0] = export_torchscript(model, im, file, optimize)
+ if engine: # TensorRT required before ONNX
+ f[1] = export_engine(model, im, file, train, half, dynamic, simplify, workspace, verbose)
+ if onnx or xml: # OpenVINO requires ONNX
+ f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
+ if xml: # OpenVINO
+ f[3] = export_openvino(model, file, half)
+ if coreml:
+ _, f[4] = export_coreml(model, im, file, int8, half)
+
+ # TensorFlow Exports
+ if any((saved_model, pb, tflite, edgetpu, tfjs)):
+ if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
+ check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
+ assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
+ model, f[5] = export_saved_model(model.cpu(),
+ im,
+ file,
+ dynamic,
+ tf_nms=nms or agnostic_nms or tfjs,
+ agnostic_nms=agnostic_nms or tfjs,
+ topk_per_class=topk_per_class,
+ topk_all=topk_all,
+ iou_thres=iou_thres,
+ conf_thres=conf_thres,
+ keras=keras)
+ if pb or tfjs: # pb prerequisite to tfjs
+ f[6] = export_pb(model, file)
+ if tflite or edgetpu:
+ f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
+ if edgetpu:
+ f[8] = export_edgetpu(file)
+ if tfjs:
+ f[9] = export_tfjs(file)
+
+ # Finish
+ f = [str(x) for x in f if x] # filter out '' and None
+ if any(f):
+ h = '--half' if half else '' # --half FP16 inference arg
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
+ f"\nDetect: python detect.py --weights {f[-1]} {h}"
+ f"\nValidate: python val.py --weights {f[-1]} {h}"
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
+ f"\nVisualize: https://netron.app")
+ return f # return list of exported files/dirs
+
+
+def parse_opt():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
+ parser.add_argument('--keras', action='store_true', help='TF: use Keras')
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF/TensorRT: dynamic axes')
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
+ parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
+ parser.add_argument('--include',
+ nargs='+',
+ default=['torchscript'],
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
+ opt = parser.parse_args()
+ print_args(vars(opt))
+ return opt
+
+
+def main(opt):
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
+ run(**vars(opt))
+
+
+if __name__ == "__main__":
+ opt = parse_opt()
+ main(opt)
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/models/__init__.py b/models/object_detection/pytorch/yolov5/inference/gpu/models/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/models/common.py b/models/object_detection/pytorch/yolov5/inference/gpu/models/common.py
new file mode 100644
index 000000000..44192e622
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/models/common.py
@@ -0,0 +1,774 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Common modules
+"""
+
+import json
+import math
+import platform
+import warnings
+from collections import OrderedDict, namedtuple
+from copy import copy
+from pathlib import Path
+
+import cv2
+import numpy as np
+import pandas as pd
+import requests
+import torch
+import torch.nn as nn
+from PIL import Image
+from torch.cuda import amp
+
+from utils.dataloaders import exif_transpose, letterbox
+from utils.general import (LOGGER, ROOT, Profile, check_requirements, check_suffix, check_version, colorstr,
+ increment_path, make_divisible, non_max_suppression, scale_coords, xywh2xyxy, xyxy2xywh,
+ yaml_load)
+from utils.plots import Annotator, colors, save_one_box
+from utils.torch_utils import copy_attr, smart_inference_mode
+
+
+def autopad(k, p=None): # kernel, padding
+ # Pad to 'same'
+ if p is None:
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
+ return p
+
+
+class Conv(nn.Module):
+ # Standard convolution
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
+ super().__init__()
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
+ self.bn = nn.BatchNorm2d(c2)
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
+
+ def forward(self, x):
+ return self.act(self.bn(self.conv(x)))
+
+ def forward_fuse(self, x):
+ return self.act(self.conv(x))
+
+
+class DWConv(Conv):
+ # Depth-wise convolution class
+ def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
+
+
+class DWConvTranspose2d(nn.ConvTranspose2d):
+ # Depth-wise transpose convolution class
+ def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
+ super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
+
+
+class TransformerLayer(nn.Module):
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
+ def __init__(self, c, num_heads):
+ super().__init__()
+ self.q = nn.Linear(c, c, bias=False)
+ self.k = nn.Linear(c, c, bias=False)
+ self.v = nn.Linear(c, c, bias=False)
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
+ self.fc1 = nn.Linear(c, c, bias=False)
+ self.fc2 = nn.Linear(c, c, bias=False)
+
+ def forward(self, x):
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
+ x = self.fc2(self.fc1(x)) + x
+ return x
+
+
+class TransformerBlock(nn.Module):
+ # Vision Transformer https://arxiv.org/abs/2010.11929
+ def __init__(self, c1, c2, num_heads, num_layers):
+ super().__init__()
+ self.conv = None
+ if c1 != c2:
+ self.conv = Conv(c1, c2)
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
+ self.c2 = c2
+
+ def forward(self, x):
+ if self.conv is not None:
+ x = self.conv(x)
+ b, _, w, h = x.shape
+ p = x.flatten(2).permute(2, 0, 1)
+ return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
+
+
+class Bottleneck(nn.Module):
+ # Standard bottleneck
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
+ super().__init__()
+ c_ = int(c2 * e) # hidden channels
+ self.cv1 = Conv(c1, c_, 1, 1)
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
+ self.add = shortcut and c1 == c2
+
+ def forward(self, x):
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
+
+
+class BottleneckCSP(nn.Module):
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
+ super().__init__()
+ c_ = int(c2 * e) # hidden channels
+ self.cv1 = Conv(c1, c_, 1, 1)
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
+ self.act = nn.SiLU()
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
+
+ def forward(self, x):
+ y1 = self.cv3(self.m(self.cv1(x)))
+ y2 = self.cv2(x)
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
+
+
+class CrossConv(nn.Module):
+ # Cross Convolution Downsample
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
+ super().__init__()
+ c_ = int(c2 * e) # hidden channels
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
+ self.add = shortcut and c1 == c2
+
+ def forward(self, x):
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
+
+
+class C3(nn.Module):
+ # CSP Bottleneck with 3 convolutions
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
+ super().__init__()
+ c_ = int(c2 * e) # hidden channels
+ self.cv1 = Conv(c1, c_, 1, 1)
+ self.cv2 = Conv(c1, c_, 1, 1)
+ self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
+
+ def forward(self, x):
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
+
+
+class C3x(C3):
+ # C3 module with cross-convolutions
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
+ super().__init__(c1, c2, n, shortcut, g, e)
+ c_ = int(c2 * e)
+ self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))
+
+
+class C3TR(C3):
+ # C3 module with TransformerBlock()
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
+ super().__init__(c1, c2, n, shortcut, g, e)
+ c_ = int(c2 * e)
+ self.m = TransformerBlock(c_, c_, 4, n)
+
+
+class C3SPP(C3):
+ # C3 module with SPP()
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
+ super().__init__(c1, c2, n, shortcut, g, e)
+ c_ = int(c2 * e)
+ self.m = SPP(c_, c_, k)
+
+
+class C3Ghost(C3):
+ # C3 module with GhostBottleneck()
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
+ super().__init__(c1, c2, n, shortcut, g, e)
+ c_ = int(c2 * e) # hidden channels
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
+
+
+class SPP(nn.Module):
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
+ def __init__(self, c1, c2, k=(5, 9, 13)):
+ super().__init__()
+ c_ = c1 // 2 # hidden channels
+ self.cv1 = Conv(c1, c_, 1, 1)
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
+
+ def forward(self, x):
+ x = self.cv1(x)
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
+
+
+class SPPF(nn.Module):
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
+ super().__init__()
+ c_ = c1 // 2 # hidden channels
+ self.cv1 = Conv(c1, c_, 1, 1)
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
+
+ def forward(self, x):
+ x = self.cv1(x)
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
+ y1 = self.m(x)
+ y2 = self.m(y1)
+ return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
+
+
+class Focus(nn.Module):
+ # Focus wh information into c-space
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
+ super().__init__()
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
+ # self.contract = Contract(gain=2)
+
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
+ return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))
+ # return self.conv(self.contract(x))
+
+
+class GhostConv(nn.Module):
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
+ super().__init__()
+ c_ = c2 // 2 # hidden channels
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
+
+ def forward(self, x):
+ y = self.cv1(x)
+ return torch.cat((y, self.cv2(y)), 1)
+
+
+class GhostBottleneck(nn.Module):
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
+ super().__init__()
+ c_ = c2 // 2
+ self.conv = nn.Sequential(
+ GhostConv(c1, c_, 1, 1), # pw
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,
+ act=False)) if s == 2 else nn.Identity()
+
+ def forward(self, x):
+ return self.conv(x) + self.shortcut(x)
+
+
+class Contract(nn.Module):
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
+ def __init__(self, gain=2):
+ super().__init__()
+ self.gain = gain
+
+ def forward(self, x):
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
+ s = self.gain
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
+
+
+class Expand(nn.Module):
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
+ def __init__(self, gain=2):
+ super().__init__()
+ self.gain = gain
+
+ def forward(self, x):
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
+ s = self.gain
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
+
+
+class Concat(nn.Module):
+ # Concatenate a list of tensors along dimension
+ def __init__(self, dimension=1):
+ super().__init__()
+ self.d = dimension
+
+ def forward(self, x):
+ return torch.cat(x, self.d)
+
+
+class DetectMultiBackend(nn.Module):
+ # YOLOv5 MultiBackend class for python inference on various backends
+ def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):
+ # Usage:
+ # PyTorch: weights = *.pt
+ # TorchScript: *.torchscript
+ # ONNX Runtime: *.onnx
+ # ONNX OpenCV DNN: *.onnx with --dnn
+ # OpenVINO: *.xml
+ # CoreML: *.mlmodel
+ # TensorRT: *.engine
+ # TensorFlow SavedModel: *_saved_model
+ # TensorFlow GraphDef: *.pb
+ # TensorFlow Lite: *.tflite
+ # TensorFlow Edge TPU: *_edgetpu.tflite
+ from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
+
+ super().__init__()
+ w = str(weights[0] if isinstance(weights, list) else weights)
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = self._model_type(w) # get backend
+ w = attempt_download(w) # download if not local
+ fp16 &= pt or jit or onnx or engine # FP16
+ stride = 32 # default stride
+
+ if pt: # PyTorch
+ model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
+ stride = max(int(model.stride.max()), 32) # model stride
+ names = model.module.names if hasattr(model, 'module') else model.names # get class names
+ model.half() if fp16 else model.float()
+ self.model = model # explicitly assign for to(), cpu(), cuda(), half()
+ elif jit: # TorchScript
+ LOGGER.info(f'Loading {w} for TorchScript inference...')
+ extra_files = {'config.txt': ''} # model metadata
+ model = torch.jit.load(w, _extra_files=extra_files)
+ model.half() if fp16 else model.float()
+ if extra_files['config.txt']: # load metadata dict
+ d = json.loads(extra_files['config.txt'],
+ object_hook=lambda d: {int(k) if k.isdigit() else k: v
+ for k, v in d.items()})
+ stride, names = int(d['stride']), d['names']
+ elif dnn: # ONNX OpenCV DNN
+ LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')
+ check_requirements(('opencv-python>=4.5.4',))
+ net = cv2.dnn.readNetFromONNX(w)
+ elif onnx: # ONNX Runtime
+ LOGGER.info(f'Loading {w} for ONNX Runtime inference...')
+ cuda = torch.cuda.is_available() and device.type != 'cpu'
+ check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))
+ import onnxruntime
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
+ session = onnxruntime.InferenceSession(w, providers=providers)
+ meta = session.get_modelmeta().custom_metadata_map # metadata
+ if 'stride' in meta:
+ stride, names = int(meta['stride']), eval(meta['names'])
+ elif xml: # OpenVINO
+ LOGGER.info(f'Loading {w} for OpenVINO inference...')
+ check_requirements(('openvino',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
+ from openvino.runtime import Core, Layout, get_batch
+ ie = Core()
+ if not Path(w).is_file(): # if not *.xml
+ w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir
+ network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin'))
+ if network.get_parameters()[0].get_layout().empty:
+ network.get_parameters()[0].set_layout(Layout("NCHW"))
+ batch_dim = get_batch(network)
+ if batch_dim.is_static:
+ batch_size = batch_dim.get_length()
+ executable_network = ie.compile_model(network, device_name="CPU") # device_name="MYRIAD" for Intel NCS2
+ output_layer = next(iter(executable_network.outputs))
+ meta = Path(w).with_suffix('.yaml')
+ if meta.exists():
+ stride, names = self._load_metadata(meta) # load metadata
+ elif engine: # TensorRT
+ LOGGER.info(f'Loading {w} for TensorRT inference...')
+ import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
+ check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
+ if device.type == 'cpu':
+ device = torch.device('cuda:0')
+ Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))
+ logger = trt.Logger(trt.Logger.INFO)
+ with open(w, 'rb') as f, trt.Runtime(logger) as runtime:
+ model = runtime.deserialize_cuda_engine(f.read())
+ context = model.create_execution_context()
+ bindings = OrderedDict()
+ fp16 = False # default updated below
+ dynamic = False
+ for index in range(model.num_bindings):
+ name = model.get_binding_name(index)
+ dtype = trt.nptype(model.get_binding_dtype(index))
+ if model.binding_is_input(index):
+ if -1 in tuple(model.get_binding_shape(index)): # dynamic
+ dynamic = True
+ context.set_binding_shape(index, tuple(model.get_profile_shape(0, index)[2]))
+ if dtype == np.float16:
+ fp16 = True
+ shape = tuple(context.get_binding_shape(index))
+ im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)
+ bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))
+ binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
+ batch_size = bindings['images'].shape[0] # if dynamic, this is instead max batch size
+ elif coreml: # CoreML
+ LOGGER.info(f'Loading {w} for CoreML inference...')
+ import coremltools as ct
+ model = ct.models.MLModel(w)
+ else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
+ if saved_model: # SavedModel
+ LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')
+ import tensorflow as tf
+ keras = False # assume TF1 saved_model
+ model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
+ elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
+ LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')
+ import tensorflow as tf
+
+ def wrap_frozen_graph(gd, inputs, outputs):
+ x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
+ ge = x.graph.as_graph_element
+ return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
+
+ gd = tf.Graph().as_graph_def() # graph_def
+ with open(w, 'rb') as f:
+ gd.ParseFromString(f.read())
+ frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs="Identity:0")
+ elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
+ try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
+ from tflite_runtime.interpreter import Interpreter, load_delegate
+ except ImportError:
+ import tensorflow as tf
+ Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,
+ if edgetpu: # Edge TPU https://coral.ai/software/#edgetpu-runtime
+ LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')
+ delegate = {
+ 'Linux': 'libedgetpu.so.1',
+ 'Darwin': 'libedgetpu.1.dylib',
+ 'Windows': 'edgetpu.dll'}[platform.system()]
+ interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
+ else: # Lite
+ LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')
+ interpreter = Interpreter(model_path=w) # load TFLite model
+ interpreter.allocate_tensors() # allocate
+ input_details = interpreter.get_input_details() # inputs
+ output_details = interpreter.get_output_details() # outputs
+ elif tfjs:
+ raise NotImplementedError('ERROR: YOLOv5 TF.js inference is not supported')
+ else:
+ raise NotImplementedError(f'ERROR: {w} is not a supported format')
+
+ # class names
+ if 'names' not in locals():
+ names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}
+ if names[0] == 'n01440764' and len(names) == 1000: # ImageNet
+ names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names
+
+ self.__dict__.update(locals()) # assign all variables to self
+
+ def forward(self, im, augment=False, visualize=False, val=False):
+ # YOLOv5 MultiBackend inference
+ b, ch, h, w = im.shape # batch, channel, height, width
+ if self.fp16 and im.dtype != torch.float16:
+ im = im.half() # to FP16
+
+ if self.pt: # PyTorch
+ y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
+ if isinstance(y, tuple):
+ y = y[0]
+ elif self.jit: # TorchScript
+ y = self.model(im)[0]
+ elif self.dnn: # ONNX OpenCV DNN
+ im = im.cpu().numpy() # torch to numpy
+ self.net.setInput(im)
+ y = self.net.forward()
+ elif self.onnx: # ONNX Runtime
+ im = im.cpu().numpy() # torch to numpy
+ y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0]
+ elif self.xml: # OpenVINO
+ im = im.cpu().numpy() # FP32
+ y = self.executable_network([im])[self.output_layer]
+ elif self.engine: # TensorRT
+ if self.dynamic and im.shape != self.bindings['images'].shape:
+ i_in, i_out = (self.model.get_binding_index(x) for x in ('images', 'output'))
+ self.context.set_binding_shape(i_in, im.shape) # reshape if dynamic
+ self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)
+ self.bindings['output'].data.resize_(tuple(self.context.get_binding_shape(i_out)))
+ s = self.bindings['images'].shape
+ assert im.shape == s, f"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}"
+ self.binding_addrs['images'] = int(im.data_ptr())
+ self.context.execute_v2(list(self.binding_addrs.values()))
+ y = self.bindings['output'].data
+ elif self.coreml: # CoreML
+ im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
+ im = Image.fromarray((im[0] * 255).astype('uint8'))
+ # im = im.resize((192, 320), Image.ANTIALIAS)
+ y = self.model.predict({'image': im}) # coordinates are xywh normalized
+ if 'confidence' in y:
+ box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
+ conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
+ y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
+ else:
+ k = 'var_' + str(sorted(int(k.replace('var_', '')) for k in y)[-1]) # output key
+ y = y[k] # output
+ else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
+ im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3)
+ if self.saved_model: # SavedModel
+ y = (self.model(im, training=False) if self.keras else self.model(im)).numpy()
+ elif self.pb: # GraphDef
+ y = self.frozen_func(x=self.tf.constant(im)).numpy()
+ else: # Lite or Edge TPU
+ input, output = self.input_details[0], self.output_details[0]
+ int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
+ if int8:
+ scale, zero_point = input['quantization']
+ im = (im / scale + zero_point).astype(np.uint8) # de-scale
+ self.interpreter.set_tensor(input['index'], im)
+ self.interpreter.invoke()
+ y = self.interpreter.get_tensor(output['index'])
+ if int8:
+ scale, zero_point = output['quantization']
+ y = (y.astype(np.float32) - zero_point) * scale # re-scale
+ y[..., :4] *= [w, h, w, h] # xywh normalized to pixels
+
+ if isinstance(y, np.ndarray):
+ y = torch.tensor(y, device=self.device)
+ return (y, []) if val else y
+
+ def warmup(self, imgsz=(1, 3, 640, 640)):
+ # Warmup model by running inference once
+ warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb
+ if any(warmup_types) and self.device.type != 'cpu':
+ im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
+ for _ in range(2 if self.jit else 1): #
+ self.forward(im) # warmup
+
+ @staticmethod
+ def _model_type(p='path/to/model.pt'):
+ # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx
+ from export import export_formats
+ suffixes = list(export_formats().Suffix) + ['.xml'] # export suffixes
+ check_suffix(p, suffixes) # checks
+ p = Path(p).name # eliminate trailing separators
+ pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes)
+ xml |= xml2 # *_openvino_model or *.xml
+ tflite &= not edgetpu # *.tflite
+ return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs
+
+ @staticmethod
+ def _load_metadata(f='path/to/meta.yaml'):
+ # Load metadata from meta.yaml if it exists
+ d = yaml_load(f)
+ return d['stride'], d['names'] # assign stride, names
+
+
+class AutoShape(nn.Module):
+ # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
+ conf = 0.25 # NMS confidence threshold
+ iou = 0.45 # NMS IoU threshold
+ agnostic = False # NMS class-agnostic
+ multi_label = False # NMS multiple labels per box
+ classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
+ max_det = 1000 # maximum number of detections per image
+ amp = False # Automatic Mixed Precision (AMP) inference
+
+ def __init__(self, model, verbose=True):
+ super().__init__()
+ if verbose:
+ LOGGER.info('Adding AutoShape... ')
+ copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
+ self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
+ self.pt = not self.dmb or model.pt # PyTorch model
+ self.model = model.eval()
+ if self.pt:
+ m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
+ m.inplace = False # Detect.inplace=False for safe multithread inference
+
+ def _apply(self, fn):
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
+ self = super()._apply(fn)
+ if self.pt:
+ m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
+ m.stride = fn(m.stride)
+ m.grid = list(map(fn, m.grid))
+ if isinstance(m.anchor_grid, list):
+ m.anchor_grid = list(map(fn, m.anchor_grid))
+ return self
+
+ @smart_inference_mode()
+ def forward(self, ims, size=640, augment=False, profile=False):
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
+ # file: ims = 'data/images/zidane.jpg' # str or PosixPath
+ # URI: = 'https://ultralytics.com/images/zidane.jpg'
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
+ # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
+ # numpy: = np.zeros((640,1280,3)) # HWC
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
+
+ dt = (Profile(), Profile(), Profile())
+ with dt[0]:
+ p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) # param
+ autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
+ if isinstance(ims, torch.Tensor): # torch
+ with amp.autocast(autocast):
+ return self.model(ims.to(p.device).type_as(p), augment, profile) # inference
+
+ # Pre-process
+ n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of images
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
+ for i, im in enumerate(ims):
+ f = f'image{i}' # filename
+ if isinstance(im, (str, Path)): # filename or uri
+ im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
+ im = np.asarray(exif_transpose(im))
+ elif isinstance(im, Image.Image): # PIL Image
+ im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
+ files.append(Path(f).with_suffix('.jpg').name)
+ if im.shape[0] < 5: # image in CHW
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
+ im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch input
+ s = im.shape[:2] # HWC
+ shape0.append(s) # image shape
+ g = (size / max(s)) # gain
+ shape1.append([y * g for y in s])
+ ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
+ shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)] # inf shape
+ x = [letterbox(im, shape1, auto=False)[0] for im in ims] # pad
+ x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
+
+ with amp.autocast(autocast):
+ # Inference
+ with dt[1]:
+ y = self.model(x, augment, profile) # forward
+
+ # Post-process
+ with dt[2]:
+ y = non_max_suppression(y if self.dmb else y[0],
+ self.conf,
+ self.iou,
+ self.classes,
+ self.agnostic,
+ self.multi_label,
+ max_det=self.max_det) # NMS
+ for i in range(n):
+ scale_coords(shape1, y[i][:, :4], shape0[i])
+
+ return Detections(ims, y, files, dt, self.names, x.shape)
+
+
+class Detections:
+ # YOLOv5 detections class for inference results
+ def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
+ super().__init__()
+ d = pred[0].device # device
+ gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] # normalizations
+ self.ims = ims # list of images as numpy arrays
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
+ self.names = names # class names
+ self.files = files # image filenames
+ self.times = times # profiling times
+ self.xyxy = pred # xyxy pixels
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
+ self.n = len(self.pred) # number of images (batch size)
+ self.t = tuple(x.t / self.n * 1E3 for x in times) # timestamps (ms)
+ self.s = shape # inference BCHW shape
+
+ def display(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
+ crops = []
+ for i, (im, pred) in enumerate(zip(self.ims, self.pred)):
+ s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
+ if pred.shape[0]:
+ for c in pred[:, -1].unique():
+ n = (pred[:, -1] == c).sum() # detections per class
+ s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
+ if show or save or render or crop:
+ annotator = Annotator(im, example=str(self.names))
+ for *box, conf, cls in reversed(pred): # xyxy, confidence, class
+ label = f'{self.names[int(cls)]} {conf:.2f}'
+ if crop:
+ file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
+ crops.append({
+ 'box': box,
+ 'conf': conf,
+ 'cls': cls,
+ 'label': label,
+ 'im': save_one_box(box, im, file=file, save=save)})
+ else: # all others
+ annotator.box_label(box, label if labels else '', color=colors(cls))
+ im = annotator.im
+ else:
+ s += '(no detections)'
+
+ im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
+ if pprint:
+ print(s.rstrip(', '))
+ if show:
+ im.show(self.files[i]) # show
+ if save:
+ f = self.files[i]
+ im.save(save_dir / f) # save
+ if i == self.n - 1:
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
+ if render:
+ self.ims[i] = np.asarray(im)
+ if crop:
+ if save:
+ LOGGER.info(f'Saved results to {save_dir}\n')
+ return crops
+
+ def print(self):
+ self.display(pprint=True) # print results
+ print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)
+
+ def show(self, labels=True):
+ self.display(show=True, labels=labels) # show results
+
+ def save(self, labels=True, save_dir='runs/detect/exp'):
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
+ self.display(save=True, labels=labels, save_dir=save_dir) # save results
+
+ def crop(self, save=True, save_dir='runs/detect/exp'):
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
+ return self.display(crop=True, save=save, save_dir=save_dir) # crop results
+
+ def render(self, labels=True):
+ self.display(render=True, labels=labels) # render results
+ return self.ims
+
+ def pandas(self):
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
+ new = copy(self) # return copy
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
+ return new
+
+ def tolist(self):
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
+ r = range(self.n) # iterable
+ x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
+ # for d in x:
+ # for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
+ # setattr(d, k, getattr(d, k)[0]) # pop out of list
+ return x
+
+ def __len__(self):
+ return self.n # override len(results)
+
+ def __str__(self):
+ self.print() # override print(results)
+ return ''
+
+
+class Classify(nn.Module):
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
+ super().__init__()
+ c_ = 1280 # efficientnet_b0 size
+ self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
+ self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
+ self.drop = nn.Dropout(p=0.0, inplace=True)
+ self.linear = nn.Linear(c_, c2) # to x(b,c2)
+
+ def forward(self, x):
+ if isinstance(x, list):
+ x = torch.cat(x, 1)
+ return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/models/experimental.py b/models/object_detection/pytorch/yolov5/inference/gpu/models/experimental.py
new file mode 100644
index 000000000..02d35b9eb
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/models/experimental.py
@@ -0,0 +1,111 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Experimental modules
+"""
+import math
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from utils.downloads import attempt_download
+
+
+class Sum(nn.Module):
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
+ def __init__(self, n, weight=False): # n: number of inputs
+ super().__init__()
+ self.weight = weight # apply weights boolean
+ self.iter = range(n - 1) # iter object
+ if weight:
+ self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
+
+ def forward(self, x):
+ y = x[0] # no weight
+ if self.weight:
+ w = torch.sigmoid(self.w) * 2
+ for i in self.iter:
+ y = y + x[i + 1] * w[i]
+ else:
+ for i in self.iter:
+ y = y + x[i + 1]
+ return y
+
+
+class MixConv2d(nn.Module):
+ # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
+ super().__init__()
+ n = len(k) # number of convolutions
+ if equal_ch: # equal c_ per group
+ i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
+ c_ = [(i == g).sum() for g in range(n)] # intermediate channels
+ else: # equal weight.numel() per group
+ b = [c2] + [0] * n
+ a = np.eye(n + 1, n, k=-1)
+ a -= np.roll(a, 1, axis=1)
+ a *= np.array(k) ** 2
+ a[0] = 1
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
+
+ self.m = nn.ModuleList([
+ nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
+ self.bn = nn.BatchNorm2d(c2)
+ self.act = nn.SiLU()
+
+ def forward(self, x):
+ return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
+
+
+class Ensemble(nn.ModuleList):
+ # Ensemble of models
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x, augment=False, profile=False, visualize=False):
+ y = [module(x, augment, profile, visualize)[0] for module in self]
+ # y = torch.stack(y).max(0)[0] # max ensemble
+ # y = torch.stack(y).mean(0) # mean ensemble
+ y = torch.cat(y, 1) # nms ensemble
+ return y, None # inference, train output
+
+
+def attempt_load(weights, device=None, inplace=True, fuse=True):
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
+ from models.yolo import Detect, Model
+
+ model = Ensemble()
+ for w in weights if isinstance(weights, list) else [weights]:
+ ckpt = torch.load(attempt_download(w), map_location='cpu') # load
+ ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
+
+ # Model compatibility updates
+ if not hasattr(ckpt, 'stride'):
+ ckpt.stride = torch.tensor([32.])
+ if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):
+ ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
+
+ model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode
+
+ # Module compatibility updates
+ for m in model.modules():
+ t = type(m)
+ if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
+ m.inplace = inplace # torch 1.7.0 compatibility
+ if t is Detect and not isinstance(m.anchor_grid, list):
+ delattr(m, 'anchor_grid')
+ setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
+ elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
+
+ # Return model
+ if len(model) == 1:
+ return model[-1]
+
+ # Return detection ensemble
+ print(f'Ensemble created with {weights}\n')
+ for k in 'names', 'nc', 'yaml':
+ setattr(model, k, getattr(model[0], k))
+ model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
+ assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
+ return model
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/models/yolo.py b/models/object_detection/pytorch/yolov5/inference/gpu/models/yolo.py
new file mode 100644
index 000000000..32a47e959
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/models/yolo.py
@@ -0,0 +1,360 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+YOLO-specific modules
+
+Usage:
+ $ python path/to/models/yolo.py --cfg yolov5s.yaml
+"""
+
+import argparse
+import contextlib
+import os
+import platform
+import sys
+from copy import deepcopy
+from pathlib import Path
+
+FILE = Path(__file__).resolve()
+ROOT = FILE.parents[1] # YOLOv5 root directory
+if str(ROOT) not in sys.path:
+ sys.path.append(str(ROOT)) # add ROOT to PATH
+if platform.system() != 'Windows':
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
+
+from models.common import *
+from models.experimental import *
+from utils.autoanchor import check_anchor_order
+from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
+from utils.plots import feature_visualization
+from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
+ time_sync)
+
+try:
+ import thop # for FLOPs computation
+except ImportError:
+ thop = None
+
+
+class Detect(nn.Module):
+ stride = None # strides computed during build
+ onnx_dynamic = False # ONNX export parameter
+ export = False # export mode
+
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
+ super().__init__()
+ self.nc = nc # number of classes
+ self.no = nc + 5 # number of outputs per anchor
+ self.nl = len(anchors) # number of detection layers
+ self.na = len(anchors[0]) // 2 # number of anchors
+ self.grid = [torch.empty(1)] * self.nl # init grid
+ self.anchor_grid = [torch.empty(1)] * self.nl # init anchor grid
+ self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
+ self.inplace = inplace # use inplace ops (e.g. slice assignment)
+
+ def forward(self, x):
+ z = [] # inference output
+ for i in range(self.nl):
+ x[i] = self.m[i](x[i]) # conv
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
+
+ if not self.training: # inference
+ if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
+ self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
+
+ y = x[i].sigmoid()
+ if self.inplace:
+ y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
+ xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
+ xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
+ wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
+ y = torch.cat((xy, wh, conf), 4)
+ z.append(y.view(bs, -1, self.no))
+
+ return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
+
+ def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):
+ d = self.anchors[i].device
+ t = self.anchors[i].dtype
+ shape = 1, self.na, ny, nx, 2 # grid shape
+ y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
+ if torch_1_10: # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
+ yv, xv = torch.meshgrid(y, x, indexing='ij')
+ else:
+ yv, xv = torch.meshgrid(y, x)
+ grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
+ anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
+ return grid, anchor_grid
+
+
+class BaseModel(nn.Module):
+ # YOLOv5 base model
+ def forward(self, x, profile=False, visualize=False):
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
+
+ def _forward_once(self, x, profile=False, visualize=False):
+ y, dt = [], [] # outputs
+ for m in self.model:
+ if m.f != -1: # if not from previous layer
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
+ if profile:
+ self._profile_one_layer(m, x, dt)
+ x = m(x) # run
+ y.append(x if m.i in self.save else None) # save output
+ if visualize:
+ feature_visualization(x, m.type, m.i, save_dir=visualize)
+ return x
+
+ def _profile_one_layer(self, m, x, dt):
+ c = m == self.model[-1] # is final layer, copy input as inplace fix
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
+ t = time_sync()
+ for _ in range(10):
+ m(x.copy() if c else x)
+ dt.append((time_sync() - t) * 100)
+ if m == self.model[0]:
+ LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
+ LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
+ if c:
+ LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
+
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
+ LOGGER.info('Fusing layers... ')
+ for m in self.model.modules():
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
+ delattr(m, 'bn') # remove batchnorm
+ m.forward = m.forward_fuse # update forward
+ self.info()
+ return self
+
+ def info(self, verbose=False, img_size=640): # print model information
+ model_info(self, verbose, img_size)
+
+ def _apply(self, fn):
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
+ self = super()._apply(fn)
+ m = self.model[-1] # Detect()
+ if isinstance(m, Detect):
+ m.stride = fn(m.stride)
+ m.grid = list(map(fn, m.grid))
+ if isinstance(m.anchor_grid, list):
+ m.anchor_grid = list(map(fn, m.anchor_grid))
+ return self
+
+
+class DetectionModel(BaseModel):
+ # YOLOv5 detection model
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
+ super().__init__()
+ if isinstance(cfg, dict):
+ self.yaml = cfg # model dict
+ else: # is *.yaml
+ import yaml # for torch hub
+ self.yaml_file = Path(cfg).name
+ with open(cfg, encoding='ascii', errors='ignore') as f:
+ self.yaml = yaml.safe_load(f) # model dict
+
+ # Define model
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
+ if nc and nc != self.yaml['nc']:
+ LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
+ self.yaml['nc'] = nc # override yaml value
+ if anchors:
+ LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
+ self.yaml['anchors'] = round(anchors) # override yaml value
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
+ self.inplace = self.yaml.get('inplace', True)
+
+ # Build strides, anchors
+ m = self.model[-1] # Detect()
+ if isinstance(m, Detect):
+ s = 256 # 2x min stride
+ m.inplace = self.inplace
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.empty(1, ch, s, s))]) # forward
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
+ m.anchors /= m.stride.view(-1, 1, 1)
+ self.stride = m.stride
+ self._initialize_biases() # only run once
+
+ # Init weights, biases
+ initialize_weights(self)
+ self.info()
+ LOGGER.info('')
+
+ def forward(self, x, augment=False, profile=False, visualize=False):
+ if augment:
+ return self._forward_augment(x) # augmented inference, None
+ return self._forward_once(x, profile, visualize) # single-scale inference, train
+
+ def _forward_augment(self, x):
+ img_size = x.shape[-2:] # height, width
+ s = [1, 0.83, 0.67] # scales
+ f = [None, 3, None] # flips (2-ud, 3-lr)
+ y = [] # outputs
+ for si, fi in zip(s, f):
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
+ yi = self._forward_once(xi)[0] # forward
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
+ yi = self._descale_pred(yi, fi, si, img_size)
+ y.append(yi)
+ y = self._clip_augmented(y) # clip augmented tails
+ return torch.cat(y, 1), None # augmented inference, train
+
+ def _descale_pred(self, p, flips, scale, img_size):
+ # de-scale predictions following augmented inference (inverse operation)
+ if self.inplace:
+ p[..., :4] /= scale # de-scale
+ if flips == 2:
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
+ elif flips == 3:
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
+ else:
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
+ if flips == 2:
+ y = img_size[0] - y # de-flip ud
+ elif flips == 3:
+ x = img_size[1] - x # de-flip lr
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
+ return p
+
+ def _clip_augmented(self, y):
+ # Clip YOLOv5 augmented inference tails
+ nl = self.model[-1].nl # number of detection layers (P3-P5)
+ g = sum(4 ** x for x in range(nl)) # grid points
+ e = 1 # exclude layer count
+ i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
+ y[0] = y[0][:, :-i] # large
+ i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
+ y[-1] = y[-1][:, i:] # small
+ return y
+
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
+ # https://arxiv.org/abs/1708.02002 section 3.3
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
+ m = self.model[-1] # Detect() module
+ for mi, s in zip(m.m, m.stride): # from
+ b = mi.bias.view(m.na, -1).detach() # conv.bias(255) to (3,85)
+ b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
+ b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
+
+
+Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility
+
+
+class ClassificationModel(BaseModel):
+ # YOLOv5 classification model
+ def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index
+ super().__init__()
+ self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
+
+ def _from_detection_model(self, model, nc=1000, cutoff=10):
+ # Create a YOLOv5 classification model from a YOLOv5 detection model
+ if isinstance(model, DetectMultiBackend):
+ model = model.model # unwrap DetectMultiBackend
+ model.model = model.model[:cutoff] # backbone
+ m = model.model[-1] # last layer
+ ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module
+ c = Classify(ch, nc) # Classify()
+ c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type
+ model.model[-1] = c # replace
+ self.model = model.model
+ self.stride = model.stride
+ self.save = []
+ self.nc = nc
+
+ def _from_yaml(self, cfg):
+ # Create a YOLOv5 classification model from a *.yaml file
+ self.model = None
+
+
+def parse_model(d, ch): # model_dict, input_channels(3)
+ LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
+
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
+ m = eval(m) if isinstance(m, str) else m # eval strings
+ for j, a in enumerate(args):
+ with contextlib.suppress(NameError):
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
+
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
+ if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x):
+ c1, c2 = ch[f], args[0]
+ if c2 != no: # if not output
+ c2 = make_divisible(c2 * gw, 8)
+
+ args = [c1, c2, *args[1:]]
+ if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]:
+ args.insert(2, n) # number of repeats
+ n = 1
+ elif m is nn.BatchNorm2d:
+ args = [ch[f]]
+ elif m is Concat:
+ c2 = sum(ch[x] for x in f)
+ elif m is Detect:
+ args.append([ch[x] for x in f])
+ if isinstance(args[1], int): # number of anchors
+ args[1] = [list(range(args[1] * 2))] * len(f)
+ elif m is Contract:
+ c2 = ch[f] * args[0] ** 2
+ elif m is Expand:
+ c2 = ch[f] // args[0] ** 2
+ else:
+ c2 = ch[f]
+
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
+ t = str(m)[8:-2].replace('__main__.', '') # module type
+ np = sum(x.numel() for x in m_.parameters()) # number params
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
+ LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
+ layers.append(m_)
+ if i == 0:
+ ch = []
+ ch.append(c2)
+ return nn.Sequential(*layers), sorted(save)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
+ parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
+ parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
+ parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
+ opt = parser.parse_args()
+ opt.cfg = check_yaml(opt.cfg) # check YAML
+ print_args(vars(opt))
+ device = select_device(opt.device)
+
+ # Create model
+ im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
+ model = Model(opt.cfg).to(device)
+
+ # Options
+ if opt.line_profile: # profile layer by layer
+ model(im, profile=True)
+
+ elif opt.profile: # profile forward-backward
+ results = profile(input=im, ops=[model], n=3)
+
+ elif opt.test: # test all models
+ for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
+ try:
+ _ = Model(cfg)
+ except Exception as e:
+ print(f'Error in {cfg}: {e}')
+
+ else: # report fused model summary
+ model.fuse()
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/__init__.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/__init__.py
new file mode 100644
index 000000000..a63c473a4
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/__init__.py
@@ -0,0 +1,36 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+utils/initialization
+"""
+
+
+def notebook_init(verbose=True):
+ # Check system software and hardware
+ print('Checking setup...')
+
+ import os
+ import shutil
+
+ from utils.general import check_requirements, emojis, is_colab
+ from utils.torch_utils import select_device # imports
+
+ check_requirements(('psutil', 'IPython'))
+ import psutil
+ from IPython import display # to display images and clear console output
+
+ if is_colab():
+ shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory
+
+ # System info
+ if verbose:
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
+ ram = psutil.virtual_memory().total
+ total, used, free = shutil.disk_usage("/")
+ display.clear_output()
+ s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)'
+ else:
+ s = ''
+
+ select_device(newline=False)
+ print(emojis(f'Setup complete ✅ {s}'))
+ return display
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/activations.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/activations.py
new file mode 100644
index 000000000..084ce8c41
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/activations.py
@@ -0,0 +1,103 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Activation functions
+"""
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+class SiLU(nn.Module):
+ # SiLU activation https://arxiv.org/pdf/1606.08415.pdf
+ @staticmethod
+ def forward(x):
+ return x * torch.sigmoid(x)
+
+
+class Hardswish(nn.Module):
+ # Hard-SiLU activation
+ @staticmethod
+ def forward(x):
+ # return x * F.hardsigmoid(x) # for TorchScript and CoreML
+ return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
+
+
+class Mish(nn.Module):
+ # Mish activation https://github.com/digantamisra98/Mish
+ @staticmethod
+ def forward(x):
+ return x * F.softplus(x).tanh()
+
+
+class MemoryEfficientMish(nn.Module):
+ # Mish activation memory-efficient
+ class F(torch.autograd.Function):
+
+ @staticmethod
+ def forward(ctx, x):
+ ctx.save_for_backward(x)
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ x = ctx.saved_tensors[0]
+ sx = torch.sigmoid(x)
+ fx = F.softplus(x).tanh()
+ return grad_output * (fx + x * sx * (1 - fx * fx))
+
+ def forward(self, x):
+ return self.F.apply(x)
+
+
+class FReLU(nn.Module):
+ # FReLU activation https://arxiv.org/abs/2007.11824
+ def __init__(self, c1, k=3): # ch_in, kernel
+ super().__init__()
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
+ self.bn = nn.BatchNorm2d(c1)
+
+ def forward(self, x):
+ return torch.max(x, self.bn(self.conv(x)))
+
+
+class AconC(nn.Module):
+ r""" ACON activation (activate or not)
+ AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
+ according to "Activate or Not: Learning Customized Activation" .
+ """
+
+ def __init__(self, c1):
+ super().__init__()
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
+ self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
+
+ def forward(self, x):
+ dpx = (self.p1 - self.p2) * x
+ return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
+
+
+class MetaAconC(nn.Module):
+ r""" ACON activation (activate or not)
+ MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
+ according to "Activate or Not: Learning Customized Activation" .
+ """
+
+ def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
+ super().__init__()
+ c2 = max(r, c1 // r)
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
+ self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
+ self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
+ # self.bn1 = nn.BatchNorm2d(c2)
+ # self.bn2 = nn.BatchNorm2d(c1)
+
+ def forward(self, x):
+ y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
+ # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
+ # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
+ beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
+ dpx = (self.p1 - self.p2) * x
+ return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/augmentations.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/augmentations.py
new file mode 100644
index 000000000..a55fefa68
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/augmentations.py
@@ -0,0 +1,347 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Image augmentation functions
+"""
+
+import math
+import random
+
+import cv2
+import numpy as np
+import torchvision.transforms as T
+import torchvision.transforms.functional as TF
+
+from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box
+from utils.metrics import bbox_ioa
+
+IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
+IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
+
+
+class Albumentations:
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
+ def __init__(self):
+ self.transform = None
+ prefix = colorstr('albumentations: ')
+ try:
+ import albumentations as A
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
+
+ T = [
+ A.Blur(p=0.01),
+ A.MedianBlur(p=0.01),
+ A.ToGray(p=0.01),
+ A.CLAHE(p=0.01),
+ A.RandomBrightnessContrast(p=0.0),
+ A.RandomGamma(p=0.0),
+ A.ImageCompression(quality_lower=75, p=0.0)] # transforms
+ self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
+
+ LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
+ except ImportError: # package not installed, skip
+ pass
+ except Exception as e:
+ LOGGER.info(f'{prefix}{e}')
+
+ def __call__(self, im, labels, p=1.0):
+ if self.transform and random.random() < p:
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
+ return im, labels
+
+
+def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
+ # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std
+ return TF.normalize(x, mean, std, inplace=inplace)
+
+
+def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
+ # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean
+ for i in range(3):
+ x[:, i] = x[:, i] * std[i] + mean[i]
+ return x
+
+
+def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
+ # HSV color-space augmentation
+ if hgain or sgain or vgain:
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
+ hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
+ dtype = im.dtype # uint8
+
+ x = np.arange(0, 256, dtype=r.dtype)
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
+
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
+
+
+def hist_equalize(im, clahe=True, bgr=False):
+ # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
+ yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
+ if clahe:
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
+ else:
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
+
+
+def replicate(im, labels):
+ # Replicate labels
+ h, w = im.shape[:2]
+ boxes = labels[:, 1:].astype(int)
+ x1, y1, x2, y2 = boxes.T
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
+ x1b, y1b, x2b, y2b = boxes[i]
+ bh, bw = y2b - y1b, x2b - x1b
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
+ im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
+
+ return im, labels
+
+
+def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
+ # Resize and pad image while meeting stride-multiple constraints
+ shape = im.shape[:2] # current shape [height, width]
+ if isinstance(new_shape, int):
+ new_shape = (new_shape, new_shape)
+
+ # Scale ratio (new / old)
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
+ r = min(r, 1.0)
+
+ # Compute padding
+ ratio = r, r # width, height ratios
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
+ if auto: # minimum rectangle
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
+ elif scaleFill: # stretch
+ dw, dh = 0.0, 0.0
+ new_unpad = (new_shape[1], new_shape[0])
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
+
+ dw /= 2 # divide padding into 2 sides
+ dh /= 2
+
+ if shape[::-1] != new_unpad: # resize
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
+ return im, ratio, (dw, dh)
+
+
+def random_perspective(im,
+ targets=(),
+ segments=(),
+ degrees=10,
+ translate=.1,
+ scale=.1,
+ shear=10,
+ perspective=0.0,
+ border=(0, 0)):
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
+ # targets = [cls, xyxy]
+
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
+ width = im.shape[1] + border[1] * 2
+
+ # Center
+ C = np.eye(3)
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
+
+ # Perspective
+ P = np.eye(3)
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
+
+ # Rotation and Scale
+ R = np.eye(3)
+ a = random.uniform(-degrees, degrees)
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
+ s = random.uniform(1 - scale, 1 + scale)
+ # s = 2 ** random.uniform(-scale, scale)
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
+
+ # Shear
+ S = np.eye(3)
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
+
+ # Translation
+ T = np.eye(3)
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
+
+ # Combined rotation matrix
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
+ if perspective:
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
+ else: # affine
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
+
+ # Visualize
+ # import matplotlib.pyplot as plt
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
+ # ax[0].imshow(im[:, :, ::-1]) # base
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
+
+ # Transform label coordinates
+ n = len(targets)
+ if n:
+ use_segments = any(x.any() for x in segments)
+ new = np.zeros((n, 4))
+ if use_segments: # warp segments
+ segments = resample_segments(segments) # upsample
+ for i, segment in enumerate(segments):
+ xy = np.ones((len(segment), 3))
+ xy[:, :2] = segment
+ xy = xy @ M.T # transform
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
+
+ # clip
+ new[i] = segment2box(xy, width, height)
+
+ else: # warp boxes
+ xy = np.ones((n * 4, 3))
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
+ xy = xy @ M.T # transform
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
+
+ # create new boxes
+ x = xy[:, [0, 2, 4, 6]]
+ y = xy[:, [1, 3, 5, 7]]
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
+
+ # clip
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
+
+ # filter candidates
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
+ targets = targets[i]
+ targets[:, 1:5] = new[i]
+
+ return im, targets
+
+
+def copy_paste(im, labels, segments, p=0.5):
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
+ n = len(segments)
+ if p and n:
+ h, w, c = im.shape # height, width, channels
+ im_new = np.zeros(im.shape, np.uint8)
+ for j in random.sample(range(n), k=round(p * n)):
+ l, s = labels[j], segments[j]
+ box = w - l[3], l[2], w - l[1], l[4]
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
+
+ result = cv2.bitwise_and(src1=im, src2=im_new)
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
+ i = result > 0 # pixels to replace
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
+
+ return im, labels, segments
+
+
+def cutout(im, labels, p=0.5):
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
+ if random.random() < p:
+ h, w = im.shape[:2]
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
+ for s in scales:
+ mask_h = random.randint(1, int(h * s)) # create random masks
+ mask_w = random.randint(1, int(w * s))
+
+ # box
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
+ xmax = min(w, xmin + mask_w)
+ ymax = min(h, ymin + mask_h)
+
+ # apply random color mask
+ im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
+
+ # return unobscured labels
+ if len(labels) and s > 0.03:
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
+
+ return labels
+
+
+def mixup(im, labels, im2, labels2):
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
+ labels = np.concatenate((labels, labels2), 0)
+ return im, labels
+
+
+def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
+
+
+def classify_albumentations(augment=True,
+ size=224,
+ scale=(0.08, 1.0),
+ hflip=0.5,
+ vflip=0.0,
+ jitter=0.4,
+ mean=IMAGENET_MEAN,
+ std=IMAGENET_STD,
+ auto_aug=False):
+ # YOLOv5 classification Albumentations (optional, only used if package is installed)
+ prefix = colorstr('albumentations: ')
+ try:
+ import albumentations as A
+ from albumentations.pytorch import ToTensorV2
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
+ if augment: # Resize and crop
+ T = [A.RandomResizedCrop(height=size, width=size, scale=scale)]
+ if auto_aug:
+ # TODO: implement AugMix, AutoAug & RandAug in albumentation
+ LOGGER.info(f'{prefix}auto augmentations are currently not supported')
+ else:
+ if hflip > 0:
+ T += [A.HorizontalFlip(p=hflip)]
+ if vflip > 0:
+ T += [A.VerticalFlip(p=vflip)]
+ if jitter > 0:
+ color_jitter = (float(jitter),) * 3 # repeat value for brightness, contrast, satuaration, 0 hue
+ T += [A.ColorJitter(*color_jitter, 0)]
+ else: # Use fixed crop for eval set (reproducibility)
+ T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
+ T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
+ LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
+ return A.Compose(T)
+
+ except ImportError: # package not installed, skip
+ pass
+ except Exception as e:
+ LOGGER.info(f'{prefix}{e}')
+
+
+def classify_transforms(size=224):
+ # Transforms to apply if albumentations not installed
+ return T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/autoanchor.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/autoanchor.py
new file mode 100644
index 000000000..f2222203e
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/autoanchor.py
@@ -0,0 +1,170 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+AutoAnchor utils
+"""
+
+import random
+
+import numpy as np
+import torch
+import yaml
+from tqdm import tqdm
+
+from utils.general import LOGGER, colorstr
+
+PREFIX = colorstr('AutoAnchor: ')
+
+
+def check_anchor_order(m):
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
+ a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer
+ da = a[-1] - a[0] # delta a
+ ds = m.stride[-1] - m.stride[0] # delta s
+ if da and (da.sign() != ds.sign()): # same order
+ LOGGER.info(f'{PREFIX}Reversing anchor order')
+ m.anchors[:] = m.anchors.flip(0)
+
+
+def check_anchors(dataset, model, thr=4.0, imgsz=640):
+ # Check anchor fit to data, recompute if necessary
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
+
+ def metric(k): # compute metric
+ r = wh[:, None] / k[None]
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
+ best = x.max(1)[0] # best_x
+ aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
+ bpr = (best > 1 / thr).float().mean() # best possible recall
+ return bpr, aat
+
+ stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides
+ anchors = m.anchors.clone() * stride # current anchors
+ bpr, aat = metric(anchors.cpu().view(-1, 2))
+ s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '
+ if bpr > 0.98: # threshold to recompute
+ LOGGER.info(f'{s}Current anchors are a good fit to dataset ✅')
+ else:
+ LOGGER.info(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...')
+ na = m.anchors.numel() // 2 # number of anchors
+ try:
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
+ except Exception as e:
+ LOGGER.info(f'{PREFIX}ERROR: {e}')
+ new_bpr = metric(anchors)[0]
+ if new_bpr > bpr: # replace anchors
+ anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
+ m.anchors[:] = anchors.clone().view_as(m.anchors)
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
+ m.anchors /= stride
+ s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)'
+ else:
+ s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)'
+ LOGGER.info(s)
+
+
+def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
+ """ Creates kmeans-evolved anchors from training dataset
+
+ Arguments:
+ dataset: path to data.yaml, or a loaded dataset
+ n: number of anchors
+ img_size: image size used for training
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
+ gen: generations to evolve anchors using genetic algorithm
+ verbose: print all results
+
+ Return:
+ k: kmeans evolved anchors
+
+ Usage:
+ from utils.autoanchor import *; _ = kmean_anchors()
+ """
+ from scipy.cluster.vq import kmeans
+
+ npr = np.random
+ thr = 1 / thr
+
+ def metric(k, wh): # compute metrics
+ r = wh[:, None] / k[None]
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
+ return x, x.max(1)[0] # x, best_x
+
+ def anchor_fitness(k): # mutation fitness
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
+ return (best * (best > thr).float()).mean() # fitness
+
+ def print_results(k, verbose=True):
+ k = k[np.argsort(k.prod(1))] # sort small to large
+ x, best = metric(k, wh0)
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
+ s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \
+ f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \
+ f'past_thr={x[x > thr].mean():.3f}-mean: '
+ for x in k:
+ s += '%i,%i, ' % (round(x[0]), round(x[1]))
+ if verbose:
+ LOGGER.info(s[:-2])
+ return k
+
+ if isinstance(dataset, str): # *.yaml file
+ with open(dataset, errors='ignore') as f:
+ data_dict = yaml.safe_load(f) # model dict
+ from utils.dataloaders import LoadImagesAndLabels
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
+
+ # Get label wh
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
+
+ # Filter
+ i = (wh0 < 3.0).any(1).sum()
+ if i:
+ LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found: {i} of {len(wh0)} labels are < 3 pixels in size')
+ wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
+ # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
+
+ # Kmeans init
+ try:
+ LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')
+ assert n <= len(wh) # apply overdetermined constraint
+ s = wh.std(0) # sigmas for whitening
+ k = kmeans(wh / s, n, iter=30)[0] * s # points
+ assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar
+ except Exception:
+ LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init')
+ k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init
+ wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))
+ k = print_results(k, verbose=False)
+
+ # Plot
+ # k, d = [None] * 20, [None] * 20
+ # for i in tqdm(range(1, 21)):
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
+ # ax = ax.ravel()
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
+ # fig.savefig('wh.png', dpi=200)
+
+ # Evolve
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
+ pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
+ for _ in pbar:
+ v = np.ones(sh)
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
+ v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
+ kg = (k.copy() * v).clip(min=2.0)
+ fg = anchor_fitness(kg)
+ if fg > f:
+ f, k = fg, kg.copy()
+ pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
+ if verbose:
+ print_results(k, verbose)
+
+ return print_results(k)
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/autobatch.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/autobatch.py
new file mode 100644
index 000000000..07cddc99f
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/autobatch.py
@@ -0,0 +1,66 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Auto-batch utils
+"""
+
+from copy import deepcopy
+
+import numpy as np
+import torch
+
+from utils.general import LOGGER, colorstr
+from utils.torch_utils import profile
+
+
+def check_train_batch_size(model, imgsz=640, amp=True):
+ # Check YOLOv5 training batch size
+ with torch.cuda.amp.autocast(amp):
+ return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
+
+
+def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):
+ # Automatically estimate best batch size to use `fraction` of available CUDA memory
+ # Usage:
+ # import torch
+ # from utils.autobatch import autobatch
+ # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
+ # print(autobatch(model))
+
+ # Check device
+ prefix = colorstr('AutoBatch: ')
+ LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')
+ device = next(model.parameters()).device # get model device
+ if device.type == 'cpu':
+ LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')
+ return batch_size
+
+ # Inspect CUDA memory
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
+ d = str(device).upper() # 'CUDA:0'
+ properties = torch.cuda.get_device_properties(device) # device properties
+ t = properties.total_memory / gb # GiB total
+ r = torch.cuda.memory_reserved(device) / gb # GiB reserved
+ a = torch.cuda.memory_allocated(device) / gb # GiB allocated
+ f = t - (r + a) # GiB free
+ LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
+
+ # Profile batch sizes
+ batch_sizes = [1, 2, 4, 8, 16]
+ try:
+ img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
+ results = profile(img, model, n=3, device=device)
+ except Exception as e:
+ LOGGER.warning(f'{prefix}{e}')
+
+ # Fit a solution
+ y = [x[2] for x in results if x] # memory [2]
+ p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit
+ b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
+ if None in results: # some sizes failed
+ i = results.index(None) # first fail index
+ if b >= batch_sizes[i]: # y intercept above failure point
+ b = batch_sizes[max(i - 1, 0)] # select prior safe point
+
+ fraction = np.polyval(p, b) / t # actual fraction predicted
+ LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')
+ return b
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/benchmarks.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/benchmarks.py
new file mode 100644
index 000000000..d412653c8
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/benchmarks.py
@@ -0,0 +1,157 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Run YOLOv5 benchmarks on all supported export formats
+
+Format | `export.py --include` | Model
+--- | --- | ---
+PyTorch | - | yolov5s.pt
+TorchScript | `torchscript` | yolov5s.torchscript
+ONNX | `onnx` | yolov5s.onnx
+OpenVINO | `openvino` | yolov5s_openvino_model/
+TensorRT | `engine` | yolov5s.engine
+CoreML | `coreml` | yolov5s.mlmodel
+TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
+TensorFlow GraphDef | `pb` | yolov5s.pb
+TensorFlow Lite | `tflite` | yolov5s.tflite
+TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
+TensorFlow.js | `tfjs` | yolov5s_web_model/
+
+Requirements:
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
+ $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
+
+Usage:
+ $ python utils/benchmarks.py --weights yolov5s.pt --img 640
+"""
+
+import argparse
+import platform
+import sys
+import time
+from pathlib import Path
+
+import pandas as pd
+
+FILE = Path(__file__).resolve()
+ROOT = FILE.parents[1] # YOLOv5 root directory
+if str(ROOT) not in sys.path:
+ sys.path.append(str(ROOT)) # add ROOT to PATH
+# ROOT = ROOT.relative_to(Path.cwd()) # relative
+
+import export
+import val
+from utils import notebook_init
+from utils.general import LOGGER, check_yaml, file_size, print_args
+from utils.torch_utils import select_device
+
+
+def run(
+ weights=ROOT / 'yolov5s.pt', # weights path
+ imgsz=640, # inference size (pixels)
+ batch_size=1, # batch size
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
+ half=False, # use FP16 half-precision inference
+ test=False, # test exports only
+ pt_only=False, # test PyTorch only
+ hard_fail=False, # throw error on benchmark failure
+):
+ y, t = [], time.time()
+ device = select_device(device)
+ for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
+ try:
+ assert i not in (9, 10), 'inference not supported' # Edge TPU and TF.js are unsupported
+ assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13' # CoreML
+ if 'cpu' in device.type:
+ assert cpu, 'inference not supported on CPU'
+ if 'cuda' in device.type:
+ assert gpu, 'inference not supported on GPU'
+
+ # Export
+ if f == '-':
+ w = weights # PyTorch format
+ else:
+ w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others
+ assert suffix in str(w), 'export failed'
+
+ # Validate
+ result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half)
+ metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls))
+ speeds = result[2] # times (preprocess, inference, postprocess)
+ y.append([name, round(file_size(w), 1), round(metrics[3], 4), round(speeds[1], 2)]) # MB, mAP, t_inference
+ except Exception as e:
+ if hard_fail:
+ assert type(e) is AssertionError, f'Benchmark --hard-fail for {name}: {e}'
+ LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}')
+ y.append([name, None, None, None]) # mAP, t_inference
+ if pt_only and i == 0:
+ break # break after PyTorch
+
+ # Print results
+ LOGGER.info('\n')
+ parse_opt()
+ notebook_init() # print system info
+ c = ['Format', 'Size (MB)', 'mAP@0.5:0.95', 'Inference time (ms)'] if map else ['Format', 'Export', '', '']
+ py = pd.DataFrame(y, columns=c)
+ LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
+ LOGGER.info(str(py if map else py.iloc[:, :2]))
+ return py
+
+
+def test(
+ weights=ROOT / 'yolov5s.pt', # weights path
+ imgsz=640, # inference size (pixels)
+ batch_size=1, # batch size
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
+ half=False, # use FP16 half-precision inference
+ test=False, # test exports only
+ pt_only=False, # test PyTorch only
+ hard_fail=False, # throw error on benchmark failure
+):
+ y, t = [], time.time()
+ device = select_device(device)
+ for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
+ try:
+ w = weights if f == '-' else \
+ export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights
+ assert suffix in str(w), 'export failed'
+ y.append([name, True])
+ except Exception:
+ y.append([name, False]) # mAP, t_inference
+
+ # Print results
+ LOGGER.info('\n')
+ parse_opt()
+ notebook_init() # print system info
+ py = pd.DataFrame(y, columns=['Format', 'Export'])
+ LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)')
+ LOGGER.info(str(py))
+ return py
+
+
+def parse_opt():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
+ parser.add_argument('--test', action='store_true', help='test exports only')
+ parser.add_argument('--pt-only', action='store_true', help='test PyTorch only')
+ parser.add_argument('--hard-fail', action='store_true', help='throw error on benchmark failure')
+ opt = parser.parse_args()
+ opt.data = check_yaml(opt.data) # check YAML
+ print_args(vars(opt))
+ return opt
+
+
+def main(opt):
+ test(**vars(opt)) if opt.test else run(**vars(opt))
+
+
+if __name__ == "__main__":
+ opt = parse_opt()
+ main(opt)
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/callbacks.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/callbacks.py
new file mode 100644
index 000000000..2b32df0bf
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/callbacks.py
@@ -0,0 +1,71 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Callback utils
+"""
+
+
+class Callbacks:
+ """"
+ Handles all registered callbacks for YOLOv5 Hooks
+ """
+
+ def __init__(self):
+ # Define the available callbacks
+ self._callbacks = {
+ 'on_pretrain_routine_start': [],
+ 'on_pretrain_routine_end': [],
+ 'on_train_start': [],
+ 'on_train_epoch_start': [],
+ 'on_train_batch_start': [],
+ 'optimizer_step': [],
+ 'on_before_zero_grad': [],
+ 'on_train_batch_end': [],
+ 'on_train_epoch_end': [],
+ 'on_val_start': [],
+ 'on_val_batch_start': [],
+ 'on_val_image_end': [],
+ 'on_val_batch_end': [],
+ 'on_val_end': [],
+ 'on_fit_epoch_end': [], # fit = train + val
+ 'on_model_save': [],
+ 'on_train_end': [],
+ 'on_params_update': [],
+ 'teardown': [],}
+ self.stop_training = False # set True to interrupt training
+
+ def register_action(self, hook, name='', callback=None):
+ """
+ Register a new action to a callback hook
+
+ Args:
+ hook: The callback hook name to register the action to
+ name: The name of the action for later reference
+ callback: The callback to fire
+ """
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
+ assert callable(callback), f"callback '{callback}' is not callable"
+ self._callbacks[hook].append({'name': name, 'callback': callback})
+
+ def get_registered_actions(self, hook=None):
+ """"
+ Returns all the registered actions by callback hook
+
+ Args:
+ hook: The name of the hook to check, defaults to all
+ """
+ return self._callbacks[hook] if hook else self._callbacks
+
+ def run(self, hook, *args, **kwargs):
+ """
+ Loop through the registered actions and fire all callbacks
+
+ Args:
+ hook: The name of the hook to check, defaults to all
+ args: Arguments to receive from YOLOv5
+ kwargs: Keyword Arguments to receive from YOLOv5
+ """
+
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
+
+ for logger in self._callbacks[hook]:
+ logger['callback'](*args, **kwargs)
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/dataloaders.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/dataloaders.py
new file mode 100755
index 000000000..3f26be2cd
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/dataloaders.py
@@ -0,0 +1,1157 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Dataloaders and dataset utils
+"""
+
+import contextlib
+import glob
+import hashlib
+import json
+import math
+import os
+import random
+import shutil
+import time
+from itertools import repeat
+from multiprocessing.pool import Pool, ThreadPool
+from pathlib import Path
+from threading import Thread
+from urllib.parse import urlparse
+from zipfile import ZipFile
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+import torchvision
+import yaml
+from PIL import ExifTags, Image, ImageOps
+from torch.utils.data import DataLoader, Dataset, dataloader, distributed
+from tqdm import tqdm
+
+from utils.augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,
+ letterbox, mixup, random_perspective)
+from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str,
+ cv2, is_colab, is_kaggle, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
+from utils.torch_utils import torch_distributed_zero_first
+
+# Parameters
+HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
+IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' # include image suffixes
+VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes
+BAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}' # tqdm bar format
+LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
+
+# Get orientation exif tag
+for orientation in ExifTags.TAGS.keys():
+ if ExifTags.TAGS[orientation] == 'Orientation':
+ break
+
+
+def get_hash(paths):
+ # Returns a single hash value of a list of paths (files or dirs)
+ size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
+ h = hashlib.md5(str(size).encode()) # hash sizes
+ h.update(''.join(paths).encode()) # hash paths
+ return h.hexdigest() # return hash
+
+
+def exif_size(img):
+ # Returns exif-corrected PIL size
+ s = img.size # (width, height)
+ with contextlib.suppress(Exception):
+ rotation = dict(img._getexif().items())[orientation]
+ if rotation in [6, 8]: # rotation 270 or 90
+ s = (s[1], s[0])
+ return s
+
+
+def exif_transpose(image):
+ """
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
+
+ :param image: The image to transpose.
+ :return: An image.
+ """
+ exif = image.getexif()
+ orientation = exif.get(0x0112, 1) # default 1
+ if orientation > 1:
+ method = {
+ 2: Image.FLIP_LEFT_RIGHT,
+ 3: Image.ROTATE_180,
+ 4: Image.FLIP_TOP_BOTTOM,
+ 5: Image.TRANSPOSE,
+ 6: Image.ROTATE_270,
+ 7: Image.TRANSVERSE,
+ 8: Image.ROTATE_90,}.get(orientation)
+ if method is not None:
+ image = image.transpose(method)
+ del exif[0x0112]
+ image.info["exif"] = exif.tobytes()
+ return image
+
+
+def seed_worker(worker_id):
+ # Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader
+ worker_seed = torch.initial_seed() % 2 ** 32
+ np.random.seed(worker_seed)
+ random.seed(worker_seed)
+
+
+def create_dataloader(path,
+ imgsz,
+ batch_size,
+ stride,
+ single_cls=False,
+ hyp=None,
+ augment=False,
+ cache=False,
+ pad=0.0,
+ rect=False,
+ rank=-1,
+ workers=8,
+ image_weights=False,
+ quad=False,
+ prefix='',
+ shuffle=False):
+ if rect and shuffle:
+ LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')
+ shuffle = False
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
+ dataset = LoadImagesAndLabels(
+ path,
+ imgsz,
+ batch_size,
+ augment=augment, # augmentation
+ hyp=hyp, # hyperparameters
+ rect=rect, # rectangular batches
+ cache_images=cache,
+ single_cls=single_cls,
+ stride=int(stride),
+ pad=pad,
+ image_weights=image_weights,
+ prefix=prefix)
+
+ batch_size = min(batch_size, len(dataset))
+ nd = torch.cuda.device_count() # number of CUDA devices
+ nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers
+ sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
+ loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
+ generator = torch.Generator()
+ generator.manual_seed(0)
+ return loader(dataset,
+ batch_size=batch_size,
+ shuffle=shuffle and sampler is None,
+ num_workers=nw,
+ sampler=sampler,
+ pin_memory=True,
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn,
+ worker_init_fn=seed_worker,
+ generator=generator), dataset
+
+
+class InfiniteDataLoader(dataloader.DataLoader):
+ """ Dataloader that reuses workers
+
+ Uses same syntax as vanilla DataLoader
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
+ self.iterator = super().__iter__()
+
+ def __len__(self):
+ return len(self.batch_sampler.sampler)
+
+ def __iter__(self):
+ for _ in range(len(self)):
+ yield next(self.iterator)
+
+
+class _RepeatSampler:
+ """ Sampler that repeats forever
+
+ Args:
+ sampler (Sampler)
+ """
+
+ def __init__(self, sampler):
+ self.sampler = sampler
+
+ def __iter__(self):
+ while True:
+ yield from iter(self.sampler)
+
+
+class LoadImages:
+ # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
+ def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None):
+ files = []
+ for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
+ p = str(Path(p).resolve())
+ if '*' in p:
+ files.extend(sorted(glob.glob(p, recursive=True))) # glob
+ elif os.path.isdir(p):
+ files.extend(sorted(glob.glob(os.path.join(p, '*.*')))) # dir
+ elif os.path.isfile(p):
+ files.append(p) # files
+ else:
+ raise FileNotFoundError(f'{p} does not exist')
+
+ images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
+ videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
+ ni, nv = len(images), len(videos)
+
+ self.img_size = img_size
+ self.stride = stride
+ self.files = images + videos
+ self.nf = ni + nv # number of files
+ self.video_flag = [False] * ni + [True] * nv
+ self.mode = 'image'
+ self.auto = auto
+ self.transforms = transforms # optional
+ if any(videos):
+ self.new_video(videos[0]) # new video
+ else:
+ self.cap = None
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
+ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
+
+ def __iter__(self):
+ self.count = 0
+ return self
+
+ def __next__(self):
+ if self.count == self.nf:
+ raise StopIteration
+ path = self.files[self.count]
+
+ if self.video_flag[self.count]:
+ # Read video
+ self.mode = 'video'
+ ret_val, im0 = self.cap.read()
+ while not ret_val:
+ self.count += 1
+ self.cap.release()
+ if self.count == self.nf: # last video
+ raise StopIteration
+ path = self.files[self.count]
+ self.new_video(path)
+ ret_val, im0 = self.cap.read()
+
+ self.frame += 1
+ s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
+
+ else:
+ # Read image
+ self.count += 1
+ im0 = cv2.imread(path) # BGR
+ assert im0 is not None, f'Image Not Found {path}'
+ s = f'image {self.count}/{self.nf} {path}: '
+
+ if self.transforms:
+ im = self.transforms(cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)) # classify transforms
+ else:
+ im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize
+ im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
+ im = np.ascontiguousarray(im) # contiguous
+
+ return path, im, im0, self.cap, s
+
+ def new_video(self, path):
+ self.frame = 0
+ self.cap = cv2.VideoCapture(path)
+ self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
+
+ def __len__(self):
+ return self.nf # number of files
+
+
+class LoadWebcam: # for inference
+ # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0`
+ def __init__(self, pipe='0', img_size=640, stride=32):
+ self.img_size = img_size
+ self.stride = stride
+ self.pipe = eval(pipe) if pipe.isnumeric() else pipe
+ self.cap = cv2.VideoCapture(self.pipe) # video capture object
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
+
+ def __iter__(self):
+ self.count = -1
+ return self
+
+ def __next__(self):
+ self.count += 1
+ if cv2.waitKey(1) == ord('q'): # q to quit
+ self.cap.release()
+ cv2.destroyAllWindows()
+ raise StopIteration
+
+ # Read frame
+ ret_val, img0 = self.cap.read()
+ img0 = cv2.flip(img0, 1) # flip left-right
+
+ # Print
+ assert ret_val, f'Camera Error {self.pipe}'
+ img_path = 'webcam.jpg'
+ s = f'webcam {self.count}: '
+
+ # Padded resize
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
+
+ # Convert
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
+ img = np.ascontiguousarray(img)
+
+ return img_path, img, img0, None, s
+
+ def __len__(self):
+ return 0
+
+
+class LoadStreams:
+ # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`
+ def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):
+ self.mode = 'stream'
+ self.img_size = img_size
+ self.stride = stride
+
+ if os.path.isfile(sources):
+ with open(sources) as f:
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
+ else:
+ sources = [sources]
+
+ n = len(sources)
+ self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
+ self.auto = auto
+ for i, s in enumerate(sources): # index, source
+ # Start thread to read frames from video stream
+ st = f'{i + 1}/{n}: {s}... '
+ if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'): # if source is YouTube video
+ check_requirements(('pafy', 'youtube_dl==2020.12.2'))
+ import pafy
+ s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
+ s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
+ if s == 0:
+ assert not is_colab(), '--source 0 webcam unsupported on Colab. Rerun command in a local environment.'
+ assert not is_kaggle(), '--source 0 webcam unsupported on Kaggle. Rerun command in a local environment.'
+ cap = cv2.VideoCapture(s)
+ assert cap.isOpened(), f'{st}Failed to open {s}'
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+ fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan
+ self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
+ self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback
+
+ _, self.imgs[i] = cap.read() # guarantee first frame
+ self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)
+ LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
+ self.threads[i].start()
+ LOGGER.info('') # newline
+
+ # check for common shapes
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
+ if not self.rect:
+ LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.')
+
+ def update(self, i, cap, stream):
+ # Read stream `i` frames in daemon thread
+ n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
+ while cap.isOpened() and n < f:
+ n += 1
+ # _, self.imgs[index] = cap.read()
+ cap.grab()
+ if n % read == 0:
+ success, im = cap.retrieve()
+ if success:
+ self.imgs[i] = im
+ else:
+ LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.')
+ self.imgs[i] = np.zeros_like(self.imgs[i])
+ cap.open(stream) # re-open stream if signal was lost
+ time.sleep(0.0) # wait time
+
+ def __iter__(self):
+ self.count = -1
+ return self
+
+ def __next__(self):
+ self.count += 1
+ if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
+ cv2.destroyAllWindows()
+ raise StopIteration
+
+ # Letterbox
+ img0 = self.imgs.copy()
+ img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]
+
+ # Stack
+ img = np.stack(img, 0)
+
+ # Convert
+ img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
+ img = np.ascontiguousarray(img)
+
+ return self.sources, img, img0, None, ''
+
+ def __len__(self):
+ return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
+
+
+def img2label_paths(img_paths):
+ # Define label paths as a function of image paths
+ sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings
+ return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
+
+
+class LoadImagesAndLabels(Dataset):
+ # YOLOv5 train_loader/val_loader, loads images and labels for training and validation
+ cache_version = 0.6 # dataset labels *.cache version
+ rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
+
+ def __init__(self,
+ path,
+ img_size=640,
+ batch_size=16,
+ augment=False,
+ hyp=None,
+ rect=False,
+ image_weights=False,
+ cache_images=False,
+ single_cls=False,
+ stride=32,
+ pad=0.0,
+ prefix=''):
+ self.img_size = img_size
+ self.augment = augment
+ self.hyp = hyp
+ self.image_weights = image_weights
+ self.rect = False if image_weights else rect
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
+ self.stride = stride
+ self.path = path
+ self.albumentations = Albumentations() if augment else None
+
+ try:
+ f = [] # image files
+ for p in path if isinstance(path, list) else [path]:
+ p = Path(p) # os-agnostic
+ if p.is_dir(): # dir
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
+ # f = list(p.rglob('*.*')) # pathlib
+ elif p.is_file(): # file
+ with open(p) as t:
+ t = t.read().strip().splitlines()
+ parent = str(p.parent) + os.sep
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
+ else:
+ raise FileNotFoundError(f'{prefix}{p} does not exist')
+ self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib
+ assert self.im_files, f'{prefix}No images found'
+ except Exception as e:
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}')
+
+ # Check cache
+ self.label_files = img2label_paths(self.im_files) # labels
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
+ try:
+ cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
+ assert cache['version'] == self.cache_version # matches current version
+ assert cache['hash'] == get_hash(self.label_files + self.im_files) # identical hash
+ except Exception:
+ cache, exists = self.cache_labels(cache_path, prefix), False # run cache ops
+
+ # Display cache
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total
+ if exists and LOCAL_RANK in {-1, 0}:
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt"
+ tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results
+ if cache['msgs']:
+ LOGGER.info('\n'.join(cache['msgs'])) # display warnings
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'
+
+ # Read cache
+ [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
+ labels, shapes, self.segments = zip(*cache.values())
+ self.labels = list(labels)
+ self.shapes = np.array(shapes)
+ self.im_files = list(cache.keys()) # update
+ self.label_files = img2label_paths(cache.keys()) # update
+ n = len(shapes) # number of images
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
+ nb = bi[-1] + 1 # number of batches
+ self.batch = bi # batch index of image
+ self.n = n
+ self.indices = range(n)
+
+ # Update labels
+ include_class = [] # filter labels to include only these classes (optional)
+ include_class_array = np.array(include_class).reshape(1, -1)
+ for i, (label, segment) in enumerate(zip(self.labels, self.segments)):
+ if include_class:
+ j = (label[:, 0:1] == include_class_array).any(1)
+ self.labels[i] = label[j]
+ if segment:
+ self.segments[i] = segment[j]
+ if single_cls: # single-class training, merge all classes into 0
+ self.labels[i][:, 0] = 0
+ if segment:
+ self.segments[i][:, 0] = 0
+
+ # Rectangular Training
+ if self.rect:
+ # Sort by aspect ratio
+ s = self.shapes # wh
+ ar = s[:, 1] / s[:, 0] # aspect ratio
+ irect = ar.argsort()
+ self.im_files = [self.im_files[i] for i in irect]
+ self.label_files = [self.label_files[i] for i in irect]
+ self.labels = [self.labels[i] for i in irect]
+ self.shapes = s[irect] # wh
+ ar = ar[irect]
+
+ # Set training image shapes
+ shapes = [[1, 1]] * nb
+ for i in range(nb):
+ ari = ar[bi == i]
+ mini, maxi = ari.min(), ari.max()
+ if maxi < 1:
+ shapes[i] = [maxi, 1]
+ elif mini > 1:
+ shapes[i] = [1, 1 / mini]
+
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
+
+ # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources)
+ self.ims = [None] * n
+ self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]
+ if cache_images:
+ gb = 0 # Gigabytes of cached images
+ self.im_hw0, self.im_hw = [None] * n, [None] * n
+ fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image
+ results = ThreadPool(NUM_THREADS).imap(fcn, range(n))
+ pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT, disable=LOCAL_RANK > 0)
+ for i, x in pbar:
+ if cache_images == 'disk':
+ gb += self.npy_files[i].stat().st_size
+ else: # 'ram'
+ self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
+ gb += self.ims[i].nbytes
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'
+ pbar.close()
+
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
+ # Cache dataset labels, check images and read shapes
+ x = {} # dict
+ nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
+ desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
+ with Pool(NUM_THREADS) as pool:
+ pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),
+ desc=desc,
+ total=len(self.im_files),
+ bar_format=BAR_FORMAT)
+ for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
+ nm += nm_f
+ nf += nf_f
+ ne += ne_f
+ nc += nc_f
+ if im_file:
+ x[im_file] = [lb, shape, segments]
+ if msg:
+ msgs.append(msg)
+ pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt"
+
+ pbar.close()
+ if msgs:
+ LOGGER.info('\n'.join(msgs))
+ if nf == 0:
+ LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')
+ x['hash'] = get_hash(self.label_files + self.im_files)
+ x['results'] = nf, nm, ne, nc, len(self.im_files)
+ x['msgs'] = msgs # warnings
+ x['version'] = self.cache_version # cache version
+ try:
+ np.save(path, x) # save cache for next time
+ path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
+ LOGGER.info(f'{prefix}New cache created: {path}')
+ except Exception as e:
+ LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable
+ return x
+
+ def __len__(self):
+ return len(self.im_files)
+
+ # def __iter__(self):
+ # self.count = -1
+ # print('ran dataset iter')
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
+ # return self
+
+ def __getitem__(self, index):
+ index = self.indices[index] # linear, shuffled, or image_weights
+
+ hyp = self.hyp
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
+ if mosaic:
+ # Load mosaic
+ img, labels = self.load_mosaic(index)
+ shapes = None
+
+ # MixUp augmentation
+ if random.random() < hyp['mixup']:
+ img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1)))
+
+ else:
+ # Load image
+ img, (h0, w0), (h, w) = self.load_image(index)
+
+ # Letterbox
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
+
+ labels = self.labels[index].copy()
+ if labels.size: # normalized xywh to pixel xyxy format
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
+
+ if self.augment:
+ img, labels = random_perspective(img,
+ labels,
+ degrees=hyp['degrees'],
+ translate=hyp['translate'],
+ scale=hyp['scale'],
+ shear=hyp['shear'],
+ perspective=hyp['perspective'])
+
+ nl = len(labels) # number of labels
+ if nl:
+ labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
+
+ if self.augment:
+ # Albumentations
+ img, labels = self.albumentations(img, labels)
+ nl = len(labels) # update after albumentations
+
+ # HSV color-space
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
+
+ # Flip up-down
+ if random.random() < hyp['flipud']:
+ img = np.flipud(img)
+ if nl:
+ labels[:, 2] = 1 - labels[:, 2]
+
+ # Flip left-right
+ if random.random() < hyp['fliplr']:
+ img = np.fliplr(img)
+ if nl:
+ labels[:, 1] = 1 - labels[:, 1]
+
+ # Cutouts
+ # labels = cutout(img, labels, p=0.5)
+ # nl = len(labels) # update after cutout
+
+ labels_out = torch.zeros((nl, 6))
+ if nl:
+ labels_out[:, 1:] = torch.from_numpy(labels)
+
+ # Convert
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
+ img = np.ascontiguousarray(img)
+
+ return torch.from_numpy(img), labels_out, self.im_files[index], shapes
+
+ def load_image(self, i):
+ # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw)
+ im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],
+ if im is None: # not cached in RAM
+ if fn.exists(): # load npy
+ im = np.load(fn)
+ else: # read image
+ im = cv2.imread(f) # BGR
+ assert im is not None, f'Image Not Found {f}'
+ h0, w0 = im.shape[:2] # orig hw
+ r = self.img_size / max(h0, w0) # ratio
+ if r != 1: # if sizes are not equal
+ interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA
+ im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=interp)
+ return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
+ return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized
+
+ def cache_images_to_disk(self, i):
+ # Saves an image as an *.npy file for faster loading
+ f = self.npy_files[i]
+ if not f.exists():
+ np.save(f.as_posix(), cv2.imread(self.im_files[i]))
+
+ def load_mosaic(self, index):
+ # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
+ labels4, segments4 = [], []
+ s = self.img_size
+ yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
+ random.shuffle(indices)
+ for i, index in enumerate(indices):
+ # Load image
+ img, _, (h, w) = self.load_image(index)
+
+ # place img in img4
+ if i == 0: # top left
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
+ elif i == 1: # top right
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
+ elif i == 2: # bottom left
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
+ elif i == 3: # bottom right
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
+
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
+ padw = x1a - x1b
+ padh = y1a - y1b
+
+ # Labels
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
+ if labels.size:
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
+ labels4.append(labels)
+ segments4.extend(segments)
+
+ # Concat/clip labels
+ labels4 = np.concatenate(labels4, 0)
+ for x in (labels4[:, 1:], *segments4):
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
+ # img4, labels4 = replicate(img4, labels4) # replicate
+
+ # Augment
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
+ img4, labels4 = random_perspective(img4,
+ labels4,
+ segments4,
+ degrees=self.hyp['degrees'],
+ translate=self.hyp['translate'],
+ scale=self.hyp['scale'],
+ shear=self.hyp['shear'],
+ perspective=self.hyp['perspective'],
+ border=self.mosaic_border) # border to remove
+
+ return img4, labels4
+
+ def load_mosaic9(self, index):
+ # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic
+ labels9, segments9 = [], []
+ s = self.img_size
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
+ random.shuffle(indices)
+ hp, wp = -1, -1 # height, width previous
+ for i, index in enumerate(indices):
+ # Load image
+ img, _, (h, w) = self.load_image(index)
+
+ # place img in img9
+ if i == 0: # center
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
+ h0, w0 = h, w
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
+ elif i == 1: # top
+ c = s, s - h, s + w, s
+ elif i == 2: # top right
+ c = s + wp, s - h, s + wp + w, s
+ elif i == 3: # right
+ c = s + w0, s, s + w0 + w, s + h
+ elif i == 4: # bottom right
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
+ elif i == 5: # bottom
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
+ elif i == 6: # bottom left
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
+ elif i == 7: # left
+ c = s - w, s + h0 - h, s, s + h0
+ elif i == 8: # top left
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
+
+ padx, pady = c[:2]
+ x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
+
+ # Labels
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
+ if labels.size:
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
+ labels9.append(labels)
+ segments9.extend(segments)
+
+ # Image
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
+ hp, wp = h, w # height, width previous
+
+ # Offset
+ yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
+
+ # Concat/clip labels
+ labels9 = np.concatenate(labels9, 0)
+ labels9[:, [1, 3]] -= xc
+ labels9[:, [2, 4]] -= yc
+ c = np.array([xc, yc]) # centers
+ segments9 = [x - c for x in segments9]
+
+ for x in (labels9[:, 1:], *segments9):
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
+ # img9, labels9 = replicate(img9, labels9) # replicate
+
+ # Augment
+ img9, labels9 = random_perspective(img9,
+ labels9,
+ segments9,
+ degrees=self.hyp['degrees'],
+ translate=self.hyp['translate'],
+ scale=self.hyp['scale'],
+ shear=self.hyp['shear'],
+ perspective=self.hyp['perspective'],
+ border=self.mosaic_border) # border to remove
+
+ return img9, labels9
+
+ @staticmethod
+ def collate_fn(batch):
+ im, label, path, shapes = zip(*batch) # transposed
+ for i, lb in enumerate(label):
+ lb[:, 0] = i # add target image index for build_targets()
+ return torch.stack(im, 0), torch.cat(label, 0), path, shapes
+
+ @staticmethod
+ def collate_fn4(batch):
+ img, label, path, shapes = zip(*batch) # transposed
+ n = len(shapes) // 4
+ im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
+
+ ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])
+ wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])
+ s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
+ i *= 4
+ if random.random() < 0.5:
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear',
+ align_corners=False)[0].type(img[i].type())
+ lb = label[i]
+ else:
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
+ lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
+ im4.append(im)
+ label4.append(lb)
+
+ for i, lb in enumerate(label4):
+ lb[:, 0] = i # add target image index for build_targets()
+
+ return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4
+
+
+# Ancillary functions --------------------------------------------------------------------------------------------------
+def flatten_recursive(path=DATASETS_DIR / 'coco128'):
+ # Flatten a recursive directory by bringing all files to top level
+ new_path = Path(f'{str(path)}_flat')
+ if os.path.exists(new_path):
+ shutil.rmtree(new_path) # delete output folder
+ os.makedirs(new_path) # make new output folder
+ for file in tqdm(glob.glob(f'{str(Path(path))}/**/*.*', recursive=True)):
+ shutil.copyfile(file, new_path / Path(file).name)
+
+
+def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.dataloaders import *; extract_boxes()
+ # Convert detection dataset into classification dataset, with one directory per class
+ path = Path(path) # images dir
+ shutil.rmtree(path / 'classification') if (path / 'classification').is_dir() else None # remove existing
+ files = list(path.rglob('*.*'))
+ n = len(files) # number of files
+ for im_file in tqdm(files, total=n):
+ if im_file.suffix[1:] in IMG_FORMATS:
+ # image
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
+ h, w = im.shape[:2]
+
+ # labels
+ lb_file = Path(img2label_paths([str(im_file)])[0])
+ if Path(lb_file).exists():
+ with open(lb_file) as f:
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
+
+ for j, x in enumerate(lb):
+ c = int(x[0]) # class
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
+ if not f.parent.is_dir():
+ f.parent.mkdir(parents=True)
+
+ b = x[1:] * [w, h, w, h] # box
+ # b[2:] = b[2:].max() # rectangle to square
+ b[2:] = b[2:] * 1.2 + 3 # pad
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
+
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
+
+
+def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
+ Usage: from utils.dataloaders import *; autosplit()
+ Arguments
+ path: Path to images directory
+ weights: Train, val, test weights (list, tuple)
+ annotated_only: Only use images with an annotated txt file
+ """
+ path = Path(path) # images dir
+ files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only
+ n = len(files) # number of files
+ random.seed(0) # for reproducibility
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
+
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
+ [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
+
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
+ for i, img in tqdm(zip(indices, files), total=n):
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
+ with open(path.parent / txt[i], 'a') as f:
+ f.write(f'./{img.relative_to(path.parent).as_posix()}' + '\n') # add image to txt file
+
+
+def verify_image_label(args):
+ # Verify one image-label pair
+ im_file, lb_file, prefix = args
+ nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
+ try:
+ # verify images
+ im = Image.open(im_file)
+ im.verify() # PIL verify
+ shape = exif_size(im) # image size
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
+ assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
+ if im.format.lower() in ('jpg', 'jpeg'):
+ with open(im_file, 'rb') as f:
+ f.seek(-2, 2)
+ if f.read() != b'\xff\xd9': # corrupt JPEG
+ ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
+ msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
+
+ # verify labels
+ if os.path.isfile(lb_file):
+ nf = 1 # label found
+ with open(lb_file) as f:
+ lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
+ if any(len(x) > 6 for x in lb): # is segment
+ classes = np.array([x[0] for x in lb], dtype=np.float32)
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
+ lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
+ lb = np.array(lb, dtype=np.float32)
+ nl = len(lb)
+ if nl:
+ assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'
+ assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'
+ assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'
+ _, i = np.unique(lb, axis=0, return_index=True)
+ if len(i) < nl: # duplicate row check
+ lb = lb[i] # remove duplicates
+ if segments:
+ segments = segments[i]
+ msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'
+ else:
+ ne = 1 # label empty
+ lb = np.zeros((0, 5), dtype=np.float32)
+ else:
+ nm = 1 # label missing
+ lb = np.zeros((0, 5), dtype=np.float32)
+ return im_file, lb, shape, segments, nm, nf, ne, nc, msg
+ except Exception as e:
+ nc = 1
+ msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'
+ return [None, None, None, None, nm, nf, ne, nc, msg]
+
+
+class HUBDatasetStats():
+ """ Return dataset statistics dictionary with images and instances counts per split per class
+ To run in parent directory: export PYTHONPATH="$PWD/yolov5"
+ Usage1: from utils.dataloaders import *; HUBDatasetStats('coco128.yaml', autodownload=True)
+ Usage2: from utils.dataloaders import *; HUBDatasetStats('path/to/coco128_with_yaml.zip')
+ Arguments
+ path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
+ autodownload: Attempt to download dataset if not found locally
+ """
+
+ def __init__(self, path='coco128.yaml', autodownload=False):
+ # Initialize class
+ zipped, data_dir, yaml_path = self._unzip(Path(path))
+ try:
+ with open(check_yaml(yaml_path), errors='ignore') as f:
+ data = yaml.safe_load(f) # data dict
+ if zipped:
+ data['path'] = data_dir
+ except Exception as e:
+ raise Exception("error/HUB/dataset_stats/yaml_load") from e
+
+ check_dataset(data, autodownload) # download dataset if missing
+ self.hub_dir = Path(data['path'] + '-hub')
+ self.im_dir = self.hub_dir / 'images'
+ self.im_dir.mkdir(parents=True, exist_ok=True) # makes /images
+ self.stats = {'nc': data['nc'], 'names': list(data['names'].values())} # statistics dictionary
+ self.data = data
+
+ @staticmethod
+ def _find_yaml(dir):
+ # Return data.yaml file
+ files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml')) # try root level first and then recursive
+ assert files, f'No *.yaml file found in {dir}'
+ if len(files) > 1:
+ files = [f for f in files if f.stem == dir.stem] # prefer *.yaml files that match dir name
+ assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed'
+ assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}'
+ return files[0]
+
+ def _unzip(self, path):
+ # Unzip data.zip
+ if not str(path).endswith('.zip'): # path is data.yaml
+ return False, None, path
+ assert Path(path).is_file(), f'Error unzipping {path}, file not found'
+ ZipFile(path).extractall(path=path.parent) # unzip
+ dir = path.with_suffix('') # dataset directory == zip name
+ assert dir.is_dir(), f'Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/'
+ return True, str(dir), self._find_yaml(dir) # zipped, data_dir, yaml_path
+
+ def _hub_ops(self, f, max_dim=1920):
+ # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing
+ f_new = self.im_dir / Path(f).name # dataset-hub image filename
+ try: # use PIL
+ im = Image.open(f)
+ r = max_dim / max(im.height, im.width) # ratio
+ if r < 1.0: # image too large
+ im = im.resize((int(im.width * r), int(im.height * r)))
+ im.save(f_new, 'JPEG', quality=50, optimize=True) # save
+ except Exception as e: # use OpenCV
+ print(f'WARNING: HUB ops PIL failure {f}: {e}')
+ im = cv2.imread(f)
+ im_height, im_width = im.shape[:2]
+ r = max_dim / max(im_height, im_width) # ratio
+ if r < 1.0: # image too large
+ im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)
+ cv2.imwrite(str(f_new), im)
+
+ def get_json(self, save=False, verbose=False):
+ # Return dataset JSON for Ultralytics HUB
+ def _round(labels):
+ # Update labels to integer class and 6 decimal place floats
+ return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
+
+ for split in 'train', 'val', 'test':
+ if self.data.get(split) is None:
+ self.stats[split] = None # i.e. no test set
+ continue
+ dataset = LoadImagesAndLabels(self.data[split]) # load dataset
+ x = np.array([
+ np.bincount(label[:, 0].astype(int), minlength=self.data['nc'])
+ for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics')]) # shape(128x80)
+ self.stats[split] = {
+ 'instance_stats': {
+ 'total': int(x.sum()),
+ 'per_class': x.sum(0).tolist()},
+ 'image_stats': {
+ 'total': dataset.n,
+ 'unlabelled': int(np.all(x == 0, 1).sum()),
+ 'per_class': (x > 0).sum(0).tolist()},
+ 'labels': [{
+ str(Path(k).name): _round(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)]}
+
+ # Save, print and return
+ if save:
+ stats_path = self.hub_dir / 'stats.json'
+ print(f'Saving {stats_path.resolve()}...')
+ with open(stats_path, 'w') as f:
+ json.dump(self.stats, f) # save stats.json
+ if verbose:
+ print(json.dumps(self.stats, indent=2, sort_keys=False))
+ return self.stats
+
+ def process_images(self):
+ # Compress images for Ultralytics HUB
+ for split in 'train', 'val', 'test':
+ if self.data.get(split) is None:
+ continue
+ dataset = LoadImagesAndLabels(self.data[split]) # load dataset
+ desc = f'{split} images'
+ for _ in tqdm(ThreadPool(NUM_THREADS).imap(self._hub_ops, dataset.im_files), total=dataset.n, desc=desc):
+ pass
+ print(f'Done. All images saved to {self.im_dir}')
+ return self.im_dir
+
+
+# Classification dataloaders -------------------------------------------------------------------------------------------
+class ClassificationDataset(torchvision.datasets.ImageFolder):
+ """
+ YOLOv5 Classification Dataset.
+ Arguments
+ root: Dataset path
+ transform: torchvision transforms, used by default
+ album_transform: Albumentations transforms, used if installed
+ """
+
+ def __init__(self, root, augment, imgsz, cache=False):
+ super().__init__(root=root)
+ self.torch_transforms = classify_transforms(imgsz)
+ self.album_transforms = classify_albumentations(augment, imgsz) if augment else None
+ self.cache_ram = cache is True or cache == 'ram'
+ self.cache_disk = cache == 'disk'
+ self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples] # file, index, npy, im
+
+ def __getitem__(self, i):
+ f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
+ if self.album_transforms:
+ if self.cache_ram and im is None:
+ im = self.samples[i][3] = cv2.imread(f)
+ elif self.cache_disk:
+ if not fn.exists(): # load npy
+ np.save(fn.as_posix(), cv2.imread(f))
+ im = np.load(fn)
+ else: # read image
+ im = cv2.imread(f) # BGR
+ sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))["image"]
+ else:
+ sample = self.torch_transforms(self.loader(f))
+ return sample, j
+
+
+def create_classification_dataloader(path,
+ imgsz=224,
+ batch_size=16,
+ augment=True,
+ cache=False,
+ rank=-1,
+ workers=8,
+ shuffle=True):
+ # Returns Dataloader object to be used with YOLOv5 Classifier
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
+ dataset = ClassificationDataset(root=path, imgsz=imgsz, augment=augment, cache=cache)
+ batch_size = min(batch_size, len(dataset))
+ nd = torch.cuda.device_count()
+ nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])
+ sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
+ generator = torch.Generator()
+ generator.manual_seed(0)
+ return InfiniteDataLoader(dataset,
+ batch_size=batch_size,
+ shuffle=shuffle and sampler is None,
+ num_workers=nw,
+ sampler=sampler,
+ pin_memory=True,
+ worker_init_fn=seed_worker,
+ generator=generator) # or DataLoader(persistent_workers=True)
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/downloads.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/downloads.py
new file mode 100644
index 000000000..c4d4a85c3
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/downloads.py
@@ -0,0 +1,180 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Download utils
+"""
+
+import logging
+import os
+import platform
+import subprocess
+import time
+import urllib
+from pathlib import Path
+from zipfile import ZipFile
+
+import requests
+import torch
+
+
+def is_url(url, check_online=True):
+ # Check if online file exists
+ try:
+ url = str(url)
+ result = urllib.parse.urlparse(url)
+ assert all([result.scheme, result.netloc, result.path]) # check if is url
+ return (urllib.request.urlopen(url).getcode() == 200) if check_online else True # check if exists online
+ except (AssertionError, urllib.request.HTTPError):
+ return False
+
+
+def gsutil_getsize(url=''):
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
+
+
+def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
+ # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
+ from utils.general import LOGGER
+
+ file = Path(file)
+ assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
+ try: # url1
+ LOGGER.info(f'Downloading {url} to {file}...')
+ torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
+ assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
+ except Exception as e: # url2
+ file.unlink(missing_ok=True) # remove partial downloads
+ LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
+ os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
+ finally:
+ if not file.exists() or file.stat().st_size < min_bytes: # check
+ file.unlink(missing_ok=True) # remove partial downloads
+ LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
+ LOGGER.info('')
+
+
+def attempt_download(file, repo='ultralytics/yolov5', release='v6.2'):
+ # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.2', etc.
+ from utils.general import LOGGER
+
+ def github_assets(repository, version='latest'):
+ # Return GitHub repo tag (i.e. 'v6.2') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...])
+ if version != 'latest':
+ version = f'tags/{version}' # i.e. tags/v6.2
+ response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api
+ return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets
+
+ file = Path(str(file).strip().replace("'", ''))
+ if not file.exists():
+ # URL specified
+ name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
+ if str(file).startswith(('http:/', 'https:/')): # download
+ url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
+ file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
+ if Path(file).is_file():
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
+ else:
+ safe_download(file=file, url=url, min_bytes=1E5)
+ return file
+
+ # GitHub assets
+ assets = [
+ 'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt',
+ 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
+ try:
+ tag, assets = github_assets(repo, release)
+ except Exception:
+ try:
+ tag, assets = github_assets(repo) # latest release
+ except Exception:
+ try:
+ tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
+ except Exception:
+ tag = release
+
+ file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
+ if name in assets:
+ url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror
+ safe_download(
+ file,
+ url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
+ url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}', # backup url (optional)
+ min_bytes=1E5,
+ error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}')
+
+ return str(file)
+
+
+def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
+ # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
+ t = time.time()
+ file = Path(file)
+ cookie = Path('cookie') # gdrive cookie
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
+ file.unlink(missing_ok=True) # remove existing file
+ cookie.unlink(missing_ok=True) # remove existing cookie
+
+ # Attempt file download
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
+ os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
+ if os.path.exists('cookie'): # large file
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
+ else: # small file
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
+ r = os.system(s) # execute, capture return
+ cookie.unlink(missing_ok=True) # remove existing cookie
+
+ # Error check
+ if r != 0:
+ file.unlink(missing_ok=True) # remove partial
+ print('Download error ') # raise Exception('Download error')
+ return r
+
+ # Unzip if archive
+ if file.suffix == '.zip':
+ print('unzipping... ', end='')
+ ZipFile(file).extractall(path=file.parent) # unzip
+ file.unlink() # remove zip
+
+ print(f'Done ({time.time() - t:.1f}s)')
+ return r
+
+
+def get_token(cookie="./cookie"):
+ with open(cookie) as f:
+ for line in f:
+ if "download" in line:
+ return line.split()[-1]
+ return ""
+
+
+# Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------
+#
+#
+# def upload_blob(bucket_name, source_file_name, destination_blob_name):
+# # Uploads a file to a bucket
+# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
+#
+# storage_client = storage.Client()
+# bucket = storage_client.get_bucket(bucket_name)
+# blob = bucket.blob(destination_blob_name)
+#
+# blob.upload_from_filename(source_file_name)
+#
+# print('File {} uploaded to {}.'.format(
+# source_file_name,
+# destination_blob_name))
+#
+#
+# def download_blob(bucket_name, source_blob_name, destination_file_name):
+# # Uploads a blob from a bucket
+# storage_client = storage.Client()
+# bucket = storage_client.get_bucket(bucket_name)
+# blob = bucket.blob(source_blob_name)
+#
+# blob.download_to_filename(destination_file_name)
+#
+# print('Blob {} downloaded to {}.'.format(
+# source_blob_name,
+# destination_file_name))
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/general.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/general.py
new file mode 100755
index 000000000..42d000918
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/general.py
@@ -0,0 +1,1060 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+General utils
+"""
+
+import contextlib
+import glob
+import inspect
+import logging
+import math
+import os
+import platform
+import random
+import re
+import shutil
+import signal
+import sys
+import threading
+import time
+import urllib
+from datetime import datetime
+from itertools import repeat
+from multiprocessing.pool import ThreadPool
+from pathlib import Path
+from subprocess import check_output
+from typing import Optional
+from zipfile import ZipFile
+
+import cv2
+import numpy as np
+import pandas as pd
+import pkg_resources as pkg
+import torch
+import torchvision
+import yaml
+
+from utils.downloads import gsutil_getsize
+from utils.metrics import box_iou, fitness
+
+FILE = Path(__file__).resolve()
+ROOT = FILE.parents[1] # YOLOv5 root directory
+RANK = int(os.getenv('RANK', -1))
+
+# Settings
+DATASETS_DIR = ROOT.parent / 'datasets' # YOLOv5 datasets directory
+NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads
+AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode
+VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode
+FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf
+
+torch.set_printoptions(linewidth=320, precision=5, profile='long')
+np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
+pd.options.display.max_columns = 10
+cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
+os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads
+os.environ['OMP_NUM_THREADS'] = '1' if platform.system() == 'darwin' else str(NUM_THREADS) # OpenMP (PyTorch and SciPy)
+
+
+def is_ascii(s=''):
+ # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7)
+ s = str(s) # convert list, tuple, None, etc. to str
+ return len(s.encode().decode('ascii', 'ignore')) == len(s)
+
+
+def is_chinese(s='人工智能'):
+ # Is string composed of any Chinese characters?
+ return bool(re.search('[\u4e00-\u9fff]', str(s)))
+
+
+def is_colab():
+ # Is environment a Google Colab instance?
+ return 'COLAB_GPU' in os.environ
+
+
+def is_kaggle():
+ # Is environment a Kaggle Notebook?
+ return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'
+
+
+def is_docker() -> bool:
+ """Check if the process runs inside a docker container."""
+ if Path("/.dockerenv").exists():
+ return True
+ try: # check if docker is in control groups
+ with open("/proc/self/cgroup") as file:
+ return any("docker" in line for line in file)
+ except OSError:
+ return False
+
+
+def is_writeable(dir, test=False):
+ # Return True if directory has write permissions, test opening a file with write permissions if test=True
+ if not test:
+ return os.access(dir, os.W_OK) # possible issues on Windows
+ file = Path(dir) / 'tmp.txt'
+ try:
+ with open(file, 'w'): # open file with write permissions
+ pass
+ file.unlink() # remove file
+ return True
+ except OSError:
+ return False
+
+
+def set_logging(name=None, verbose=VERBOSE):
+ # Sets level and returns logger
+ if is_kaggle() or is_colab():
+ for h in logging.root.handlers:
+ logging.root.removeHandler(h) # remove all handlers associated with the root logger object
+ rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
+ level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
+ log = logging.getLogger(name)
+ log.setLevel(level)
+ handler = logging.StreamHandler()
+ handler.setFormatter(logging.Formatter("%(message)s"))
+ handler.setLevel(level)
+ log.addHandler(handler)
+
+
+set_logging() # run before defining LOGGER
+LOGGER = logging.getLogger("yolov5") # define globally (used in train.py, val.py, detect.py, etc.)
+if platform.system() == 'Windows':
+ for fn in LOGGER.info, LOGGER.warning:
+ setattr(LOGGER, fn.__name__, lambda x: fn(emojis(x))) # emoji safe logging
+
+
+def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):
+ # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.
+ env = os.getenv(env_var)
+ if env:
+ path = Path(env) # use environment variable
+ else:
+ cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs
+ path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir
+ path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable
+ path.mkdir(exist_ok=True) # make if required
+ return path
+
+
+CONFIG_DIR = user_config_dir() # Ultralytics settings dir
+
+
+class Profile(contextlib.ContextDecorator):
+ # YOLOv5 Profile class. Usage: @Profile() decorator or 'with Profile():' context manager
+ def __init__(self, t=0.0):
+ self.t = t
+ self.cuda = torch.cuda.is_available()
+
+ def __enter__(self):
+ self.start = self.time()
+
+ def __exit__(self, type, value, traceback):
+ self.dt = self.time() - self.start # delta-time
+ self.t += self.dt # accumulate dt
+
+ def time(self):
+ if self.cuda:
+ torch.cuda.synchronize()
+ return time.time()
+
+
+class Timeout(contextlib.ContextDecorator):
+ # YOLOv5 Timeout class. Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
+ def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):
+ self.seconds = int(seconds)
+ self.timeout_message = timeout_msg
+ self.suppress = bool(suppress_timeout_errors)
+
+ def _timeout_handler(self, signum, frame):
+ raise TimeoutError(self.timeout_message)
+
+ def __enter__(self):
+ if platform.system() != 'Windows': # not supported on Windows
+ signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM
+ signal.alarm(self.seconds) # start countdown for SIGALRM to be raised
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if platform.system() != 'Windows':
+ signal.alarm(0) # Cancel SIGALRM if it's scheduled
+ if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError
+ return True
+
+
+class WorkingDirectory(contextlib.ContextDecorator):
+ # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager
+ def __init__(self, new_dir):
+ self.dir = new_dir # new dir
+ self.cwd = Path.cwd().resolve() # current dir
+
+ def __enter__(self):
+ os.chdir(self.dir)
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ os.chdir(self.cwd)
+
+
+def try_except(func):
+ # try-except function. Usage: @try_except decorator
+ def handler(*args, **kwargs):
+ try:
+ func(*args, **kwargs)
+ except Exception as e:
+ print(e)
+
+ return handler
+
+
+def threaded(func):
+ # Multi-threads a target function and returns thread. Usage: @threaded decorator
+ def wrapper(*args, **kwargs):
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
+ thread.start()
+ return thread
+
+ return wrapper
+
+
+def methods(instance):
+ # Get class/instance methods
+ return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]
+
+
+def print_args(args: Optional[dict] = None, show_file=True, show_fcn=False):
+ # Print function arguments (optional args dict)
+ x = inspect.currentframe().f_back # previous frame
+ file, _, fcn, _, _ = inspect.getframeinfo(x)
+ if args is None: # get args automatically
+ args, _, _, frm = inspect.getargvalues(x)
+ args = {k: v for k, v in frm.items() if k in args}
+ try:
+ file = Path(file).resolve().relative_to(ROOT).with_suffix('')
+ except ValueError:
+ file = Path(file).stem
+ s = (f'{file}: ' if show_file else '') + (f'{fcn}: ' if show_fcn else '')
+ LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items()))
+
+
+def init_seeds(seed=0, deterministic=False):
+ # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html
+ # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible
+ import torch.backends.cudnn as cudnn
+
+ if deterministic and check_version(torch.__version__, '1.12.0'): # https://github.com/ultralytics/yolov5/pull/8213
+ torch.use_deterministic_algorithms(True)
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
+ os.environ['PYTHONHASHSEED'] = str(seed)
+
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False)
+ torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed) # for Multi-GPU, exception safe
+
+
+def intersect_dicts(da, db, exclude=()):
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
+
+
+def get_latest_run(search_dir='.'):
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
+ return max(last_list, key=os.path.getctime) if last_list else ''
+
+
+def emojis(str=''):
+ # Return platform-dependent emoji-safe version of string
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
+
+
+def file_age(path=__file__):
+ # Return days since last file update
+ dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)) # delta
+ return dt.days # + dt.seconds / 86400 # fractional days
+
+
+def file_date(path=__file__):
+ # Return human-readable file modification date, i.e. '2021-3-26'
+ t = datetime.fromtimestamp(Path(path).stat().st_mtime)
+ return f'{t.year}-{t.month}-{t.day}'
+
+
+def file_size(path):
+ # Return file/dir size (MB)
+ mb = 1 << 20 # bytes to MiB (1024 ** 2)
+ path = Path(path)
+ if path.is_file():
+ return path.stat().st_size / mb
+ elif path.is_dir():
+ return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb
+ else:
+ return 0.0
+
+
+def check_online():
+ # Check internet connectivity
+ import socket
+ try:
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility
+ return True
+ except OSError:
+ return False
+
+
+def git_describe(path=ROOT): # path must be a directory
+ # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
+ try:
+ assert (Path(path) / '.git').is_dir()
+ return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]
+ except Exception:
+ return ''
+
+
+@try_except
+@WorkingDirectory(ROOT)
+def check_git_status(repo='ultralytics/yolov5'):
+ # YOLOv5 status check, recommend 'git pull' if code is out of date
+ url = f'https://github.com/{repo}'
+ msg = f', for updates see {url}'
+ s = colorstr('github: ') # string
+ assert Path('.git').exists(), s + 'skipping check (not a git repository)' + msg
+ assert check_online(), s + 'skipping check (offline)' + msg
+
+ splits = re.split(pattern=r'\s', string=check_output('git remote -v', shell=True).decode())
+ matches = [repo in s for s in splits]
+ if any(matches):
+ remote = splits[matches.index(True) - 1]
+ else:
+ remote = 'ultralytics'
+ check_output(f'git remote add {remote} {url}', shell=True)
+ check_output(f'git fetch {remote}', shell=True, timeout=5) # git fetch
+ branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
+ n = int(check_output(f'git rev-list {branch}..{remote}/master --count', shell=True)) # commits behind
+ if n > 0:
+ pull = 'git pull' if remote == 'origin' else f'git pull {remote} master'
+ s += f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `{pull}` or `git clone {url}` to update."
+ else:
+ s += f'up to date with {url} ✅'
+ LOGGER.info(s)
+
+
+def check_python(minimum='3.7.0'):
+ # Check current python version vs. required python version
+ check_version(platform.python_version(), minimum, name='Python ', hard=True)
+
+
+def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):
+ # Check version vs. required version
+ current, minimum = (pkg.parse_version(x) for x in (current, minimum))
+ result = (current == minimum) if pinned else (current >= minimum) # bool
+ s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string
+ if hard:
+ assert result, s # assert min requirements met
+ if verbose and not result:
+ LOGGER.warning(s)
+ return result
+
+
+@try_except
+def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=()):
+ # Check installed dependencies meet YOLOv5 requirements (pass *.txt file or list of packages)
+ prefix = colorstr('red', 'bold', 'requirements:')
+ check_python() # check python version
+ if isinstance(requirements, (str, Path)): # requirements.txt file
+ file = Path(requirements)
+ assert file.exists(), f"{prefix} {file.resolve()} not found, check failed."
+ with file.open() as f:
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]
+ else: # list or tuple of packages
+ requirements = [x for x in requirements if x not in exclude]
+
+ n = 0 # number of packages updates
+ for i, r in enumerate(requirements):
+ try:
+ pkg.require(r)
+ except Exception: # DistributionNotFound or VersionConflict if requirements not met
+ s = f"{prefix} {r} not found and is required by YOLOv5"
+ if install and AUTOINSTALL: # check environment variable
+ LOGGER.info(f"{s}, attempting auto-update...")
+ try:
+ assert check_online(), f"'pip install {r}' skipped (offline)"
+ LOGGER.info(check_output(f'pip install "{r}" {cmds[i] if cmds else ""}', shell=True).decode())
+ n += 1
+ except Exception as e:
+ LOGGER.warning(f'{prefix} {e}')
+ else:
+ LOGGER.info(f'{s}. Please install and rerun your command.')
+
+ if n: # if packages updated
+ source = file.resolve() if 'file' in locals() else requirements
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
+ LOGGER.info(s)
+
+
+def check_img_size(imgsz, s=32, floor=0):
+ # Verify image size is a multiple of stride s in each dimension
+ if isinstance(imgsz, int): # integer i.e. img_size=640
+ new_size = max(make_divisible(imgsz, int(s)), floor)
+ else: # list i.e. img_size=[640, 480]
+ imgsz = list(imgsz) # convert to list if tuple
+ new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]
+ if new_size != imgsz:
+ LOGGER.warning(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')
+ return new_size
+
+
+def check_imshow():
+ # Check if environment supports image displays
+ try:
+ assert not is_docker(), 'cv2.imshow() is disabled in Docker environments'
+ assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments'
+ cv2.imshow('test', np.zeros((1, 1, 3)))
+ cv2.waitKey(1)
+ cv2.destroyAllWindows()
+ cv2.waitKey(1)
+ return True
+ except Exception as e:
+ LOGGER.warning(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')
+ return False
+
+
+def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''):
+ # Check file(s) for acceptable suffix
+ if file and suffix:
+ if isinstance(suffix, str):
+ suffix = [suffix]
+ for f in file if isinstance(file, (list, tuple)) else [file]:
+ s = Path(f).suffix.lower() # file suffix
+ if len(s):
+ assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}"
+
+
+def check_yaml(file, suffix=('.yaml', '.yml')):
+ # Search/download YAML file (if necessary) and return path, checking suffix
+ return check_file(file, suffix)
+
+
+def check_file(file, suffix=''):
+ # Search/download file (if necessary) and return path
+ check_suffix(file, suffix) # optional
+ file = str(file) # convert to str()
+ if Path(file).is_file() or not file: # exists
+ return file
+ elif file.startswith(('http:/', 'https:/')): # download
+ url = file # warning: Pathlib turns :// -> :/
+ file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth
+ if Path(file).is_file():
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
+ else:
+ LOGGER.info(f'Downloading {url} to {file}...')
+ torch.hub.download_url_to_file(url, file)
+ assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check
+ return file
+ elif file.startswith('clearml://'): # ClearML Dataset ID
+ assert 'clearml' in sys.modules, "ClearML is not installed, so cannot use ClearML dataset. Try running 'pip install clearml'."
+ return file
+ else: # search
+ files = []
+ for d in 'data', 'models', 'utils': # search directories
+ files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file
+ assert len(files), f'File not found: {file}' # assert file was found
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
+ return files[0] # return file
+
+
+def check_font(font=FONT, progress=False):
+ # Download font to CONFIG_DIR if necessary
+ font = Path(font)
+ file = CONFIG_DIR / font.name
+ if not font.exists() and not file.exists():
+ url = "https://ultralytics.com/assets/" + font.name
+ LOGGER.info(f'Downloading {url} to {file}...')
+ torch.hub.download_url_to_file(url, str(file), progress=progress)
+
+
+def check_dataset(data, autodownload=True):
+ # Download, check and/or unzip dataset if not found locally
+
+ # Download (optional)
+ extract_dir = ''
+ if isinstance(data, (str, Path)) and str(data).endswith('.zip'): # i.e. gs://bucket/dir/coco128.zip
+ download(data, dir=f'{DATASETS_DIR}/{Path(data).stem}', unzip=True, delete=False, curl=False, threads=1)
+ data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml'))
+ extract_dir, autodownload = data.parent, False
+
+ # Read yaml (optional)
+ if isinstance(data, (str, Path)):
+ with open(data, errors='ignore') as f:
+ data = yaml.safe_load(f) # dictionary
+
+ # Checks
+ for k in 'train', 'val', 'names':
+ assert k in data, f"data.yaml '{k}:' field missing ❌"
+ if isinstance(data['names'], (list, tuple)): # old array format
+ data['names'] = dict(enumerate(data['names'])) # convert to dict
+ data['nc'] = len(data['names'])
+
+ # Resolve paths
+ path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.'
+ if not path.is_absolute():
+ path = (ROOT / path).resolve()
+ for k in 'train', 'val', 'test':
+ if data.get(k): # prepend path
+ data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]]
+
+ # Parse yaml
+ train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))
+ if val:
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
+ if not all(x.exists() for x in val):
+ LOGGER.info('\nDataset not found ⚠️, missing paths %s' % [str(x) for x in val if not x.exists()])
+ if not s or not autodownload:
+ raise Exception('Dataset not found ❌')
+ t = time.time()
+ root = path.parent if 'path' in data else '..' # unzip directory i.e. '../'
+ if s.startswith('http') and s.endswith('.zip'): # URL
+ f = Path(s).name # filename
+ LOGGER.info(f'Downloading {s} to {f}...')
+ torch.hub.download_url_to_file(s, f)
+ Path(root).mkdir(parents=True, exist_ok=True) # create root
+ ZipFile(f).extractall(path=root) # unzip
+ Path(f).unlink() # remove zip
+ r = None # success
+ elif s.startswith('bash '): # bash script
+ LOGGER.info(f'Running {s} ...')
+ r = os.system(s)
+ else: # python script
+ r = exec(s, {'yaml': data}) # return None
+ dt = f'({round(time.time() - t, 1)}s)'
+ s = f"success ✅ {dt}, saved to {colorstr('bold', root)}" if r in (0, None) else f"failure {dt} ❌"
+ LOGGER.info(f"Dataset download {s}")
+ check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts
+ return data # dictionary
+
+
+def check_amp(model):
+ # Check PyTorch Automatic Mixed Precision (AMP) functionality. Return True on correct operation
+ from models.common import AutoShape, DetectMultiBackend
+
+ def amp_allclose(model, im):
+ # All close FP32 vs AMP results
+ m = AutoShape(model, verbose=False) # model
+ a = m(im).xywhn[0] # FP32 inference
+ m.amp = True
+ b = m(im).xywhn[0] # AMP inference
+ return a.shape == b.shape and torch.allclose(a, b, atol=0.1) # close to 10% absolute tolerance
+
+ prefix = colorstr('AMP: ')
+ device = next(model.parameters()).device # get model device
+ if device.type == 'cpu':
+ return False # AMP disabled on CPU
+ f = ROOT / 'data' / 'images' / 'bus.jpg' # image to check
+ im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if check_online() else np.ones((640, 640, 3))
+ try:
+ assert amp_allclose(model, im) or amp_allclose(DetectMultiBackend('yolov5n.pt', device), im)
+ LOGGER.info(f'{prefix}checks passed ✅')
+ return True
+ except Exception:
+ help_url = 'https://github.com/ultralytics/yolov5/issues/7908'
+ LOGGER.warning(f'{prefix}checks failed ❌, disabling Automatic Mixed Precision. See {help_url}')
+ return False
+
+
+def yaml_load(file='data.yaml'):
+ # Single-line safe yaml loading
+ with open(file, errors='ignore') as f:
+ return yaml.safe_load(f)
+
+
+def yaml_save(file='data.yaml', data={}):
+ # Single-line safe yaml saving
+ with open(file, 'w') as f:
+ yaml.safe_dump({k: str(v) if isinstance(v, Path) else v for k, v in data.items()}, f, sort_keys=False)
+
+
+def url2file(url):
+ # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt
+ url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/
+ return Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth
+
+
+def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3):
+ # Multi-threaded file download and unzip function, used in data.yaml for autodownload
+ def download_one(url, dir):
+ # Download 1 file
+ success = True
+ f = dir / Path(url).name # filename
+ if Path(url).is_file(): # exists in current path
+ Path(url).rename(f) # move to dir
+ elif not f.exists():
+ LOGGER.info(f'Downloading {url} to {f}...')
+ for i in range(retry + 1):
+ if curl:
+ s = 'sS' if threads > 1 else '' # silent
+ r = os.system(f'curl -{s}L "{url}" -o "{f}" --retry 9 -C -') # curl download with retry, continue
+ success = r == 0
+ else:
+ torch.hub.download_url_to_file(url, f, progress=threads == 1) # torch download
+ success = f.is_file()
+ if success:
+ break
+ elif i < retry:
+ LOGGER.warning(f'Download failure, retrying {i + 1}/{retry} {url}...')
+ else:
+ LOGGER.warning(f'Failed to download {url}...')
+
+ if unzip and success and f.suffix in ('.zip', '.tar', '.gz'):
+ LOGGER.info(f'Unzipping {f}...')
+ if f.suffix == '.zip':
+ ZipFile(f).extractall(path=dir) # unzip
+ elif f.suffix == '.tar':
+ os.system(f'tar xf {f} --directory {f.parent}') # unzip
+ elif f.suffix == '.gz':
+ os.system(f'tar xfz {f} --directory {f.parent}') # unzip
+ if delete:
+ f.unlink() # remove zip
+
+ dir = Path(dir)
+ dir.mkdir(parents=True, exist_ok=True) # make directory
+ if threads > 1:
+ pool = ThreadPool(threads)
+ pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded
+ pool.close()
+ pool.join()
+ else:
+ for u in [url] if isinstance(url, (str, Path)) else url:
+ download_one(u, dir)
+
+
+def make_divisible(x, divisor):
+ # Returns nearest x divisible by divisor
+ if isinstance(divisor, torch.Tensor):
+ divisor = int(divisor.max()) # to int
+ return math.ceil(x / divisor) * divisor
+
+
+def clean_str(s):
+ # Cleans a string by replacing special characters with underscore _
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
+
+
+def one_cycle(y1=0.0, y2=1.0, steps=100):
+ # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
+
+
+def colorstr(*input):
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
+ colors = {
+ 'black': '\033[30m', # basic colors
+ 'red': '\033[31m',
+ 'green': '\033[32m',
+ 'yellow': '\033[33m',
+ 'blue': '\033[34m',
+ 'magenta': '\033[35m',
+ 'cyan': '\033[36m',
+ 'white': '\033[37m',
+ 'bright_black': '\033[90m', # bright colors
+ 'bright_red': '\033[91m',
+ 'bright_green': '\033[92m',
+ 'bright_yellow': '\033[93m',
+ 'bright_blue': '\033[94m',
+ 'bright_magenta': '\033[95m',
+ 'bright_cyan': '\033[96m',
+ 'bright_white': '\033[97m',
+ 'end': '\033[0m', # misc
+ 'bold': '\033[1m',
+ 'underline': '\033[4m'}
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
+
+
+def labels_to_class_weights(labels, nc=80):
+ # Get class weights (inverse frequency) from training labels
+ if labels[0] is None: # no labels loaded
+ return torch.Tensor()
+
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
+ classes = labels[:, 0].astype(int) # labels = [class xywh]
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
+
+ # Prepend gridpoint count (for uCE training)
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
+
+ weights[weights == 0] = 1 # replace empty bins with 1
+ weights = 1 / weights # number of targets per class
+ weights /= weights.sum() # normalize
+ return torch.from_numpy(weights).float()
+
+
+def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
+ # Produces image weights based on class_weights and image contents
+ # Usage: index = random.choices(range(n), weights=image_weights, k=1) # weighted image sample
+ class_counts = np.array([np.bincount(x[:, 0].astype(int), minlength=nc) for x in labels])
+ return (class_weights.reshape(1, nc) * class_counts).sum(1)
+
+
+def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
+ return [
+ 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,
+ 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,
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
+
+
+def xyxy2xywh(x):
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
+ y[:, 2] = x[:, 2] - x[:, 0] # width
+ y[:, 3] = x[:, 3] - x[:, 1] # height
+ return y
+
+
+def xywh2xyxy(x):
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
+ return y
+
+
+def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
+ y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
+ y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
+ y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
+ y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
+ return y
+
+
+def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
+ if clip:
+ clip_coords(x, (h - eps, w - eps)) # warning: inplace clip
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
+ y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center
+ y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center
+ y[:, 2] = (x[:, 2] - x[:, 0]) / w # width
+ y[:, 3] = (x[:, 3] - x[:, 1]) / h # height
+ return y
+
+
+def xyn2xy(x, w=640, h=640, padw=0, padh=0):
+ # Convert normalized segments into pixel segments, shape (n,2)
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
+ y[:, 0] = w * x[:, 0] + padw # top left x
+ y[:, 1] = h * x[:, 1] + padh # top left y
+ return y
+
+
+def segment2box(segment, width=640, height=640):
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
+ x, y = segment.T # segment xy
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
+ x, y, = x[inside], y[inside]
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
+
+
+def segments2boxes(segments):
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
+ boxes = []
+ for s in segments:
+ x, y = s.T # segment xy
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
+
+
+def resample_segments(segments, n=1000):
+ # Up-sample an (n,2) segment
+ for i, s in enumerate(segments):
+ s = np.concatenate((s, s[0:1, :]), axis=0)
+ x = np.linspace(0, len(s) - 1, n)
+ xp = np.arange(len(s))
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
+ return segments
+
+
+def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
+ # Rescale coords (xyxy) from img1_shape to img0_shape
+ if ratio_pad is None: # calculate from img0_shape
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
+ else:
+ gain = ratio_pad[0][0]
+ pad = ratio_pad[1]
+
+ coords[:, [0, 2]] -= pad[0] # x padding
+ coords[:, [1, 3]] -= pad[1] # y padding
+ coords[:, :4] /= gain
+ clip_coords(coords, img0_shape)
+ return coords
+
+
+def clip_coords(boxes, shape):
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
+ if isinstance(boxes, torch.Tensor): # faster individually
+ boxes[:, 0].clamp_(0, shape[1]) # x1
+ boxes[:, 1].clamp_(0, shape[0]) # y1
+ boxes[:, 2].clamp_(0, shape[1]) # x2
+ boxes[:, 3].clamp_(0, shape[0]) # y2
+ else: # np.array (faster grouped)
+ boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2
+ boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2
+
+
+def non_max_suppression(prediction,
+ conf_thres=0.25,
+ iou_thres=0.45,
+ classes=None,
+ agnostic=False,
+ multi_label=False,
+ labels=(),
+ max_det=300):
+ """Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes
+
+ Returns:
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
+ """
+
+ bs = prediction.shape[0] # batch size
+ nc = prediction.shape[2] - 5 # number of classes
+ xc = prediction[..., 4] > conf_thres # candidates
+
+ # Checks
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
+
+ # Settings
+ # min_wh = 2 # (pixels) minimum box width and height
+ max_wh = 7680 # (pixels) maximum box width and height
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
+ time_limit = 0.3 + 0.03 * bs # seconds to quit after
+ redundant = True # require redundant detections
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
+ merge = False # use merge-NMS
+
+ t = time.time()
+ output = [torch.zeros((0, 6), device=prediction.device)] * bs
+ for xi, x in enumerate(prediction): # image index, image inference
+ # Apply constraints
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
+ x = x[xc[xi]] # confidence
+
+ # Cat apriori labels if autolabelling
+ if labels and len(labels[xi]):
+ lb = labels[xi]
+ v = torch.zeros((len(lb), nc + 5), device=x.device)
+ v[:, :4] = lb[:, 1:5] # box
+ v[:, 4] = 1.0 # conf
+ v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls
+ x = torch.cat((x, v), 0)
+
+ # If none remain process next image
+ if not x.shape[0]:
+ continue
+
+ # Compute conf
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
+
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
+ box = xywh2xyxy(x[:, :4])
+
+ # Detections matrix nx6 (xyxy, conf, cls)
+ if multi_label:
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
+ else: # best class only
+ conf, j = x[:, 5:].max(1, keepdim=True)
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
+
+ # Filter by class
+ if classes is not None:
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
+
+ # Apply finite constraint
+ # if not torch.isfinite(x).all():
+ # x = x[torch.isfinite(x).all(1)]
+
+ # Check shape
+ n = x.shape[0] # number of boxes
+ if not n: # no boxes
+ continue
+ elif n > max_nms: # excess boxes
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
+
+ # Batched NMS
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
+ if i.shape[0] > max_det: # limit detections
+ i = i[:max_det]
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
+ weights = iou * scores[None] # box weights
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
+ if redundant:
+ i = i[iou.sum(1) > 1] # require redundancy
+
+ output[xi] = x[i]
+ if (time.time() - t) > time_limit:
+ LOGGER.warning(f'WARNING: NMS time limit {time_limit:.3f}s exceeded')
+ break # time limit exceeded
+
+ return output
+
+
+def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
+ x = torch.load(f, map_location=torch.device('cpu'))
+ if x.get('ema'):
+ x['model'] = x['ema'] # replace model with ema
+ for k in 'optimizer', 'best_fitness', 'wandb_id', 'ema', 'updates': # keys
+ x[k] = None
+ x['epoch'] = -1
+ x['model'].half() # to FP16
+ for p in x['model'].parameters():
+ p.requires_grad = False
+ torch.save(x, s or f)
+ mb = os.path.getsize(s or f) / 1E6 # filesize
+ LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB")
+
+
+def print_mutation(results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')):
+ evolve_csv = save_dir / 'evolve.csv'
+ evolve_yaml = save_dir / 'hyp_evolve.yaml'
+ keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss',
+ 'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys()) # [results + hyps]
+ keys = tuple(x.strip() for x in keys)
+ vals = results + tuple(hyp.values())
+ n = len(keys)
+
+ # Download (optional)
+ if bucket:
+ url = f'gs://{bucket}/evolve.csv'
+ if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0):
+ os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local
+
+ # Log to evolve.csv
+ s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header
+ with open(evolve_csv, 'a') as f:
+ f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n')
+
+ # Save yaml
+ with open(evolve_yaml, 'w') as f:
+ data = pd.read_csv(evolve_csv)
+ data = data.rename(columns=lambda x: x.strip()) # strip keys
+ i = np.argmax(fitness(data.values[:, :4])) #
+ generations = len(data)
+ f.write('# YOLOv5 Hyperparameter Evolution Results\n' + f'# Best generation: {i}\n' +
+ f'# Last generation: {generations - 1}\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) +
+ '\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n')
+ yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False)
+
+ # Print to screen
+ LOGGER.info(prefix + f'{generations} generations finished, current result:\n' + prefix +
+ ', '.join(f'{x.strip():>20s}' for x in keys) + '\n' + prefix + ', '.join(f'{x:20.5g}'
+ for x in vals) + '\n\n')
+
+ if bucket:
+ os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload
+
+
+def apply_classifier(x, model, img, im0):
+ # Apply a second stage classifier to YOLO outputs
+ # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval()
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
+ for i, d in enumerate(x): # per image
+ if d is not None and len(d):
+ d = d.clone()
+
+ # Reshape and pad cutouts
+ b = xyxy2xywh(d[:, :4]) # boxes
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
+ d[:, :4] = xywh2xyxy(b).long()
+
+ # Rescale boxes from img_size to im0 size
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
+
+ # Classes
+ pred_cls1 = d[:, 5].long()
+ ims = []
+ for a in d:
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
+ im = cv2.resize(cutout, (224, 224)) # BGR
+
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
+ im /= 255 # 0 - 255 to 0.0 - 1.0
+ ims.append(im)
+
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
+
+ return x
+
+
+def increment_path(path, exist_ok=False, sep='', mkdir=False):
+ # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
+ path = Path(path) # os-agnostic
+ if path.exists() and not exist_ok:
+ path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
+
+ # Method 1
+ for n in range(2, 9999):
+ p = f'{path}{sep}{n}{suffix}' # increment path
+ if not os.path.exists(p): #
+ break
+ path = Path(p)
+
+ # Method 2 (deprecated)
+ # dirs = glob.glob(f"{path}{sep}*") # similar paths
+ # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs]
+ # i = [int(m.groups()[0]) for m in matches if m] # indices
+ # n = max(i) + 1 if i else 2 # increment number
+ # path = Path(f"{path}{sep}{n}{suffix}") # increment path
+
+ if mkdir:
+ path.mkdir(parents=True, exist_ok=True) # make directory
+
+ return path
+
+
+# OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------
+imshow_ = cv2.imshow # copy to avoid recursion errors
+
+
+def imread(path, flags=cv2.IMREAD_COLOR):
+ return cv2.imdecode(np.fromfile(path, np.uint8), flags)
+
+
+def imwrite(path, im):
+ try:
+ cv2.imencode(Path(path).suffix, im)[1].tofile(path)
+ return True
+ except Exception:
+ return False
+
+
+def imshow(path, im):
+ imshow_(path.encode('unicode_escape').decode(), im)
+
+
+cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow # redefine
+
+# Variables ------------------------------------------------------------------------------------------------------------
+NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/loss.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/loss.py
new file mode 100644
index 000000000..9b9c3d9f8
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/loss.py
@@ -0,0 +1,234 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Loss functions
+"""
+
+import torch
+import torch.nn as nn
+
+from utils.metrics import bbox_iou
+from utils.torch_utils import de_parallel
+
+
+def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
+ # return positive, negative label smoothing BCE targets
+ return 1.0 - 0.5 * eps, 0.5 * eps
+
+
+class BCEBlurWithLogitsLoss(nn.Module):
+ # BCEwithLogitLoss() with reduced missing label effects.
+ def __init__(self, alpha=0.05):
+ super().__init__()
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
+ self.alpha = alpha
+
+ def forward(self, pred, true):
+ loss = self.loss_fcn(pred, true)
+ pred = torch.sigmoid(pred) # prob from logits
+ dx = pred - true # reduce only missing label effects
+ # dx = (pred - true).abs() # reduce missing label and false label effects
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
+ loss *= alpha_factor
+ return loss.mean()
+
+
+class FocalLoss(nn.Module):
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
+ super().__init__()
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
+ self.gamma = gamma
+ self.alpha = alpha
+ self.reduction = loss_fcn.reduction
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
+
+ def forward(self, pred, true):
+ loss = self.loss_fcn(pred, true)
+ # p_t = torch.exp(-loss)
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
+
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
+ pred_prob = torch.sigmoid(pred) # prob from logits
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
+ modulating_factor = (1.0 - p_t) ** self.gamma
+ loss *= alpha_factor * modulating_factor
+
+ if self.reduction == 'mean':
+ return loss.mean()
+ elif self.reduction == 'sum':
+ return loss.sum()
+ else: # 'none'
+ return loss
+
+
+class QFocalLoss(nn.Module):
+ # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
+ super().__init__()
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
+ self.gamma = gamma
+ self.alpha = alpha
+ self.reduction = loss_fcn.reduction
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
+
+ def forward(self, pred, true):
+ loss = self.loss_fcn(pred, true)
+
+ pred_prob = torch.sigmoid(pred) # prob from logits
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
+ modulating_factor = torch.abs(true - pred_prob) ** self.gamma
+ loss *= alpha_factor * modulating_factor
+
+ if self.reduction == 'mean':
+ return loss.mean()
+ elif self.reduction == 'sum':
+ return loss.sum()
+ else: # 'none'
+ return loss
+
+
+class ComputeLoss:
+ sort_obj_iou = False
+
+ # Compute losses
+ def __init__(self, model, autobalance=False):
+ device = next(model.parameters()).device # get model device
+ h = model.hyp # hyperparameters
+
+ # Define criteria
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
+
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
+
+ # Focal loss
+ g = h['fl_gamma'] # focal loss gamma
+ if g > 0:
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
+
+ m = de_parallel(model).model[-1] # Detect() module
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
+ self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
+ self.na = m.na # number of anchors
+ self.nc = m.nc # number of classes
+ self.nl = m.nl # number of layers
+ self.anchors = m.anchors
+ self.device = device
+
+ def __call__(self, p, targets): # predictions, targets
+ lcls = torch.zeros(1, device=self.device) # class loss
+ lbox = torch.zeros(1, device=self.device) # box loss
+ lobj = torch.zeros(1, device=self.device) # object loss
+ tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
+
+ # Losses
+ for i, pi in enumerate(p): # layer index, layer predictions
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
+ tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
+
+ n = b.shape[0] # number of targets
+ if n:
+ # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
+ pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
+
+ # Regression
+ pxy = pxy.sigmoid() * 2 - 0.5
+ pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
+ iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
+ lbox += (1.0 - iou).mean() # iou loss
+
+ # Objectness
+ iou = iou.detach().clamp(0).type(tobj.dtype)
+ if self.sort_obj_iou:
+ j = iou.argsort()
+ b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
+ if self.gr < 1:
+ iou = (1.0 - self.gr) + self.gr * iou
+ tobj[b, a, gj, gi] = iou # iou ratio
+
+ # Classification
+ if self.nc > 1: # cls loss (only if multiple classes)
+ t = torch.full_like(pcls, self.cn, device=self.device) # targets
+ t[range(n), tcls[i]] = self.cp
+ lcls += self.BCEcls(pcls, t) # BCE
+
+ # Append targets to text file
+ # with open('targets.txt', 'a') as file:
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
+
+ obji = self.BCEobj(pi[..., 4], tobj)
+ lobj += obji * self.balance[i] # obj loss
+ if self.autobalance:
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
+
+ if self.autobalance:
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
+ lbox *= self.hyp['box']
+ lobj *= self.hyp['obj']
+ lcls *= self.hyp['cls']
+ bs = tobj.shape[0] # batch size
+
+ return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
+
+ def build_targets(self, p, targets):
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
+ tcls, tbox, indices, anch = [], [], [], []
+ gain = torch.ones(7, device=self.device) # normalized to gridspace gain
+ ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
+
+ g = 0.5 # bias
+ off = torch.tensor(
+ [
+ [0, 0],
+ [1, 0],
+ [0, 1],
+ [-1, 0],
+ [0, -1], # j,k,l,m
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
+ ],
+ device=self.device).float() * g # offsets
+
+ for i in range(self.nl):
+ anchors, shape = self.anchors[i], p[i].shape
+ gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
+
+ # Match targets to anchors
+ t = targets * gain # shape(3,n,7)
+ if nt:
+ # Matches
+ r = t[..., 4:6] / anchors[:, None] # wh ratio
+ j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
+ t = t[j] # filter
+
+ # Offsets
+ gxy = t[:, 2:4] # grid xy
+ gxi = gain[[2, 3]] - gxy # inverse
+ j, k = ((gxy % 1 < g) & (gxy > 1)).T
+ l, m = ((gxi % 1 < g) & (gxi > 1)).T
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
+ t = t.repeat((5, 1, 1))[j]
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
+ else:
+ t = targets[0]
+ offsets = 0
+
+ # Define
+ bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
+ a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
+ gij = (gxy - offsets).long()
+ gi, gj = gij.T # grid indices
+
+ # Append
+ indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
+ anch.append(anchors[a]) # anchors
+ tcls.append(c) # class
+
+ return tcls, tbox, indices, anch
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/metrics.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/metrics.py
new file mode 100644
index 000000000..08880cd3f
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/metrics.py
@@ -0,0 +1,364 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Model validation metrics
+"""
+
+import math
+import warnings
+from pathlib import Path
+
+import matplotlib.pyplot as plt
+import numpy as np
+import torch
+
+
+def fitness(x):
+ # Model fitness as a weighted combination of metrics
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
+ return (x[:, :4] * w).sum(1)
+
+
+def smooth(y, f=0.05):
+ # Box filter of fraction f
+ nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
+ p = np.ones(nf // 2) # ones padding
+ yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
+ return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
+
+
+def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16):
+ """ Compute the average precision, given the recall and precision curves.
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
+ # Arguments
+ tp: True positives (nparray, nx1 or nx10).
+ conf: Objectness value from 0-1 (nparray).
+ pred_cls: Predicted object classes (nparray).
+ target_cls: True object classes (nparray).
+ plot: Plot precision-recall curve at mAP@0.5
+ save_dir: Plot save directory
+ # Returns
+ The average precision as computed in py-faster-rcnn.
+ """
+
+ # Sort by objectness
+ i = np.argsort(-conf)
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
+
+ # Find unique classes
+ unique_classes, nt = np.unique(target_cls, return_counts=True)
+ nc = unique_classes.shape[0] # number of classes, number of detections
+
+ # Create Precision-Recall curve and compute AP for each class
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
+ for ci, c in enumerate(unique_classes):
+ i = pred_cls == c
+ n_l = nt[ci] # number of labels
+ n_p = i.sum() # number of predictions
+ if n_p == 0 or n_l == 0:
+ continue
+
+ # Accumulate FPs and TPs
+ fpc = (1 - tp[i]).cumsum(0)
+ tpc = tp[i].cumsum(0)
+
+ # Recall
+ recall = tpc / (n_l + eps) # recall curve
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
+
+ # Precision
+ precision = tpc / (tpc + fpc) # precision curve
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
+
+ # AP from recall-precision curve
+ for j in range(tp.shape[1]):
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
+ if plot and j == 0:
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
+
+ # Compute F1 (harmonic mean of precision and recall)
+ f1 = 2 * p * r / (p + r + eps)
+ names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
+ names = dict(enumerate(names)) # to dict
+ if plot:
+ plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
+ plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
+ plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
+ plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
+
+ i = smooth(f1.mean(0), 0.1).argmax() # max F1 index
+ p, r, f1 = p[:, i], r[:, i], f1[:, i]
+ tp = (r * nt).round() # true positives
+ fp = (tp / (p + eps) - tp).round() # false positives
+ return tp, fp, p, r, f1, ap, unique_classes.astype(int)
+
+
+def compute_ap(recall, precision):
+ """ Compute the average precision, given the recall and precision curves
+ # Arguments
+ recall: The recall curve (list)
+ precision: The precision curve (list)
+ # Returns
+ Average precision, precision curve, recall curve
+ """
+
+ # Append sentinel values to beginning and end
+ mrec = np.concatenate(([0.0], recall, [1.0]))
+ mpre = np.concatenate(([1.0], precision, [0.0]))
+
+ # Compute the precision envelope
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
+
+ # Integrate area under curve
+ method = 'interp' # methods: 'continuous', 'interp'
+ if method == 'interp':
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
+ else: # 'continuous'
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
+
+ return ap, mpre, mrec
+
+
+class ConfusionMatrix:
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
+ self.matrix = np.zeros((nc + 1, nc + 1))
+ self.nc = nc # number of classes
+ self.conf = conf
+ self.iou_thres = iou_thres
+
+ def process_batch(self, detections, labels):
+ """
+ Return intersection-over-union (Jaccard index) of boxes.
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
+ Arguments:
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
+ labels (Array[M, 5]), class, x1, y1, x2, y2
+ Returns:
+ None, updates confusion matrix accordingly
+ """
+ if detections is None:
+ gt_classes = labels.int()
+ for i, gc in enumerate(gt_classes):
+ self.matrix[self.nc, gc] += 1 # background FN
+ return
+
+ detections = detections[detections[:, 4] > self.conf]
+ gt_classes = labels[:, 0].int()
+ detection_classes = detections[:, 5].int()
+ iou = box_iou(labels[:, 1:], detections[:, :4])
+
+ x = torch.where(iou > self.iou_thres)
+ if x[0].shape[0]:
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
+ if x[0].shape[0] > 1:
+ matches = matches[matches[:, 2].argsort()[::-1]]
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
+ matches = matches[matches[:, 2].argsort()[::-1]]
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
+ else:
+ matches = np.zeros((0, 3))
+
+ n = matches.shape[0] > 0
+ m0, m1, _ = matches.transpose().astype(int)
+ for i, gc in enumerate(gt_classes):
+ j = m0 == i
+ if n and sum(j) == 1:
+ self.matrix[detection_classes[m1[j]], gc] += 1 # correct
+ else:
+ self.matrix[self.nc, gc] += 1 # background FP
+
+ if n:
+ for i, dc in enumerate(detection_classes):
+ if not any(m1 == i):
+ self.matrix[dc, self.nc] += 1 # background FN
+
+ def matrix(self):
+ return self.matrix
+
+ def tp_fp(self):
+ tp = self.matrix.diagonal() # true positives
+ fp = self.matrix.sum(1) - tp # false positives
+ # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
+ return tp[:-1], fp[:-1] # remove background class
+
+ def plot(self, normalize=True, save_dir='', names=()):
+ try:
+ import seaborn as sn
+
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
+
+ fig = plt.figure(figsize=(12, 9), tight_layout=True)
+ nc, nn = self.nc, len(names) # number of classes, names
+ sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
+ labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
+ sn.heatmap(array,
+ annot=nc < 30,
+ annot_kws={
+ "size": 8},
+ cmap='Blues',
+ fmt='.2f',
+ square=True,
+ vmin=0.0,
+ xticklabels=names + ['background FP'] if labels else "auto",
+ yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
+ fig.axes[0].set_xlabel('True')
+ fig.axes[0].set_ylabel('Predicted')
+ plt.title('Confusion Matrix')
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
+ plt.close()
+ except Exception as e:
+ print(f'WARNING: ConfusionMatrix plot failure: {e}')
+
+ def print(self):
+ for i in range(self.nc + 1):
+ print(' '.join(map(str, self.matrix[i])))
+
+
+def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
+ # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
+
+ # Get the coordinates of bounding boxes
+ if xywh: # transform from xywh to xyxy
+ (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, 1), box2.chunk(4, 1)
+ w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
+ b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
+ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
+ else: # x1, y1, x2, y2 = box1
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, 1)
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, 1)
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
+
+ # Intersection area
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
+
+ # Union Area
+ union = w1 * h1 + w2 * h2 - inter + eps
+
+ # IoU
+ iou = inter / union
+ if CIoU or DIoU or GIoU:
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / (h2 + eps)) - torch.atan(w1 / (h1 + eps)), 2)
+ with torch.no_grad():
+ alpha = v / (v - iou + (1 + eps))
+ return iou - (rho2 / c2 + v * alpha) # CIoU
+ return iou - rho2 / c2 # DIoU
+ c_area = cw * ch + eps # convex area
+ return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
+ return iou # IoU
+
+
+def box_area(box):
+ # box = xyxy(4,n)
+ return (box[2] - box[0]) * (box[3] - box[1])
+
+
+def box_iou(box1, box2, eps=1e-7):
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
+ """
+ Return intersection-over-union (Jaccard index) of boxes.
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
+ Arguments:
+ box1 (Tensor[N, 4])
+ box2 (Tensor[M, 4])
+ Returns:
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
+ IoU values for every element in boxes1 and boxes2
+ """
+
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
+ (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1)
+ inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)
+
+ # IoU = inter / (area1 + area2 - inter)
+ return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter + eps)
+
+
+def bbox_ioa(box1, box2, eps=1e-7):
+ """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
+ box1: np.array of shape(4)
+ box2: np.array of shape(nx4)
+ returns: np.array of shape(n)
+ """
+
+ # Get the coordinates of bounding boxes
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
+
+ # Intersection area
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
+
+ # box2 area
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
+
+ # Intersection over box2 area
+ return inter_area / box2_area
+
+
+def wh_iou(wh1, wh2, eps=1e-7):
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
+ wh1 = wh1[:, None] # [N,1,2]
+ wh2 = wh2[None] # [1,M,2]
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter + eps) # iou = inter / (area1 + area2 - inter)
+
+
+# Plots ----------------------------------------------------------------------------------------------------------------
+
+
+def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
+ # Precision-recall curve
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
+ py = np.stack(py, axis=1)
+
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
+ for i, y in enumerate(py.T):
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
+ else:
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
+
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
+ ax.set_xlabel('Recall')
+ ax.set_ylabel('Precision')
+ ax.set_xlim(0, 1)
+ ax.set_ylim(0, 1)
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
+ plt.title('Precision-Recall Curve')
+ fig.savefig(save_dir, dpi=250)
+ plt.close()
+
+
+def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'):
+ # Metric-confidence curve
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
+
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
+ for i, y in enumerate(py):
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
+ else:
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
+
+ y = smooth(py.mean(0), 0.05)
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
+ ax.set_xlabel(xlabel)
+ ax.set_ylabel(ylabel)
+ ax.set_xlim(0, 1)
+ ax.set_ylim(0, 1)
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
+ plt.title(f'{ylabel}-Confidence Curve')
+ fig.savefig(save_dir, dpi=250)
+ plt.close()
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/plots.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/plots.py
new file mode 100644
index 000000000..7417308c4
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/plots.py
@@ -0,0 +1,519 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+Plotting utils
+"""
+
+import math
+import os
+from copy import copy
+from pathlib import Path
+from urllib.error import URLError
+
+import cv2
+import matplotlib
+import matplotlib.pyplot as plt
+import numpy as np
+import pandas as pd
+import seaborn as sn
+import torch
+from PIL import Image, ImageDraw, ImageFont
+
+from utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords,
+ increment_path, is_ascii, threaded, try_except, xywh2xyxy, xyxy2xywh)
+from utils.metrics import fitness
+
+# Settings
+RANK = int(os.getenv('RANK', -1))
+matplotlib.rc('font', **{'size': 11})
+matplotlib.use('Agg') # for writing to files only
+
+
+class Colors:
+ # Ultralytics color palette https://ultralytics.com/
+ def __init__(self):
+ # hex = matplotlib.colors.TABLEAU_COLORS.values()
+ hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
+ '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
+ self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
+ self.n = len(self.palette)
+
+ def __call__(self, i, bgr=False):
+ c = self.palette[int(i) % self.n]
+ return (c[2], c[1], c[0]) if bgr else c
+
+ @staticmethod
+ def hex2rgb(h): # rgb order (PIL)
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
+
+
+colors = Colors() # create instance for 'from utils.plots import colors'
+
+
+def check_pil_font(font=FONT, size=10):
+ # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary
+ font = Path(font)
+ font = font if font.exists() else (CONFIG_DIR / font.name)
+ try:
+ return ImageFont.truetype(str(font) if font.exists() else font.name, size)
+ except Exception: # download if missing
+ try:
+ check_font(font)
+ return ImageFont.truetype(str(font), size)
+ except TypeError:
+ check_requirements('Pillow>=8.4.0') # known issue https://github.com/ultralytics/yolov5/issues/5374
+ except URLError: # not online
+ return ImageFont.load_default()
+
+
+class Annotator:
+ # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations
+ def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'):
+ assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'
+ non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic
+ self.pil = pil or non_ascii
+ if self.pil: # use PIL
+ self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
+ self.draw = ImageDraw.Draw(self.im)
+ self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font,
+ size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))
+ else: # use cv2
+ self.im = im
+ self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width
+
+ def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
+ # Add one xyxy box to image with label
+ if self.pil or not is_ascii(label):
+ self.draw.rectangle(box, width=self.lw, outline=color) # box
+ if label:
+ w, h = self.font.getsize(label) # text width, height
+ outside = box[1] - h >= 0 # label fits outside box
+ self.draw.rectangle(
+ (box[0], box[1] - h if outside else box[1], box[0] + w + 1,
+ box[1] + 1 if outside else box[1] + h + 1),
+ fill=color,
+ )
+ # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0
+ self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)
+ else: # cv2
+ p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
+ cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)
+ if label:
+ tf = max(self.lw - 1, 1) # font thickness
+ w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height
+ outside = p1[1] - h >= 3
+ p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
+ cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled
+ cv2.putText(self.im,
+ label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
+ 0,
+ self.lw / 3,
+ txt_color,
+ thickness=tf,
+ lineType=cv2.LINE_AA)
+
+ def rectangle(self, xy, fill=None, outline=None, width=1):
+ # Add rectangle to image (PIL-only)
+ self.draw.rectangle(xy, fill, outline, width)
+
+ def text(self, xy, text, txt_color=(255, 255, 255)):
+ # Add text to image (PIL-only)
+ w, h = self.font.getsize(text) # text width, height
+ self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font)
+
+ def result(self):
+ # Return annotated image as array
+ return np.asarray(self.im)
+
+
+def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
+ """
+ x: Features to be visualized
+ module_type: Module type
+ stage: Module stage within model
+ n: Maximum number of feature maps to plot
+ save_dir: Directory to save results
+ """
+ if 'Detect' not in module_type:
+ batch, channels, height, width = x.shape # batch, channels, height, width
+ if height > 1 and width > 1:
+ f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
+
+ blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
+ n = min(n, channels) # number of plots
+ fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
+ ax = ax.ravel()
+ plt.subplots_adjust(wspace=0.05, hspace=0.05)
+ for i in range(n):
+ ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
+ ax[i].axis('off')
+
+ LOGGER.info(f'Saving {f}... ({n}/{channels})')
+ plt.title('Features')
+ plt.savefig(f, dpi=300, bbox_inches='tight')
+ plt.close()
+ np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save
+
+
+def hist2d(x, y, n=100):
+ # 2d histogram used in labels.png and evolve.png
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
+ return np.log(hist[xidx, yidx])
+
+
+def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
+ from scipy.signal import butter, filtfilt
+
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
+ def butter_lowpass(cutoff, fs, order):
+ nyq = 0.5 * fs
+ normal_cutoff = cutoff / nyq
+ return butter(order, normal_cutoff, btype='low', analog=False)
+
+ b, a = butter_lowpass(cutoff, fs, order=order)
+ return filtfilt(b, a, data) # forward-backward filter
+
+
+def output_to_target(output):
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
+ targets = []
+ for i, o in enumerate(output):
+ for *box, conf, cls in o.cpu().numpy():
+ targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
+ return np.array(targets)
+
+
+@threaded
+def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):
+ # Plot image grid with labels
+ if isinstance(images, torch.Tensor):
+ images = images.cpu().float().numpy()
+ if isinstance(targets, torch.Tensor):
+ targets = targets.cpu().numpy()
+ if np.max(images[0]) <= 1:
+ images *= 255 # de-normalise (optional)
+ bs, _, h, w = images.shape # batch size, _, height, width
+ bs = min(bs, max_subplots) # limit plot images
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
+
+ # Build Image
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
+ for i, im in enumerate(images):
+ if i == max_subplots: # if last batch has fewer images than we expect
+ break
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
+ im = im.transpose(1, 2, 0)
+ mosaic[y:y + h, x:x + w, :] = im
+
+ # Resize (optional)
+ scale = max_size / ns / max(h, w)
+ if scale < 1:
+ h = math.ceil(scale * h)
+ w = math.ceil(scale * w)
+ mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
+
+ # Annotate
+ fs = int((h + w) * ns * 0.01) # font size
+ annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)
+ for i in range(i + 1):
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
+ annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
+ if paths:
+ annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
+ if len(targets) > 0:
+ ti = targets[targets[:, 0] == i] # image targets
+ boxes = xywh2xyxy(ti[:, 2:6]).T
+ classes = ti[:, 1].astype('int')
+ labels = ti.shape[1] == 6 # labels if no conf column
+ conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
+
+ if boxes.shape[1]:
+ if boxes.max() <= 1.01: # if normalized with tolerance 0.01
+ boxes[[0, 2]] *= w # scale to pixels
+ boxes[[1, 3]] *= h
+ elif scale < 1: # absolute coords need scale if image scales
+ boxes *= scale
+ boxes[[0, 2]] += x
+ boxes[[1, 3]] += y
+ for j, box in enumerate(boxes.T.tolist()):
+ cls = classes[j]
+ color = colors(cls)
+ cls = names[cls] if names else cls
+ if labels or conf[j] > 0.25: # 0.25 conf thresh
+ label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'
+ annotator.box_label(box, label, color=color)
+ annotator.im.save(fname) # save
+
+
+def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
+ # Plot LR simulating training for full epochs
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
+ y = []
+ for _ in range(epochs):
+ scheduler.step()
+ y.append(optimizer.param_groups[0]['lr'])
+ plt.plot(y, '.-', label='LR')
+ plt.xlabel('epoch')
+ plt.ylabel('LR')
+ plt.grid()
+ plt.xlim(0, epochs)
+ plt.ylim(0)
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
+ plt.close()
+
+
+def plot_val_txt(): # from utils.plots import *; plot_val()
+ # Plot val.txt histograms
+ x = np.loadtxt('val.txt', dtype=np.float32)
+ box = xyxy2xywh(x[:, :4])
+ cx, cy = box[:, 0], box[:, 1]
+
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
+ ax.set_aspect('equal')
+ plt.savefig('hist2d.png', dpi=300)
+
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
+ ax[0].hist(cx, bins=600)
+ ax[1].hist(cy, bins=600)
+ plt.savefig('hist1d.png', dpi=200)
+
+
+def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
+ # Plot targets.txt histograms
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
+ ax = ax.ravel()
+ for i in range(4):
+ ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}')
+ ax[i].legend()
+ ax[i].set_title(s[i])
+ plt.savefig('targets.jpg', dpi=200)
+
+
+def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study()
+ # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)
+ save_dir = Path(file).parent if file else Path(dir)
+ plot2 = False # plot additional results
+ if plot2:
+ ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
+
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
+ # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
+ for f in sorted(save_dir.glob('study*.txt')):
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
+ if plot2:
+ s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
+ for i in range(7):
+ ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
+ ax[i].set_title(s[i])
+
+ j = y[3].argmax() + 1
+ ax2.plot(y[5, 1:j],
+ y[3, 1:j] * 1E2,
+ '.-',
+ linewidth=2,
+ markersize=8,
+ label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
+
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
+ 'k.-',
+ linewidth=2,
+ markersize=8,
+ alpha=.25,
+ label='EfficientDet')
+
+ ax2.grid(alpha=0.2)
+ ax2.set_yticks(np.arange(20, 60, 5))
+ ax2.set_xlim(0, 57)
+ ax2.set_ylim(25, 55)
+ ax2.set_xlabel('GPU Speed (ms/img)')
+ ax2.set_ylabel('COCO AP val')
+ ax2.legend(loc='lower right')
+ f = save_dir / 'study.png'
+ print(f'Saving {f}...')
+ plt.savefig(f, dpi=300)
+
+
+@try_except # known issue https://github.com/ultralytics/yolov5/issues/5395
+@Timeout(30) # known issue https://github.com/ultralytics/yolov5/issues/5611
+def plot_labels(labels, names=(), save_dir=Path('')):
+ # plot dataset labels
+ LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
+ nc = int(c.max() + 1) # number of classes
+ x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
+
+ # seaborn correlogram
+ sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
+ plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
+ plt.close()
+
+ # matplotlib labels
+ matplotlib.use('svg') # faster
+ ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
+ y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
+ try: # color histogram bars by class
+ [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195
+ except Exception:
+ pass
+ ax[0].set_ylabel('instances')
+ if 0 < len(names) < 30:
+ ax[0].set_xticks(range(len(names)))
+ ax[0].set_xticklabels(names, rotation=90, fontsize=10)
+ else:
+ ax[0].set_xlabel('classes')
+ sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
+ sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
+
+ # rectangles
+ labels[:, 1:3] = 0.5 # center
+ labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
+ img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
+ for cls, *box in labels[:1000]:
+ ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
+ ax[1].imshow(img)
+ ax[1].axis('off')
+
+ for a in [0, 1, 2, 3]:
+ for s in ['top', 'right', 'left', 'bottom']:
+ ax[a].spines[s].set_visible(False)
+
+ plt.savefig(save_dir / 'labels.jpg', dpi=200)
+ matplotlib.use('Agg')
+ plt.close()
+
+
+def imshow_cls(im, labels=None, pred=None, names=None, nmax=25, verbose=False, f=Path('images.jpg')):
+ # Show classification image grid with labels (optional) and predictions (optional)
+ from utils.augmentations import denormalize
+
+ names = names or [f'class{i}' for i in range(1000)]
+ blocks = torch.chunk(denormalize(im.clone()).cpu().float(), len(im),
+ dim=0) # select batch index 0, block by channels
+ n = min(len(blocks), nmax) # number of plots
+ m = min(8, round(n ** 0.5)) # 8 x 8 default
+ fig, ax = plt.subplots(math.ceil(n / m), m) # 8 rows x n/8 cols
+ ax = ax.ravel() if m > 1 else [ax]
+ # plt.subplots_adjust(wspace=0.05, hspace=0.05)
+ for i in range(n):
+ ax[i].imshow(blocks[i].squeeze().permute((1, 2, 0)).numpy().clip(0.0, 1.0))
+ ax[i].axis('off')
+ if labels is not None:
+ s = names[labels[i]] + (f'—{names[pred[i]]}' if pred is not None else '')
+ ax[i].set_title(s, fontsize=8, verticalalignment='top')
+ plt.savefig(f, dpi=300, bbox_inches='tight')
+ plt.close()
+ if verbose:
+ LOGGER.info(f"Saving {f}")
+ if labels is not None:
+ LOGGER.info('True: ' + ' '.join(f'{names[i]:3s}' for i in labels[:nmax]))
+ if pred is not None:
+ LOGGER.info('Predicted:' + ' '.join(f'{names[i]:3s}' for i in pred[:nmax]))
+ return f
+
+
+def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve()
+ # Plot evolve.csv hyp evolution results
+ evolve_csv = Path(evolve_csv)
+ data = pd.read_csv(evolve_csv)
+ keys = [x.strip() for x in data.columns]
+ x = data.values
+ f = fitness(x)
+ j = np.argmax(f) # max fitness index
+ plt.figure(figsize=(10, 12), tight_layout=True)
+ matplotlib.rc('font', **{'size': 8})
+ print(f'Best results from row {j} of {evolve_csv}:')
+ for i, k in enumerate(keys[7:]):
+ v = x[:, 7 + i]
+ mu = v[j] # best single result
+ plt.subplot(6, 5, i + 1)
+ plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
+ plt.plot(mu, f.max(), 'k+', markersize=15)
+ plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9}) # limit to 40 characters
+ if i % 5 != 0:
+ plt.yticks([])
+ print(f'{k:>15}: {mu:.3g}')
+ f = evolve_csv.with_suffix('.png') # filename
+ plt.savefig(f, dpi=200)
+ plt.close()
+ print(f'Saved {f}')
+
+
+def plot_results(file='path/to/results.csv', dir=''):
+ # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
+ save_dir = Path(file).parent if file else Path(dir)
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
+ ax = ax.ravel()
+ files = list(save_dir.glob('results*.csv'))
+ assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
+ for f in files:
+ try:
+ data = pd.read_csv(f)
+ s = [x.strip() for x in data.columns]
+ x = data.values[:, 0]
+ for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
+ y = data.values[:, j].astype('float')
+ # y[y == 0] = np.nan # don't show zero values
+ ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)
+ ax[i].set_title(s[j], fontsize=12)
+ # if j in [8, 9, 10]: # share train and val loss y axes
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
+ except Exception as e:
+ LOGGER.info(f'Warning: Plotting error for {f}: {e}')
+ ax[1].legend()
+ fig.savefig(save_dir / 'results.png', dpi=200)
+ plt.close()
+
+
+def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
+ # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
+ ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
+ s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
+ files = list(Path(save_dir).glob('frames*.txt'))
+ for fi, f in enumerate(files):
+ try:
+ results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
+ n = results.shape[1] # number of rows
+ x = np.arange(start, min(stop, n) if stop else n)
+ results = results[:, x]
+ t = (results[0] - results[0].min()) # set t0=0s
+ results[0] = x
+ for i, a in enumerate(ax):
+ if i < len(results):
+ label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
+ a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
+ a.set_title(s[i])
+ a.set_xlabel('time (s)')
+ # if fi == len(files) - 1:
+ # a.set_ylim(bottom=0)
+ for side in ['top', 'right']:
+ a.spines[side].set_visible(False)
+ else:
+ a.remove()
+ except Exception as e:
+ print(f'Warning: Plotting error for {f}; {e}')
+ ax[1].legend()
+ plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
+
+
+def save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True):
+ # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop
+ xyxy = torch.tensor(xyxy).view(-1, 4)
+ b = xyxy2xywh(xyxy) # boxes
+ if square:
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
+ b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
+ xyxy = xywh2xyxy(b).long()
+ clip_coords(xyxy, im.shape)
+ crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]
+ if save:
+ file.parent.mkdir(parents=True, exist_ok=True) # make directory
+ f = str(increment_path(file).with_suffix('.jpg'))
+ # cv2.imwrite(f, crop) # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue
+ Image.fromarray(crop[..., ::-1]).save(f, quality=95, subsampling=0) # save RGB
+ return crop
diff --git a/models/object_detection/pytorch/yolov5/inference/gpu/utils/torch_utils.py b/models/object_detection/pytorch/yolov5/inference/gpu/utils/torch_utils.py
new file mode 100644
index 000000000..4de2520b2
--- /dev/null
+++ b/models/object_detection/pytorch/yolov5/inference/gpu/utils/torch_utils.py
@@ -0,0 +1,431 @@
+# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
+"""
+PyTorch utils
+"""
+
+import math
+import os
+import platform
+import subprocess
+import time
+import warnings
+from contextlib import contextmanager
+from copy import deepcopy
+from pathlib import Path
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn.parallel import DistributedDataParallel as DDP
+
+from utils.general import LOGGER, check_version, colorstr, file_date, git_describe
+
+LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
+RANK = int(os.getenv('RANK', -1))
+WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
+
+try:
+ import thop # for FLOPs computation
+except ImportError:
+ thop = None
+
+# Suppress PyTorch warnings
+warnings.filterwarnings('ignore', message='User provided device_type of \'cuda\', but CUDA is not available. Disabling')
+
+
+def smart_inference_mode(torch_1_9=check_version(torch.__version__, '1.9.0')):
+ # Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator
+ def decorate(fn):
+ return (torch.inference_mode if torch_1_9 else torch.no_grad)()(fn)
+
+ return decorate
+
+
+def smartCrossEntropyLoss(label_smoothing=0.0):
+ # Returns nn.CrossEntropyLoss with label smoothing enabled for torch>=1.10.0
+ if check_version(torch.__version__, '1.10.0'):
+ return nn.CrossEntropyLoss(label_smoothing=label_smoothing) # loss function
+ else:
+ if label_smoothing > 0:
+ LOGGER.warning(f'WARNING: label smoothing {label_smoothing} requires torch>=1.10.0')
+ return nn.CrossEntropyLoss() # loss function
+
+
+def smart_DDP(model):
+ # Model DDP creation with checks
+ assert not check_version(torch.__version__, '1.12.0', pinned=True), \
+ 'torch==1.12.0 torchvision==0.13.0 DDP training is not supported due to a known issue. ' \
+ 'Please upgrade or downgrade torch to use DDP. See https://github.com/ultralytics/yolov5/issues/8395'
+ if check_version(torch.__version__, '1.11.0'):
+ return DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK, static_graph=True)
+ else:
+ return DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK)
+
+
+def reshape_classifier_output(model, n=1000):
+ # Update a TorchVision classification model to class count 'n' if required
+ from models.common import Classify
+ name, m = list((model.model if hasattr(model, 'model') else model).named_children())[-1] # last module
+ if isinstance(m, Classify): # YOLOv5 Classify() head
+ if m.linear.out_features != n:
+ m.linear = nn.Linear(m.linear.in_features, n)
+ elif isinstance(m, nn.Linear): # ResNet, EfficientNet
+ if m.out_features != n:
+ setattr(model, name, nn.Linear(m.in_features, n))
+ elif isinstance(m, nn.Sequential):
+ types = [type(x) for x in m]
+ if nn.Linear in types:
+ i = types.index(nn.Linear) # nn.Linear index
+ if m[i].out_features != n:
+ m[i] = nn.Linear(m[i].in_features, n)
+ elif nn.Conv2d in types:
+ i = types.index(nn.Conv2d) # nn.Conv2d index
+ if m[i].out_channels != n:
+ m[i] = nn.Conv2d(m[i].in_channels, n, m[i].kernel_size, m[i].stride, bias=m[i].bias)
+
+
+@contextmanager
+def torch_distributed_zero_first(local_rank: int):
+ # Decorator to make all processes in distributed training wait for each local_master to do something
+ if local_rank not in [-1, 0]:
+ dist.barrier(device_ids=[local_rank])
+ yield
+ if local_rank == 0:
+ dist.barrier(device_ids=[0])
+
+
+def device_count():
+ # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Supports Linux and Windows
+ assert platform.system() in ('Linux', 'Windows'), 'device_count() only supported on Linux or Windows'
+ try:
+ cmd = 'nvidia-smi -L | wc -l' if platform.system() == 'Linux' else 'nvidia-smi -L | find /c /v ""' # Windows
+ return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1])
+ except Exception:
+ return 0
+
+
+def select_device(device='', batch_size=0, newline=True):
+ # device = None or 'cpu' or 0 or '0' or '0,1,2,3'
+ s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} '
+ device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0'
+ cpu = device == 'cpu'
+ mps = device == 'mps' # Apple Metal Performance Shaders (MPS)
+ if cpu or mps:
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
+ elif device: # non-cpu device requested
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available()
+ assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \
+ f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)"
+
+ if not (cpu or mps) and torch.cuda.is_available(): # prefer GPU if available
+ devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7
+ n = len(devices) # device count
+ if n > 1 and batch_size > 0: # check batch_size is divisible by device_count
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
+ space = ' ' * (len(s) + 1)
+ for i, d in enumerate(devices):
+ p = torch.cuda.get_device_properties(i)
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB
+ arg = 'cuda:0'
+ elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available(): # prefer MPS if available
+ s += 'MPS\n'
+ arg = 'mps'
+ else: # revert to CPU
+ s += 'CPU\n'
+ arg = 'cpu'
+
+ if not newline:
+ s = s.rstrip()
+ LOGGER.info(s)
+ return torch.device(arg)
+
+
+def time_sync():
+ # PyTorch-accurate time
+ if torch.cuda.is_available():
+ torch.cuda.synchronize()
+ return time.time()
+
+
+def profile(input, ops, n=10, device=None):
+ """ YOLOv5 speed/memory/FLOPs profiler
+ Usage:
+ input = torch.randn(16, 3, 640, 640)
+ m1 = lambda x: x * torch.sigmoid(x)
+ m2 = nn.SiLU()
+ profile(input, [m1, m2], n=100) # profile over 100 iterations
+ """
+ results = []
+ if not isinstance(device, torch.device):
+ device = select_device(device)
+ print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}"
+ f"{'input':>24s}{'output':>24s}")
+
+ for x in input if isinstance(input, list) else [input]:
+ x = x.to(device)
+ x.requires_grad = True
+ for m in ops if isinstance(ops, list) else [ops]:
+ m = m.to(device) if hasattr(m, 'to') else m # device
+ m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m
+ tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward
+ try:
+ flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs
+ except Exception:
+ flops = 0
+
+ try:
+ for _ in range(n):
+ t[0] = time_sync()
+ y = m(x)
+ t[1] = time_sync()
+ try:
+ _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()
+ t[2] = time_sync()
+ except Exception: # no backward method
+ # print(e) # for debug
+ t[2] = float('nan')
+ tf += (t[1] - t[0]) * 1000 / n # ms per op forward
+ tb += (t[2] - t[1]) * 1000 / n # ms per op backward
+ mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB)
+ s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y)) # shapes
+ p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters
+ print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')
+ results.append([p, flops, mem, tf, tb, s_in, s_out])
+ except Exception as e:
+ print(e)
+ results.append(None)
+ torch.cuda.empty_cache()
+ return results
+
+
+def is_parallel(model):
+ # Returns True if model is of type DP or DDP
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
+
+
+def de_parallel(model):
+ # De-parallelize a model: returns single-GPU model if model is of type DP or DDP
+ return model.module if is_parallel(model) else model
+
+
+def initialize_weights(model):
+ for m in model.modules():
+ t = type(m)
+ if t is nn.Conv2d:
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ elif t is nn.BatchNorm2d:
+ m.eps = 1e-3
+ m.momentum = 0.03
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
+ m.inplace = True
+
+
+def find_modules(model, mclass=nn.Conv2d):
+ # Finds layer indices matching module class 'mclass'
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
+
+
+def sparsity(model):
+ # Return global model sparsity
+ a, b = 0, 0
+ for p in model.parameters():
+ a += p.numel()
+ b += (p == 0).sum()
+ return b / a
+
+
+def prune(model, amount=0.3):
+ # Prune model to requested global sparsity
+ import torch.nn.utils.prune as prune
+ for name, m in model.named_modules():
+ if isinstance(m, nn.Conv2d):
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
+ prune.remove(m, 'weight') # make permanent
+ LOGGER.info(f'Model pruned to {sparsity(model):.3g} global sparsity')
+
+
+def fuse_conv_and_bn(conv, bn):
+ # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
+ fusedconv = nn.Conv2d(conv.in_channels,
+ conv.out_channels,
+ kernel_size=conv.kernel_size,
+ stride=conv.stride,
+ padding=conv.padding,
+ groups=conv.groups,
+ bias=True).requires_grad_(False).to(conv.weight.device)
+
+ # Prepare filters
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
+
+ # Prepare spatial bias
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
+
+ return fusedconv
+
+
+def model_info(model, verbose=False, imgsz=640):
+ # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
+ if verbose:
+ print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}")
+ for i, (name, p) in enumerate(model.named_parameters()):
+ name = name.replace('module_list.', '')
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
+
+ try: # FLOPs
+ p = next(model.parameters())
+ stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 # max stride
+ im = torch.empty((1, p.shape[1], stride, stride), device=p.device) # input image in BCHW format
+ flops = thop.profile(deepcopy(model), inputs=(im,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs
+ imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz] # expand if int/float
+ fs = f', {flops * imgsz[0] / stride * imgsz[1] / stride:.1f} GFLOPs' # 640x640 GFLOPs
+ except Exception:
+ fs = ''
+
+ name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model'
+ LOGGER.info(f"{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
+
+
+def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
+ # Scales img(bs,3,y,x) by ratio constrained to gs-multiple
+ if ratio == 1.0:
+ return img
+ h, w = img.shape[2:]
+ s = (int(h * ratio), int(w * ratio)) # new size
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
+ if not same_shape: # pad/crop img
+ h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
+
+
+def copy_attr(a, b, include=(), exclude=()):
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
+ for k, v in b.__dict__.items():
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
+ continue
+ else:
+ setattr(a, k, v)
+
+
+def smart_optimizer(model, name='Adam', lr=0.001, momentum=0.9, decay=1e-5):
+ # YOLOv5 3-param group optimizer: 0) weights with decay, 1) weights no decay, 2) biases no decay
+ g = [], [], [] # optimizer parameter groups
+ bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k) # normalization layers, i.e. BatchNorm2d()
+ for v in model.modules():
+ if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): # bias (no decay)
+ g[2].append(v.bias)
+ if isinstance(v, bn): # weight (no decay)
+ g[1].append(v.weight)
+ elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): # weight (with decay)
+ g[0].append(v.weight)
+
+ if name == 'Adam':
+ optimizer = torch.optim.Adam(g[2], lr=lr, betas=(momentum, 0.999)) # adjust beta1 to momentum
+ elif name == 'AdamW':
+ optimizer = torch.optim.AdamW(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)
+ elif name == 'RMSProp':
+ optimizer = torch.optim.RMSprop(g[2], lr=lr, momentum=momentum)
+ elif name == 'SGD':
+ optimizer = torch.optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)
+ else:
+ raise NotImplementedError(f'Optimizer {name} not implemented.')
+
+ optimizer.add_param_group({'params': g[0], 'weight_decay': decay}) # add g0 with weight_decay
+ optimizer.add_param_group({'params': g[1], 'weight_decay': 0.0}) # add g1 (BatchNorm2d weights)
+ LOGGER.info(f"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}) with parameter groups "
+ f"{len(g[1])} weight(decay=0.0), {len(g[0])} weight(decay={decay}), {len(g[2])} bias")
+ return optimizer
+
+
+def smart_hub_load(repo='ultralytics/yolov5', model='yolov5s', **kwargs):
+ # YOLOv5 torch.hub.load() wrapper with smart error/issue handling
+ if check_version(torch.__version__, '1.9.1'):
+ kwargs['skip_validation'] = True # validation causes GitHub API rate limit errors
+ if check_version(torch.__version__, '1.12.0'):
+ kwargs['trust_repo'] = True # argument required starting in torch 0.12
+ try:
+ return torch.hub.load(repo, model, **kwargs)
+ except Exception:
+ return torch.hub.load(repo, model, force_reload=True, **kwargs)
+
+
+def smart_resume(ckpt, optimizer, ema=None, weights='yolov5s.pt', epochs=300, resume=True):
+ # Resume training from a partially trained checkpoint
+ best_fitness = 0.0
+ start_epoch = ckpt['epoch'] + 1
+ if ckpt['optimizer'] is not None:
+ optimizer.load_state_dict(ckpt['optimizer']) # optimizer
+ best_fitness = ckpt['best_fitness']
+ if ema and ckpt.get('ema'):
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict()) # EMA
+ ema.updates = ckpt['updates']
+ if resume:
+ assert start_epoch > 0, f'{weights} training to {epochs} epochs is finished, nothing to resume.\n' \
+ f"Start a new training without --resume, i.e. 'python train.py --weights {weights}'"
+ LOGGER.info(f'Resuming training from {weights} from epoch {start_epoch} to {epochs} total epochs')
+ if epochs < start_epoch:
+ LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.")
+ epochs += ckpt['epoch'] # finetune additional epochs
+ return best_fitness, start_epoch, epochs
+
+
+class EarlyStopping:
+ # YOLOv5 simple early stopper
+ def __init__(self, patience=30):
+ self.best_fitness = 0.0 # i.e. mAP
+ self.best_epoch = 0
+ self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop
+ self.possible_stop = False # possible stop may occur next epoch
+
+ def __call__(self, epoch, fitness):
+ if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training
+ self.best_epoch = epoch
+ self.best_fitness = fitness
+ delta = epoch - self.best_epoch # epochs without improvement
+ self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch
+ stop = delta >= self.patience # stop training if patience exceeded
+ if stop:
+ LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. '
+ f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n'
+ f'To update EarlyStopping(patience={self.patience}) pass a new patience value, '
+ f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.')
+ return stop
+
+
+class ModelEMA:
+ """ Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models
+ Keeps a moving average of everything in the model state_dict (parameters and buffers)
+ For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
+ """
+
+ def __init__(self, model, decay=0.9999, tau=2000, updates=0):
+ # Create EMA
+ self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA
+ self.updates = updates # number of EMA updates
+ self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
+ for p in self.ema.parameters():
+ p.requires_grad_(False)
+
+ @smart_inference_mode()
+ def update(self, model):
+ # Update EMA parameters
+ self.updates += 1
+ d = self.decay(self.updates)
+
+ msd = de_parallel(model).state_dict() # model state_dict
+ for k, v in self.ema.state_dict().items():
+ if v.dtype.is_floating_point: # true for FP16 and FP32
+ v *= d
+ v += (1 - d) * msd[k]
+ assert v.dtype == msd[k].dtype == torch.float32, f'EMA {v.dtype} and model {msd[k]} must be updated in FP32'
+
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
+ # Update EMA attributes
+ copy_attr(self.ema, model, include, exclude)
diff --git a/quickstart/common/.docs/resources_with_portal_link.md b/quickstart/common/.docs/resources_with_portal_link.md
index 4ee5417f1..16737822d 100644
--- a/quickstart/common/.docs/resources_with_portal_link.md
+++ b/quickstart/common/.docs/resources_with_portal_link.md
@@ -2,6 +2,6 @@
## Additional Resources
* To run more advanced use cases, see the instructions for the available precisions []() []() []() for calling the `launch_benchmark.py` script directly.
-* To run the model using docker, please see the [Intel® Developer Catalog](http://software.intel.com/containers)
+* To run the model using docker, please see the [Intel® Developer Catalog](https://www.intel.com/content/www/us/en/developer/tools/software-catalog/containers.html)
workload container:
[]().
\ No newline at end of file
diff --git a/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/DEVCATALOG.md b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/DEVCATALOG.md
new file mode 100644
index 000000000..66f816829
--- /dev/null
+++ b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/DEVCATALOG.md
@@ -0,0 +1,63 @@
+# Running Stable Diffusion inference on Intel® Data Center GPU Flex Series using Intel® Extension for PyTorch*
+
+## Overview
+
+This document has instructions for running Stable Diffusion inference using Intel® Extension for PyTorch on Intel® Flex Series GPU.
+
+## Requirements
+| Item | Detail |
+| ------ | ------- |
+| Host machine | Intel® Data Center GPU Flex Series |
+| Drivers | GPU-compatible drivers need to be installed:[Download Driver 647](https://dgpu-docs.intel.com/releases/stable_647_21_20230714.html)
+| Software | Docker* Installed |
+
+## Quick Start Scripts
+
+| Script name | Description |
+|-------------|-------------|
+| `online_inference.sh` | Inference for specified precision(FP32 or FP16) with batch size 1 on Flex series 170 |
+
+## Run Using Docker
+
+### Set up Docker Image
+
+```
+docker pull intel/generative-ai:pytorch-flex-gpu-stable-diffusion-inference
+```
+
+### Run Docker Image
+The stable diffusion inference container includes scripts,model and libraries need to run FP32 and FP16 inference. To run the `online_inference.sh` quickstart script using this container, you will need to provide an output directory where log files will be written.
+
+```bash
+export IMAGE_NAME=intel/generative-ai:pytorch-flex-gpu-stable-diffusion-inference
+export PRECISION=
+export OUTPUT_DIR=
+export SCRIPT=quickstart/online_inference.sh
+export OUTPUT_DIR=
+
+DOCKER_ARGS="--rm -it"
+
+docker run \
+ --privileged \
+ --device=/dev/dri \
+ --ipc=host \
+ --env PRECISION=${PRECISION} \
+ --env OUTPUT_DIR=${OUTPUT_DIR} \
+ --env http_proxy=${http_proxy} \
+ --env https_proxy=${https_proxy} \
+ --env no_proxy=${no_proxy} \
+ --volume ${OUTPUT_DIR}:${OUTPUT_DIR} \
+ ${DOCKER_ARGS} \
+ ${IMAGE_NAME} \
+ /bin/bash $SCRIPT
+```
+## Documentation and Sources
+
+[GitHub* Repository](https://github.com/IntelAI/models/tree/master/docker/flex-gpu)
+
+## Support
+Support for Intel® Extension for PyTorch* is found via the [Intel® AI Analytics Toolkit.](https://www.intel.com/content/www/us/en/developer/tools/oneapi/ai-analytics-toolkit.html#gs.qbretz) Additionally, the Intel® Extension for PyTorch* team tracks both bugs and enhancement requests using [GitHub issues](https://github.com/intel/intel-extension-for-pytorch/issues). Before submitting a suggestion or bug report, please search the GitHub issues to see if your issue has already been reported.
+
+## License Agreement
+
+LEGAL NOTICE: By accessing, downloading or using this software and any required dependent software (the “Software Package”), you agree to the terms and conditions of the software license agreements for the Software Package, which may also include notices, disclaimers, or license terms for third party software included with the Software Package. Please refer to the [license file](https://github.com/IntelAI/models/tree/master/third_party) for additional details.
diff --git a/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/README.md b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/README.md
new file mode 100644
index 000000000..2cce5cee0
--- /dev/null
+++ b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/README.md
@@ -0,0 +1,75 @@
+
+# Stable diffusion inference
+
+
+## Description
+
+This document has instructions for running Stable diffusion inference using
+Intel(R) Extension for PyTorch with GPU.
+
+
+## Software Requirements:
+- Intel® Data Center GPU Flex Series
+- Create and activate virtual environment.
+ ```bash
+ virtualenv -p python
+ source /bin/activate
+ ```
+- Follow [instructions](https://pypi.org/project/intel-extension-for-pytorch/) to install the latest IPEX version and other prerequisites.
+
+- Intel® oneAPI Base Toolkit: Need to install components of Intel® oneAPI Base Toolkit
+ - Intel® oneAPI DPC++ Compiler
+ - Intel® oneAPI Threading Building Blocks (oneTBB)
+ - Intel® oneAPI Math Kernel Library (oneMKL)
+ - Follow [instructions](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html?operatingsystem=linux&distributions=offline) to download and install the latest oneAPI Base Toolkit.
+
+ - Set environment variables for Intel® oneAPI Base Toolkit:
+ Default installation location `{ONEAPI_ROOT}` is `/opt/intel/oneapi` for root account, `${HOME}/intel/oneapi` for other accounts
+ ```bash
+ source {ONEAPI_ROOT}/compiler/latest/env/vars.sh
+ source {ONEAPI_ROOT}/mkl/latest/env/vars.sh
+ source {ONEAPI_ROOT}/tbb/latest/env/vars.sh
+ source {ONEAPI_ROOT}/mpi/latest/env/vars.sh
+ source {ONEAPI_ROOT}/ccl/latest/env/vars.sh
+ ```
+
+
+## Quick Start Scripts
+
+| Script name | Description |
+|-------------|-------------|
+| `online_inference.sh` | Inference for specified precision(FP32 or FP16) with batch size 1 on Flex series 170 |
+
+
+## Run the model
+* Clone the Model Zoo repository:
+ ```bash
+ git clone https://github.com/IntelAI/models.git
+ ```
+* Navigate to model zoo directory:
+ ```bash
+ # Navigate to the model zoo repo
+ cd models
+ ```
+
+### Run the model on Baremetal
+Set environment variables to run the quickstart script:
+```
+export PRECISION=
+export OUTPUT_DIR=
+
+# Optional envs
+export BATCH_SIZE=
+
+Run the model specific dependencies:
+NOTE: Installing dependencies in setup.sh may require root privilege
+./quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/setup.sh
+
+# Run a quickstart script
+./quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/online_inference.sh
+```
+
+
+## License
+
+[LICENSE](/LICENSE)
diff --git a/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/online_inference.sh b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/online_inference.sh
new file mode 100755
index 000000000..75f997466
--- /dev/null
+++ b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/online_inference.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2023 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.
+#
+
+MODEL_DIR=${MODEL_DIR-$PWD}
+BATCH_SIZE=${BATCH_SIZE-1}
+PRECISION=${PRECISION-fp32}
+
+if [[ -z $OUTPUT_DIR ]]; then
+ echo "The required environment variable OUTPUT_DIR has not been set"
+ exit 1
+fi
+
+echo "Stable Diffusion Inference Inference"
+if [[ ${PRECISION} == "fp32" ]]; then
+
+python -u ${MODEL_DIR}/models/generative-ai/pytorch/stable_diffusion/inference/gpu/main.py \
+ --save_image --channels_last 2>&1 | tee $OUTPUT_DIR/${PRECISION}_stable_diffusion_logs.txt
+
+elif [[ ${PRECISION} == "fp16" ]]; then
+
+python -u ${MODEL_DIR}/models/generative-ai/pytorch/stable_diffusion/inference/gpu/main.py \
+ --save_image --channels_last --precision fp16 2>&1 | tee $OUTPUT_DIR/${PRECISION}_stable_diffusion_logs.txt
+else
+ echo "Stable Diffusion currently supports fp32 and fp16 precisions."
+ exit 1
+fi
diff --git a/tools/docker/tests/pytorch/import-ipex.sh b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/setup.sh
similarity index 62%
rename from tools/docker/tests/pytorch/import-ipex.sh
rename to quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/setup.sh
index dd39f5161..a3d554c29 100755
--- a/tools/docker/tests/pytorch/import-ipex.sh
+++ b/quickstart/generative-ai/pytorch/stable_diffusion/inference/gpu/setup.sh
@@ -1,8 +1,6 @@
#!/usr/bin/env bash
#
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2021 Intel Corporation
+# Copyright (c) 2023 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,23 +15,13 @@
# limitations under the License.
#
+apt-get update
+apt-get install -y parallel
+apt-get install -y pciutils
-die() {
- echo $@
- exit 1
-}
-
-python -c '
-try:
- import intel_pytorch_extension
- print(True)
-except:
- print(False)
-'
-ipex_available=$?
+apt-get update
+apt-get install -y --no-install-recommends --fix-missing
+build-essential
+python3.10-dev
-if [[ $ipex_available -eq 0 ]]; then
- echo "PASS: IPEX is available"
-else
- die "FAIL: Could not import IPEX"
-fi
+pip install diffusers pytorch-fid transformers
diff --git a/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/DEVCATALOG.md b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/DEVCATALOG.md
new file mode 100644
index 000000000..78901d770
--- /dev/null
+++ b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/DEVCATALOG.md
@@ -0,0 +1,74 @@
+# Running Stable Diffusion Inference with FP32 and FP16 on Intel® Data Center GPU Flex Series using Intel® Extension for TensorFlow*
+
+## Overview
+
+This document has instructions for running Stable Diffusion inference using Intel® Extension for TensorFlow* with Intel® Data Center GPU Flex Series.
+
+
+## Requirements
+| Item | Detail |
+| ------ | ------- |
+| Host machine | Intel® Data Center GPU Flex Series |
+| Drivers | GPU-compatible drivers need to be installed: [Download Driver 647](https://dgpu-docs.intel.com/releases/stable_647_21_20230714.html)
+| Software | Docker* Installed |
+
+## Get Started
+
+### Dataset
+
+For accuracy measurement, please download the reference data file `img_arrays_for_acc.txt` from the link [here](https://github.com/intel/intel-extension-for-tensorflow/tree/main/examples/stable_diffussion_inference/nv_results). Set the `REFERENCE_RESULT_FILE` to point to the file.
+
+### Quick Start Scripts
+
+| Script name | Description |
+|:-------------:|:-------------:|
+| `online_inference` | Runs online inference for FP32,FP16 precisions on Flex series 170 |
+| `accuracy` | Runs batch inference for FP16 precision on Flex series 170 |
+
+## Run Using Docker
+
+### Set up Docker Image
+
+```bash
+docker pull intel/generative-ai:tf-flex-gpu-stable-diffusion-inference
+```
+
+### Run Docker Image
+
+The Stable Diffusion inference container contains scripts,models and libraries needed to run FP32 and FP16 inference. You will need to provide an output directory where log files will be written. To run the accuracy test, additionally, you will have to download and volume mount the reference data file.
+
+```bash
+export IMAGE_NAME=intel/generative-ai:tf-flex-gpu-stable-diffusion-inference
+export BATCH_SIZE=1
+export PRECISION=< provide fp32 or fp16 as precision input >
+export OUTPUT_DIR=
+export REFERENCE_RESULT_FILE=
+
+docker run \
+ --device=/dev/dri \
+ --ipc=host \
+ --privileged \
+ --env PRECISION=${PRECISION} \
+ --env BATCH_SIZE=${BATCH_SIZE} \
+ --env OUTPUT_DIR=${OUTPUT_DIR} \
+ --env REFERENCE_RESULT_FILE=${REFERENCE_RESULT_FILE} \
+ --env http_proxy=${http_proxy} \
+ --env https_proxy=${https_proxy} \
+ --env no_proxy=${no_proxy} \
+ --volume ${OUTPUT_DIR}:${OUTPUT_DIR} \
+ --volume ${REFERENCE_RESULT_FILE}:${REFERENCE_RESULT_FILE} \
+ --rm -it \
+ $IMAGE_NAME \
+ /bin/bash quickstart/.sh
+```
+
+## Documentation and Sources
+
+[GitHub* Repository](https://github.com/IntelAI/models/tree/master/docker/flex-gpu)
+
+## Support
+Support for Intel® Extension for TensorFlow* is found via the [Intel® AI Analytics Toolkit.](https://www.intel.com/content/www/us/en/developer/tools/oneapi/ai-analytics-toolkit.html#gs.qbretz) Additionally, the Intel® Extension for TensorFlow* team tracks both bugs and enhancement requests using [GitHub issues](https://github.com/intel/intel-extension-for-tensorflow/issues). Before submitting a suggestion or bug report, please search the GitHub issues to see if your issue has already been reported.
+
+## License Agreement
+
+LEGAL NOTICE: By accessing, downloading or using this software and any required dependent software (the “Software Package”), you agree to the terms and conditions of the software license agreements for the Software Package, which may also include notices, disclaimers, or license terms for third party software included with the Software Package. Please refer to the [license file](https://github.com/IntelAI/models/tree/master/third_party) for additional details.
diff --git a/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/README.md b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/README.md
new file mode 100755
index 000000000..ca34fee6c
--- /dev/null
+++ b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/README.md
@@ -0,0 +1,80 @@
+
+# Stable Diffusion inference
+
+
+## Description
+
+This document has instructions for running Stable Diffusion inference using
+Intel® Extension for TensorFlow with Intel® Data Center GPU Flex Series.
+
+
+## Software Requirements:
+- Intel® Data Center GPU Flex Series
+- Create and activate virtual environment.
+ ```bash
+ virtualenv -p python
+ source /bin/activate
+ ```
+- Follow [instructions](https://pypi.org/project/intel-extension-for-tensorflow) to install the latest ITEX version and other prerequisites.
+
+- Intel® oneAPI Base Toolkit: Need to install components of Intel® oneAPI Base Toolkit
+ - Intel® oneAPI DPC++ Compiler
+ - Intel® oneAPI Threading Building Blocks (oneTBB)
+ - Intel® oneAPI Math Kernel Library (oneMKL)
+ - Follow [instructions](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html?operatingsystem=linux&distributions=offline) to download and install the latest oneAPI Base Toolkit.
+
+ - Set environment variables for Intel® oneAPI Base Toolkit:
+ Default installation location `{ONEAPI_ROOT}` is `/opt/intel/oneapi` for root account, `${HOME}/intel/oneapi` for other accounts
+ ```bash
+ source {ONEAPI_ROOT}/compiler/latest/env/vars.sh
+ source {ONEAPI_ROOT}/mkl/latest/env/vars.sh
+ source {ONEAPI_ROOT}/tbb/latest/env/vars.sh
+ source {ONEAPI_ROOT}/mpi/latest/env/vars.sh
+ source {ONEAPI_ROOT}/ccl/latest/env/vars.sh
+ ```
+
+
+## Datasets
+
+For accuracy measurement, please download the reference data file `img_arrays_for_acc.txt` from the link [here](https://github.com/intel/intel-extension-for-tensorflow/tree/main/examples/stable_diffussion_inference/nv_results). Set the `REFERENCE_RESULT_FILE` to point to the file.
+
+
+## Quick Start Scripts
+
+| Script name | Description |
+|:-------------:|:-------------:|
+| `online_inference` | Runs online inference for FP32 and FP16 precisions on Flex series 170 |
+| `accuracy` | Runs batch inference for FP16 precision on Flex series 170 |
+
+
+## Run the model
+* Clone the Model Zoo repository:
+ ```bash
+ git clone https://github.com/IntelAI/models.git
+ ```
+
+### Run the model on Baremetal
+Navigate to the model zoo directory, and set environment variables:
+```
+cd models
+export OUTPUT_DIR=
+export PRECISION=< provide fp32 or fp16 as precision input >
+
+# Optional envs
+export BATCH_SIZE=
+
+# Set the following env only for accuracy script
+export REFERENCE_RESULT_FILE=
+
+Run the model specific dependencies:
+NOTE: Installing dependencies in setup.sh may require root privilege
+./quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/setup.sh
+
+Run quickstart script:
+./quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/.sh
+```
+
+
+## License
+
+[LICENSE](/LICENSE)
diff --git a/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/accuracy.sh b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/accuracy.sh
new file mode 100755
index 000000000..7f61e2324
--- /dev/null
+++ b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/accuracy.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2023 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.
+#
+
+MODEL_DIR=${MODEL_DIR-$PWD}
+
+echo 'MODEL_DIR='$MODEL_DIR
+echo 'OUTPUT_DIR='$OUTPUT_DIR
+echo 'PRECISION='$PRECISION
+echo 'REFERENCE_RESULT_FILE'$REFERENCE_RESULT_FILE
+
+# Create an array of input directories that are expected and then verify that they exist
+declare -A input_envs
+
+input_envs[OUTPUT_DIR]=${OUTPUT_DIR}
+input_envs[REFERENCE_RESULT_FILE]=${REFERENCE_RESULT_FILE}
+input_envs[PRECISION]=${PRECISION}
+
+for i in "${!input_envs[@]}"; do
+ var_name=$i
+ env_param=${input_envs[$i]}
+
+ if [[ -z $env_param ]]; then
+ echo "The required environment variable $var_name is not set" >&2
+ exit 1
+ fi
+done
+
+# Create the output directory in case it doesn't already exist
+mkdir -p ${OUTPUT_DIR}
+
+# If batch size env is not mentioned, then the workload will run with the default batch size.
+if [ -z "${BATCH_SIZE}" ]; then
+ BATCH_SIZE="1"
+ echo "Running with default batch size of ${BATCH_SIZE}"
+fi
+
+if [[ ${PRECISION} == "fp16" ]]; then
+ python ${MODEL_DIR}/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_accuracy.py --precision ${PRECISION} --load_ref_result --ref_result_dir ${REFERENCE_RESULT_FILE} --store_result_dir ${OUTPUT_DIR} 2>&1 | tee $OUTPUT_DIR/accuracy_stable_diffusion_logs.txt
+else
+ echo "Stable Diffusion accuracy currently supports fp16 precision."
+ exit 1
+fi
diff --git a/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/online_inference.sh b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/online_inference.sh
new file mode 100755
index 000000000..9eb3df32c
--- /dev/null
+++ b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/online_inference.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2023 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.
+#
+
+MODEL_DIR=${MODEL_DIR-$PWD}
+
+echo 'MODEL_DIR='$MODEL_DIR
+echo 'OUTPUT_DIR='$OUTPUT_DIR
+echo 'PRECISION='$PRECISION
+
+# Create an array of input directories that are expected and then verify that they exist
+declare -A input_envs
+
+input_envs[OUTPUT_DIR]=${OUTPUT_DIR}
+
+for i in "${!input_envs[@]}"; do
+ var_name=$i
+ env_param=${input_envs[$i]}
+
+ if [[ -z $env_param ]]; then
+ echo "The required environment variable $var_name is not set" >&2
+ exit 1
+ fi
+done
+
+# Create the output directory in case it doesn't already exist
+mkdir -p ${OUTPUT_DIR}
+
+# If batch size env is not mentioned, then the workload will run with the default batch size.
+if [ -z "${BATCH_SIZE}" ]; then
+ BATCH_SIZE="1"
+ echo "Running with default batch size of ${BATCH_SIZE}"
+fi
+echo "Stable Diffusion Inference Inference"
+if [[ ${PRECISION} == "fp32" || ${PRECISION} == "fp16" ]]; then
+ python -u ${MODEL_DIR}/models/generative-ai/tensorflow/stable_diffusion/inference/gpu/stable_diffusion_inference.py --precision ${PRECISION} --store_result_dir ${OUTPUT_DIR} 2>&1 | tee $OUTPUT_DIR/${PRECISION}_stable_diffusion_logs.txt
+else
+ echo "Stable Diffusion currently supports fp32 and fp16 precisions."
+ exit 1
+fi
diff --git a/tools/docker/tests/pytorch/import-torchccl.sh b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/setup.sh
similarity index 58%
rename from tools/docker/tests/pytorch/import-torchccl.sh
rename to quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/setup.sh
index 40f374fe8..3ebbad7e5 100755
--- a/tools/docker/tests/pytorch/import-torchccl.sh
+++ b/quickstart/generative-ai/tensorflow/stable_diffusion/inference/gpu/setup.sh
@@ -1,8 +1,6 @@
#!/usr/bin/env bash
#
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2021 Intel Corporation
+# Copyright (c) 2023 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,24 +15,16 @@
# limitations under the License.
#
+apt-get update
+apt-get install -y --no-install-recommends --fix-missing git
-die() {
- echo $@
- exit 1
-}
-
-python -c '
-try:
- import torch
- import torch_ccl
- print(True)
-except:
- print(False)
-'
-torchccl_available=$?
+git clone https://github.com/keras-team/keras-cv.git
+cd keras-cv
+git reset --hard 66fa74b6a2a0bb1e563ae8bce66496b118b95200
+mv ../models/generative-ai/tensorflow/stable_diffusion/inference/gpu/patch .
+git apply patch
+cd -
+pip install matplotlib
+pip install .
-if [[ $torchccl_available -eq 0 ]]; then
- echo "PASS: Torch-CCL is available"
-else
- die "FAIL: Could not import torch_ccl"
-fi
+python -m pip install scikit-image
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md
index 0d6b2683c..4836028bd 100644
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md
+++ b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md
@@ -9,7 +9,7 @@ This document has instructions for running ResNet50v1.5 inference using Intel®
| Item | Detail |
| ------ | ------- |
| Host machine | Intel® Data Center GPU Flex Series |
-| Drivers | GPU-compatible drivers need to be installed: [Download Driver 602](https://dgpu-docs.intel.com/installation-guides/ubuntu/ubuntu-jammy-dc.html#step-1-add-package-repository)
+| Drivers | GPU-compatible drivers need to be installed: [Download Driver 647](https://dgpu-docs.intel.com/releases/stable_647_21_20230714.html)
| Software | Docker* Installed |
## Get Started
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README.md b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README.md
deleted file mode 100644
index ff6a12c00..000000000
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README.md
+++ /dev/null
@@ -1,124 +0,0 @@
-
-# ResNet50v1.5 inference
-
-
-## Description
-
-This document has instructions for running ResNet50v1.5 inference using
-Intel(R) Extension for PyTorch with GPU.
-
-
-## Hardware Requirements:
-- Intel® Data Center GPU Flex Series
-
-## Software Requirements:
-- Ubuntu 20.04 (64-bit)
-- Intel GPU Drivers: Intel® Data Center GPU Flex Series [419.40](https://dgpu-docs.intel.com/releases/stable_419_40_20220914.html)
-
- |Release|OS|Intel GPU|Install Intel GPU Driver|
- |-|-|-|-|
- |v1.0.0|Ubuntu 20.04|Intel® Data Center GPU Flex Series| Refer to the [Installation Guides](https://dgpu-docs.intel.com/installation-guides/ubuntu/ubuntu-focal-dc.html) for latest driver installation. If install the verified Intel® Data Center GPU Flex Series [419.40](https://dgpu-docs.intel.com/releases/stable_419_40_20220914.html), please append the specific version after components, such as `apt-get install intel-opencl-icd=22.28.23726.1+i419~u20.04`|
-
-- Intel® oneAPI Base Toolkit 2022.3: Need to install components of Intel® oneAPI Base Toolkit
- - Intel® oneAPI DPC++ Compiler
- - Intel® oneAPI Math Kernel Library (oneMKL)
- * Download and install the verified DPC++ compiler and oneMKL in Ubuntu 20.04.
-
- ```bash
- wget https://registrationcenter-download.intel.com/akdlm/irc_nas/18852/l_BaseKit_p_2022.3.0.8767_offline.sh
- # 4 components are necessary: DPC++/C++ Compiler, DPC++ Libiary, Threading Building Blocks and oneMKL
- sh ./l_BaseKit_p_2022.3.0.8767_offline.sh
- ```
- For any more details, please follow the procedure in https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html.
-
- - Set environment variables:
- Default installation location {ONEAPI_ROOT} is /opt/intel/oneapi for root account, ${HOME}/intel/oneapi for other accounts
- ```bash
- source {ONEAPI_ROOT}/setvars.sh
- ```
-
-
-
-## Datasets
-
-The [ImageNet](http://www.image-net.org/) validation dataset is used.
-
-Download and extract the ImageNet2012 dataset from http://www.image-net.org/,
-then move validation images to labeled subfolders, using
-[the valprep.sh shell script](https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh)
-
-A after running the data prep script, your folder structure should look something like this:
-
-```
-imagenet
-└── val
- ├── ILSVRC2012_img_val.tar
- ├── n01440764
- │ ├── ILSVRC2012_val_00000293.JPEG
- │ ├── ILSVRC2012_val_00002138.JPEG
- │ ├── ILSVRC2012_val_00003014.JPEG
- │ ├── ILSVRC2012_val_00006697.JPEG
- │ └── ...
- └── ...
-```
-The folder that contains the `val` directory should be set as the
-`DATASET_DIR`
-(for example: `export DATASET_DIR=/home//imagenet`).
-
-
-## Quick Start Scripts
-
-| Script name | Description |
-|-------------|-------------|
-| inference_block_format.sh | Runs ResNet50 inference (block format) for the specified precision (int8) |
-
-
-## Run the model
-Install the following pre-requisites:
-* Python version 3.9
-* Create and activate virtual environment.
- ```bash
- virtualenv -p python
- source /bin/activate
- ```
-* Install PyTorch and Intel® Extension for PyTorch for GPU (IPEX):
- ```bash
- python -m pip install torch==1.10.0a0 -f https://developer.intel.com/ipex-whl-stable-xpu
- python -m pip install numpy==1.23.4
- python -m pip install intel_extension_for_pytorch==1.10.200+gpu -f https://developer.intel.com/ipex-whl-stable-xpu
- ```
- To verify that PyTorch and IPEX are correctly installed:
- ```bash
- python -c "import torch;print(torch.device('xpu'))" # Sample output: "xpu"
- python -c "import intel_extension_for_pytorch as ipex;print(ipex.xpu.is_available())" #Sample output True
- python -c "import intel_extension_for_pytorch as ipex;print(ipex.xpu.has_onemkl())" # Sample output: True
- ```
-* Navigate to ResNet50v1.5 inference directory and install model specific dependencies for the workload:
- ```bash
- cd quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu
- ./setup.sh
- cd -
- ```
-
-See the [datasets section](#datasets) of this document for instructions on
-downloading and preprocessing the ImageNet dataset. The path to the ImageNet
-dataset files will need to be set as the `DATASET_DIR` environment variable
-prior to running a [quickstart script](#quick-start-scripts).
-
-### Run the model on Baremetal
-Set environment variables for the path to your dataset, an output directory, and specify the precision to run the quickstart script:
-```
-To run with ImageNet data, the dataset directory will need to be specified in addition to an output directory and precision.
-export DATASET_DIR=
-export OUTPUT_DIR=
-export PRECISION=int8
-
-# Run a quickstart script
-./quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_block_format.sh
-```
-
-
-## License
-
-[LICENSE](/LICENSE)
-
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README_Flex_Series.md b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README_Flex_Series.md
index 6effd433d..43bd13e27 100644
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README_Flex_Series.md
+++ b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/README_Flex_Series.md
@@ -10,7 +10,12 @@ Intel(R) Extension for PyTorch with GPU.
## Software Requirements:
- Intel® Data Center GPU Flex Series
-- Follow [instructions](https://intel.github.io/intel-extension-for-pytorch/xpu/latest/tutorials/installation.html) to install the latest IPEX version and other prerequisites.
+- Create and activate virtual environment.
+ ```bash
+ virtualenv -p python
+ source /bin/activate
+ ```
+- Follow [instructions](https://pypi.org/project/intel-extension-for-pytorch/) to install the latest IPEX version and other prerequisites.
- Intel® oneAPI Base Toolkit: Need to install components of Intel® oneAPI Base Toolkit
- Intel® oneAPI DPC++ Compiler
@@ -66,19 +71,12 @@ The folder that contains the `val` directory should be set as the
## Run the model
-Install the following pre-requisites:
-* Create and activate virtual environment.
- ```bash
- virtualenv -p python
- source /bin/activate
- ```
* Clone the Model Zoo repository:
```bash
git clone https://github.com/IntelAI/models.git
```
-* Navigate to ResNet50v1.5 inference directory:
+* Navigate to the model zoo directory:
```bash
- # Navigate to the model zoo repo
cd models
```
@@ -90,12 +88,11 @@ prior to running a [quickstart script](#quick-start-scripts).
### Run the model on Baremetal
Set environment variables for the path to your dataset, an output directory to run the quickstart script:
```
-To run with ImageNet data, the dataset directory will need to be specified in addition to an output directory and precision.
export DATASET_DIR=
export OUTPUT_DIR=
# Optional envs
-export BATCH_SIZE=
+export BATCH_SIZE=
# Run a quickstart script
./quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_block_format.sh
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/flex_multi_card_batch_inference.sh b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/flex_multi_card_batch_inference.sh
old mode 100644
new mode 100755
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/flex_multi_card_online_inference.sh b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/flex_multi_card_online_inference.sh
old mode 100644
new mode 100755
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_channels_last.sh b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_channels_last.sh
deleted file mode 100644
index 8eada1140..000000000
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_channels_last.sh
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (c) 2022 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.
-#
-
-MODEL_DIR=${MODEL_DIR-$PWD}
-BATCH_SIZE=${BATCH_SIZE-1024}
-NUM_ITERATIONS=${NUM_ITERATIONS-10}
-
-
-
-source ${MODEL_DIR}/quickstart/setvars.sh
-
-if [[ -z "${DATASET_DIR}" ]]; then
- echo "The required environment variable DATASET_DIR has not been set"
- exit 1
-fi
-
-if [[ ! -d "${DATASET_DIR}" ]]; then
- echo "The DATASET_DIR '${DATASET_DIR}' does not exist"
- exit 1
-fi
-
-if [[ -z $OUTPUT_DIR ]]; then
- echo "The required environment variable OUTPUT_DIR has not been set"
- exit 1
-fi
-
-# Create the output directory, if it doesn't already exist
-mkdir -p $OUTPUT_DIR
-
-if [[ -z "${PRECISION}" ]]; then
- echo "The required environment variable PRECISION has not been set."
- echo "Please set PRECISION to fp32, fp16, or bf16."
- exit 1
-fi
-
-resnet50_log_analysis() {
- # $1 : src raw log
- # $2 : dst format log
- # $3 : inference or training
- # $4 : bs
-
- bs=$4
- if [ -f $2 ]; then
- rm $2
- fi
-
- if [ "inference" == "$3" ]; then
- echo -e 'Batch Size: ' $bs >$2
- cat $1 | grep Test | tail -n6 | head -n5 |
- awk -v bs=${bs} -F ' ' '{a+=$5}END{printf "Performance Benchmark Time: %.3f sec, Throughput: %.2f FPS\n", a/5, bs*5/a}' >>$2
- cat $1 | tail -n2 | grep "Acc@1" | awk -F ' ' '{printf "Accuracy: acc@1 %.2f\n", $3}' >>$2
- elif [ "training" == "$3" ]; then
- echo -e 'Batch Size: ' $bs >$2
- cat $1 | grep Epoch | tail -n1 | awk -v bs=${bs} -F ' ' '{printf "Performance Benchmark Time: %.3f sec, Throughput: %.2f FPS\nAccuracy: Loss %.4f\n", $4, bs/$4, $10}' >>$2
- else
- echo -e 'Invalid input! Only inference or training are supported.'
- exit 0
- fi
-}
-
-if [[ $PRECISION == "int8" ]]; then
- PRECISION_ARG="--int8 1"
-else
- echo "The specified precision '${PRECISION}' is unsupported."
- exit 1
-fi
-
-echo "resnet50 ${PRECISION} inference block nhwc"
-IPEX_XPU_ONEDNN_LAYOUT=1 python -u models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py \
- -a resnet50 \
- -b ${BATCH_SIZE} \
- --xpu 0 \
- -e \
- --pretrained \
- --int8 1 \
- --num-iterations ${NUM_ITERATIONS} \
- ${DATASET_DIR} \
- --benchmark 1 \
- --channels-last 2>&1 | tee ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_block_nhwc_t0_raw.log
-resnet50_log_analysis ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_block_nhwc_t0_raw.log ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_block_nhwc_t0.log inference ${BATCH_SIZE}
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_plain_format.sh b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_plain_format.sh
deleted file mode 100755
index 396de06b6..000000000
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_plain_format.sh
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (c) 2021 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.
-#
-
-MODEL_DIR=${MODEL_DIR-$PWD}
-BATCH_SIZE=${BATCH_SIZE-1024}
-NUM_ITERATIONS=${NUM_ITERATIONS-10}
-
-
-
-source ${MODEL_DIR}/quickstart/setvars.sh
-
-if [[ -z "${DATASET_DIR}" ]]; then
- echo "The required environment variable DATASET_DIR has not been set"
- exit 1
-fi
-
-if [[ ! -d "${DATASET_DIR}" ]]; then
- echo "The DATASET_DIR '${DATASET_DIR}' does not exist"
- exit 1
-fi
-
-if [[ -z $OUTPUT_DIR ]]; then
- echo "The required environment variable OUTPUT_DIR has not been set"
- exit 1
-fi
-
-# Create the output directory, if it doesn't already exist
-mkdir -p $OUTPUT_DIR
-
-if [[ -z "${PRECISION}" ]]; then
- echo "The required environment variable PRECISION has not been set."
- echo "Please set PRECISION to fp32, fp16, or bf16."
- exit 1
-fi
-
-resnet50_log_analysis() {
- # $1 : src raw log
- # $2 : dst format log
- # $3 : inference or training
- # $4 : bs
-
- bs=$4
- if [ -f $2 ]; then
- rm $2
- fi
-
- if [ "inference" == "$3" ]; then
- echo -e 'Batch Size: ' $bs >$2
- cat $1 | grep Test | tail -n6 | head -n5 |
- awk -v bs=${bs} -F ' ' '{a+=$5}END{printf "Performance Benchmark Time: %.3f sec, Throughput: %.2f FPS\n", a/5, bs*5/a}' >>$2
- cat $1 | tail -n2 | grep "Acc@1" | awk -F ' ' '{printf "Accuracy: acc@1 %.2f\n", $3}' >>$2
- elif [ "training" == "$3" ]; then
- echo -e 'Batch Size: ' $bs >$2
- cat $1 | grep Epoch | tail -n1 | awk -v bs=${bs} -F ' ' '{printf "Performance Benchmark Time: %.3f sec, Throughput: %.2f FPS\nAccuracy: Loss %.4f\n", $4, bs/$4, $10}' >>$2
- else
- echo -e 'Invalid input! Only inference or training are supported.'
- exit 0
- fi
-}
-
-if [[ $PRECISION == "bf16" ]]; then
- echo "resnet50 ${PRECISION} inference plain nhwc"
- python -u models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py \
- -a resnet50 \
- -b ${BATCH_SIZE} \
- --xpu 0 \
- -e \
- --pretrained \
- --num-iterations ${NUM_ITERATIONS} \
- --bf16 1\
- --channels-last \
- --jit-trace \
- ${DATASET_DIR} 2>&1 | tee ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_plain_nhwc_t0_raw.log
- resnet50_log_analysis ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_plain_nhwc_t0_raw.log ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_plain_nhwc_t0.log inference ${BATCH_SIZE}
-else
- echo "The specified precision '${PRECISION}' is unsupported."
- exit 1
\ No newline at end of file
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_synthetic_data.sh b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_synthetic_data.sh
deleted file mode 100644
index 16395b2c1..000000000
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/inference_synthetic_data.sh
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (c) 2021 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.
-#
-
-MODEL_DIR=${MODEL_DIR-$PWD}
-BATCH_SIZE=${BATCH_SIZE-1024}
-
-# Number of iterations to run after running 5 dry run/warm up iterations
-NUM_ITERATIONS=${NUM_ITERATIONS-500}
-
-source ${MODEL_DIR}/quickstart/setvars.sh
-
-if [[ -z $OUTPUT_DIR ]]; then
- echo "The required environment variable OUTPUT_DIR has not been set"
- exit 1
-fi
-
-# Create the output directory, if it doesn't already exist
-mkdir -p $OUTPUT_DIR
-
-# if [[ -z "${PRECISION}" ]]; then
-# echo "The required environment variable PRECISION has not been set."
-# echo "Please set PRECISION to fp32, fp16, or bf16."
-# exit 1
-# fi
-
-resnet50_log_analysis() {
- # $1 : src raw log
- # $2 : dst format log
- # $3 : inference or training
- # $4 : bs
-
- bs=$4
- if [ -f $2 ]; then
- rm $2
- fi
-
- if [ "inference" == "$3" ]; then
- echo -e 'Batch Size: ' $bs >$2
- cat $1 | grep Test | tail -n6 | head -n5 |
- awk -v bs=${bs} -F ' ' '{a+=$5}END{printf "Performance Benchmark Time: %.3f sec, Throughput: %.2f FPS\n", a/5, bs*5/a}' >>$2
- cat $1 | tail -n2 | grep "Acc@1" | awk -F ' ' '{printf "Accuracy: acc@1 %.2f\n", $3}' >>$2
- elif [ "training" == "$3" ]; then
- echo -e 'Batch Size: ' $bs >$2
- cat $1 | grep Epoch | tail -n1 | awk -v bs=${bs} -F ' ' '{printf "Performance Benchmark Time: %.3f sec, Throughput: %.2f FPS\nAccuracy: Loss %.4f\n", $4, bs/$4, $10}' >>$2
- else
- echo -e 'Invalid input! Only inference or training are supported.'
- exit 0
- fi
-}
-
-echo "resnet50 int8 inference with synthetic data"
-IPEX_XPU_ONEDNN_LAYOUT=1 python -u models/image_recognition/pytorch/resnet50v1_5/inference/gpu/main.py \
- -a resnet50 \
- -e \
- -b ${BATCH_SIZE} \
- --pretrained \
- --xpu 0 \
- --num-iterations ${NUM_ITERATIONS} \
- --int8 1 \
- --benchmark 1 \
- --dummy \
- ${OUTPUT_DIR} 2>&1 | tee ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_synthetic_raw.log
-resnet50_log_analysis ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_synthetic_raw.log ${OUTPUT_DIR}/resnet50-jit_${PRECISION}_inf_synthetic.log inference ${BATCH_SIZE}
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/run.sh b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/run.sh
deleted file mode 100755
index e5562af91..000000000
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/run.sh
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (c) 2021 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.
-#
-
-if [ -z "${OUTPUT_DIR}" ]; then
- echo "The required environment variable OUTPUT_DIR has not been set"
- exit 1
-fi
-
-if [ -z "${PRECISION}" ]; then
- echo "The required environment variable PRECISION has not been set"
- exit 1
-fi
-
-IMAGE_NAME=${IMAGE_NAME:-model-zoo:pytorch-gpu-resnet50v1-5-inference}
-DOCKER_ARGS=${DOCKER_ARGS:---rm -it}
-
-export SCRIPT="${SCRIPT:-inference_block_format.sh}"
-
-# The dataset directory is not required for the synthetic data script
-if [[ ${SCRIPT} != inference_synthetic_data.sh ]]; then
- if [ -z "${DATASET_DIR}" ]; then
- echo "The required environment variable DATASET_DIR has not been set"
- exit 1
- fi
-fi
-
-if [[ ${SCRIPT} != quickstart* ]]; then
- SCRIPT="quickstart/$SCRIPT"
-fi
-
-VIDEO=$(getent group video | sed -E 's,^video:[^:]*:([^:]*):.*$,\1,')
-RENDER=$(getent group render | sed -E 's,^render:[^:]*:([^:]*):.*$,\1,')
-
-test -z "$RENDER" || RENDER_GROUP="--group-add ${RENDER}"
-
-docker run \
- --group-add ${VIDEO} \
- ${RENDER_GROUP} \
- --device=/dev/dri \
- --ipc=host \
- --env DATASET_DIR=${DATASET_DIR} \
- --env PRECISION=${PRECISION} \
- --env OUTPUT_DIR=${OUTPUT_DIR} \
- --env http_proxy=${http_proxy} \
- --env https_proxy=${https_proxy} \
- --env no_proxy=${no_proxy} \
- --volume ${DATASET_DIR}:${DATASET_DIR} \
- --volume ${OUTPUT_DIR}:${OUTPUT_DIR} \
- ${DOCKER_ARGS} \
- $IMAGE_NAME \
- /bin/bash $SCRIPT
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/wrapper_README.md b/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/wrapper_README.md
deleted file mode 100644
index 06545f818..000000000
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/wrapper_README.md
+++ /dev/null
@@ -1,116 +0,0 @@
-
-# ResNet50v1.5 inference
-
-
-## Description
-
-This document has instructions for running ResNet50v1.5 inference using
-Intel(R) Extension for PyTorch with GPU.
-
-
-## Model Package
-
-The model package includes the scripts and libraries needed to
-build and run ResNet50v1.5 inference using a docker container. Note that
-this model container uses the PyTorch IPEX GPU container as it's base,
-and it requires the `model-zoo:pytorch-ipex-gpu` image to be built before
-the model container is built.
-```
-pytorch-gpu-resnet50v1-5-inference
-├── build.sh
-├── info.txt
-├── licenses
-│ ├── LICENSE
-│ └── third_party
-├── model_packages
-│ └── pytorch-gpu-resnet50v1-5-inference.tar.gz
-├── pytorch-gpu-resnet50v1-5-inference.Dockerfile
-├── README.md
-└── run.sh
-```
-
-
-## Datasets
-
-The [ImageNet](http://www.image-net.org/) validation dataset is used.
-
-Download and extract the ImageNet2012 dataset from http://www.image-net.org/,
-then move validation images to labeled subfolders, using
-[the valprep.sh shell script](https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh)
-
-A after running the data prep script, your folder structure should look something like this:
-
-```
-imagenet
-└── val
- ├── ILSVRC2012_img_val.tar
- ├── n01440764
- │ ├── ILSVRC2012_val_00000293.JPEG
- │ ├── ILSVRC2012_val_00002138.JPEG
- │ ├── ILSVRC2012_val_00003014.JPEG
- │ ├── ILSVRC2012_val_00006697.JPEG
- │ └── ...
- └── ...
-```
-The folder that contains the `val` directory should be set as the
-`DATASET_DIR`
-(for example: `export DATASET_DIR=/home//imagenet`).
-
-
-## Quick Start Scripts
-
-| Script name | Description |
-|-------------|-------------|
-| inference_block_format.sh | Runs ResNet50 inference (block format) for the specified precision (int8) |
-
-
-## Docker
-
-Requirements:
-* Host machine has Intel® Data Center GPU Flex Series.
-* Host machine has the Intel® Data Center GPU Flex Series Ubuntu driver. Please follow the [link](https://registrationcenter.intel.com/en/products/download/4125/) to download.
-* Host machine has Docker installed.
-* Download and build the Intel® Extension for PyTorch (IPEX) container using the [link](https://registrationcenter.intel.com/en/products/subscription/956/).
- (`model-zoo:pytorch-ipex-gpu`)
-
-Prior to building the ResNet50v1.5 inference container, ensure that you have
-built the IPEX container (`model-zoo:pytorch-ipex-gpu`).
-
-[Extract the package](#model-package), then use the `build.sh`
-script to build the container. After the container has been built, you can
-run the model inference using the `run.sh` script.
-Set environment variables for the path to [imagenet dataset](#datasets),
-the precision to run, and tan output directory for logs.
-
-The `run.sh` script will execute one of the [quickstart](#quick-start-scripts) script
-using the container that was just built. By default, the
-`inference_block_format.sh` script will be run. To run a different script,
-specify the script name of the quickstart script using the `SCRIPT`
-environment variable. See the snippet below for an example.
-
-> Note: Ensure that your system has the proxy environment variables
-> set (if needed), otherwise the container build may fail when trying to pull external
-> dependencies (like apt-get and pip installs).
-
-```
-# Extract the package
-tar -xzf pytorch-gpu-resnet50v1-5-inference.tar.gz
-cd pytorch-gpu-resnet50v1-5-inference
-
-# Build the container
-./build.sh
-
-# Set the required environment vars
-export DATASET_DIR=
-export PRECISION=int8
-export OUTPUT_DIR=
-
-# Run the container with the default inference_block_format.sh script
-./run.sh
-```
-
-
-## License
-
-[LICENSE](/LICENSE)
-
diff --git a/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/DEVCATALOG.md b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/DEVCATALOG.md
new file mode 100644
index 000000000..262578df7
--- /dev/null
+++ b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/DEVCATALOG.md
@@ -0,0 +1,93 @@
+# Running EfficientNet Inference with Int8 on Intel® Data Center GPU Flex Series using Intel® Extension for TensorFlow*
+
+## Overview
+
+This document has instructions for running EfficientNet inference using Intel® Extension for TensorFlow* with Intel® Data Center GPU Flex Series.
+
+## Requirements
+| Item | Detail |
+| ------ | ------- |
+| Host machine | Intel® Data Center GPU Flex Series 170 and 140 |
+| Drivers | GPU-compatible drivers need to be installed: [Download Driver 647](https://dgpu-docs.intel.com/releases/stable_647_21_20230714.html)
+| Software | Docker* Installed |
+
+## Get Started
+
+### Download Dataset
+The [ImageNet](http://www.image-net.org/) validation dataset is used.
+
+Download and extract the ImageNet2012 dataset from http://www.image-net.org/, then move validation images to labeled subfolders, using [the valprep.sh shell script](https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh)
+
+A after running the data prep script, your folder structure should look something like this:
+
+```
+imagenet
+└── val
+ ├── ILSVRC2012_img_val.tar
+ ├── n01440764
+ │ ├── ILSVRC2012_val_00000293.JPEG
+ │ ├── ILSVRC2012_val_00002138.JPEG
+ │ ├── ILSVRC2012_val_00003014.JPEG
+ │ ├── ILSVRC2012_val_00006697.JPEG
+ │ └── ...
+ └── ...
+```
+The folder that contains the `val` directory should be set as the`IMAGE_FILE`
+(for example: `export IMAGE_FILE=/home//imagenet/ILSVRC2012_val_00006697.JPEG`).
+### Quick Start Scripts
+
+| Script name | Description |
+|:-------------:|:-------------:|
+| `batch_inference` | Runs EfficientNet B0,B3 batch inference for fp16 precision on Flex series 170 and 140 |
+
+## Run Using Docker
+
+### Set up Docker Image
+
+```bash
+docker pull intel/image-recognition:tf-flex-gpu-efficientnet-inference
+```
+### Run Docker Image
+
+The EfficientNet inference container contains scripts,models and libraries needed to run fp16 inference. You will need to provide an output directory where log files will be written. Additionally, you will have to download and volume mount an image from the ImageNet dataset.
+
+```bash
+export IMAGE_NAME=intel/image-recognition:tf-flex-gpu-efficientnet-inference
+export MODEL_NAME=
+export BATCH_SIZE=
+export PRECISION=
+export OUTPUT_DIR=
+export IMAGE_FILE=
+export GPU_TYPE=
+
+docker run \
+ --device=/dev/dri \
+ --ipc=host \
+ --privileged \
+ --env PRECISION=${PRECISION} \
+ --env BATCH_SIZE=${BATCH_SIZE} \
+ --env MODEL_NAME=${MODEL_NAME} \
+ --env OUTPUT_DIR=${OUTPUT_DIR} \
+ --env PRECSION=${PRECISION} \
+ --env IMAGE_FILE=${IMAGE_FILE} \
+ --env GPU_TYPE=${GPU_TYPE} \
+ --env http_proxy=${http_proxy} \
+ --env https_proxy=${https_proxy} \
+ --env no_proxy=${no_proxy} \
+ --volume ${OUTPUT_DIR}:${OUTPUT_DIR} \
+ --volume ${IMAGE_FILE}:${IMAGE_FILE} \
+ --rm -it \
+ $IMAGE_NAME \
+ /bin/bash quickstart/batch_inference.sh
+ ```
+**Note:** Add `--cap-add=SYS_NICE` to the `docker run` command for executing `batch_inference.sh` on Flex series 140.
+ ## Documentation and Sources
+
+[GitHub* Repository](https://github.com/IntelAI/models/tree/master/dockers/flex-gpu)
+
+## Support
+Support for Intel® Extension for TensorFlow* is found via the [Intel® AI Analytics Toolkit.](https://www.intel.com/content/www/us/en/developer/tools/oneapi/ai-analytics-toolkit.html#gs.qbretz) Additionally, the Intel® Extension for TensorFlow* team tracks both bugs and enhancement requests using [GitHub issues](https://github.com/intel/intel-extension-for-tensorflow/issues). Before submitting a suggestion or bug report, please search the GitHub issues to see if your issue has already been reported.
+
+## License Agreement
+
+LEGAL NOTICE: By accessing, downloading or using this software and any required dependent software (the “Software Package”), you agree to the terms and conditions of the software license agreements for the Software Package, which may also include notices, disclaimers, or license terms for third party software included with the Software Package. Please refer to the [license file](https://github.com/IntelAI/models/tree/master/third_party) for additional details.
diff --git a/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/README.md b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/README.md
new file mode 100644
index 000000000..ca6b82d87
--- /dev/null
+++ b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/README.md
@@ -0,0 +1,102 @@
+
+# EfficientNet inference
+
+
+## Description
+
+This document has instructions for running EfficientNet inference using
+Intel® Extension for TensorFlow with Intel® Data Center GPU Flex Series.
+
+
+## Software Requirements:
+- Intel® Data Center GPU Flex Series 170 and 140
+- Create and activate virtual environment.
+ ```bash
+ virtualenv -p python
+ source /bin/activate
+ ```
+- Follow [instructions](https://pypi.org/project/intel-extension-for-tensorflow) to install the latest ITEX version and other prerequisites.
+
+- Intel® oneAPI Base Toolkit: Need to install components of Intel® oneAPI Base Toolkit
+ - Intel® oneAPI DPC++ Compiler
+ - Intel® oneAPI Threading Building Blocks (oneTBB)
+ - Intel® oneAPI Math Kernel Library (oneMKL)
+ - Follow [instructions](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html?operatingsystem=linux&distributions=offline) to download and install the latest oneAPI Base Toolkit.
+
+ - Set environment variables for Intel® oneAPI Base Toolkit:
+ Default installation location `{ONEAPI_ROOT}` is `/opt/intel/oneapi` for root account, `${HOME}/intel/oneapi` for other accounts
+ ```bash
+ source {ONEAPI_ROOT}/compiler/latest/env/vars.sh
+ source {ONEAPI_ROOT}/mkl/latest/env/vars.sh
+ source {ONEAPI_ROOT}/tbb/latest/env/vars.sh
+ source {ONEAPI_ROOT}/mpi/latest/env/vars.sh
+ source {ONEAPI_ROOT}/ccl/latest/env/vars.sh
+ ```
+
+
+## Datasets
+
+The [ImageNet](http://www.image-net.org/) validation dataset is used.
+
+Download and extract the ImageNet2012 dataset from http://www.image-net.org/, then move validation images to labeled subfolders, using [the valprep.sh shell script](https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh)
+
+A after running the data prep script, your folder structure should look something like this:
+
+```
+imagenet
+└── val
+ ├── ILSVRC2012_img_val.tar
+ ├── n01440764
+ │ ├── ILSVRC2012_val_00000293.JPEG
+ │ ├── ILSVRC2012_val_00002138.JPEG
+ │ ├── ILSVRC2012_val_00003014.JPEG
+ │ ├── ILSVRC2012_val_00006697.JPEG
+ │ └── ...
+ └── ...
+```
+The folder that contains the `val` directory should be set as the`IMAGE_FILE`
+(for example: `export IMAGE_FILE=/home//imagenet/ILSVRC2012_val_00006697.JPEG`).
+
+
+## Quick Start Scripts
+
+| Script name | Description |
+|:-------------:|:-------------:|
+| `batch_inference` | Runs EfficientNet B0,B3 batch inference for fp16 precision on Flex series 170 and 140 |
+
+
+## Run the model
+* Clone the Model Zoo repository:
+ ```bash
+ git clone https://github.com/IntelAI/models.git
+ ```
+
+See the [datasets section](#datasets) of this document for instructions on
+downloading and preprocessing the ImageNet dataset. The path to the ImageNet
+will need to be set as the `DATASET_DIR` environment variable
+prior to running a [quickstart script](#quick-start-scripts).
+
+### Run the model on Baremetal
+Navigate to the Model Zoo directory, and set environment variables:
+```
+cd models
+export OUTPUT_DIR=
+export MODEL_NAME=
+export PRECISION=fp16
+export IMAGE_FILE=
+export GPU_TYPE=
+
+# Optional envs
+export BATCH_SIZE=
+
+Run model specific dependencies:
+./quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/setup.sh
+
+Run quickstart script:
+./quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/batch_inference.sh
+```
+
+
+## License
+
+[LICENSE](/LICENSE)
diff --git a/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/batch_inference.sh b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/batch_inference.sh
new file mode 100755
index 000000000..74c0d7311
--- /dev/null
+++ b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/batch_inference.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2023 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.
+#
+
+MODEL_DIR=${MODEL_DIR-$PWD}
+
+echo 'MODEL_DIR='$MODEL_DIR
+echo 'PRECISION='$PRECISION
+echo 'OUTPUT_DIR='$OUTPUT_DIR
+echo 'GPU_TYPE='$GPU_TYPE
+
+echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
+
+export TF_NUM_INTEROP_THREADS=1
+export ITEX_LAYOUT_OPT=1
+
+# Create an array of input directories that are expected and then verify that they exist
+declare -A input_envs
+input_envs[OUTPUT_DIR]=${OUTPUT_DIR}
+input_envs[MODEL_NAME]=${MODEL_NAME}
+input_envs[IMAGE_FILE]=${IMAGE_FILE}
+input_envs[GPU_TYPE]=${GPU_TYPE}
+input_envs[PRECISION]=${PRECISION}
+
+for i in "${!input_envs[@]}"; do
+ var_name=$i
+ env_param=${input_envs[$i]}
+
+ if [[ -z $env_param ]]; then
+ echo "The required environment variable $var_name is not set" >&2
+ exit 1
+ fi
+done
+
+mkdir -p ${OUTPUT_DIR}
+
+# If batch size env is not mentioned, then the workload will run with the default batch size.
+if [ -z "${BATCH_SIZE}" ]; then
+ BATCH_SIZE="64"
+ echo "Running with default batch size of ${BATCH_SIZE}"
+fi
+
+declare -a str
+device_id=$( lspci | grep -i display | sed -n '1p' | awk '{print $7}' )
+num_devs=$(lspci | grep -i display | awk '{print $7}' | wc -l)
+num_threads=1
+k=0
+
+if [[ "$PRECISION" == "fp16" ]];then
+ if [[ "$GPU_TYPE" == flex_170 ]]; then
+ if [[ ${device_id} == "56c0" ]]; then
+ echo "${MODEL_NAME} FP16 inference on Flex 170"
+ python -u $MODEL_DIR/models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py git-m ${MODEL_NAME} -b ${BATCH_SIZE} -i ${IMAGE_FILE} 2>&1 | tee $OUTPUT_DIR/${MODEL_NAME}__xpu_inf_${BATCH_SIZE}.log
+ fi
+ elif [[ "$GPU_TYPE" == flex_140 ]]; then
+ if [[ ${device_id} == "56c1" ]]; then
+ if [[ $BATCH_SIZE == 1 ]]; then
+ echo "${MODEL_NAME} FP16 inference with BATCH_SIZE 1 on Flex 140"
+ for i in $( eval echo {0..$((num_devs-1))} )
+ do
+ for j in $( eval echo {1..$num_threads} )
+ do
+ str+=("ZE_AFFINITY_MASK="${i}" numactl -C ${k} -l python -u $MODEL_DIR/models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py -m ${MODEL_NAME} -b ${BATCH_SIZE} -i ${IMAGE_FILE} ")
+ ((k=k+1))
+ done
+ done
+ parallel --lb -d, --tagstring "[{#}]" ::: "${str[@]}" 2>&1 | tee $OUTPUT_DIR/${MODEL_NAME}__xpu_inf_c0_c1_${BATCH_SIZE}.log
+ else
+ echo "${MODEL_NAME} FP16 inference with BATCH_SIZE $BATCH_SIZE on Flex 140"
+ for i in $( eval echo {0..$((num_devs-1))} )
+ do
+ str+=("ZE_AFFINITY_MASK="${i}" python $MODEL_DIR/models/image_recognition/tensorflow/efficientnet/inference/gpu/predict.py \
+ -m ${MODEL_NAME} -b ${BATCH_SIZE} \
+ -i ${IMAGE_FILE} ")
+ done
+ parallel --lb -d, --tagstring "[{#}]" ::: "${str[@]}" 2>&1 | tee $OUTPUT_DIR/${MODEL_NAME}__xpu_inf_c0_c1_${BATCH_SIZE}.log
+ fi
+ file_loc=$OUTPUT_DIR/${MODEL_NAME}__xpu_inf_c0_c1_${BATCH_SIZE}.log
+ total_throughput=$( cat $file_loc | grep Throughput | awk '{print $3}' | awk '{ sum_total += $1 } END { print sum_total }' )
+ echo 'Total Throughput in images/sec: '$total_throughput | tee -a $file_loc
+ fi
+ fi
+else
+ echo "Efficient Net currently supports FP16 precision"
+ exit 1
+fi
diff --git a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/setup.sh b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/setup.sh
similarity index 74%
rename from quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/setup.sh
rename to quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/setup.sh
index e72bf8164..ba03441c3 100755
--- a/quickstart/image_recognition/pytorch/resnet50v1_5/inference/gpu/setup.sh
+++ b/quickstart/image_recognition/tensorflow/efficientnet/inference/gpu/setup.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
#
-# Copyright (c) 2022 Intel Corporation
+# Copyright (c) 2023 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,5 +15,7 @@
# limitations under the License.
#
-pip install pillow
-pip install torchvision==0.8.2 --no-deps
+if [[ "$GPU_TYPE" == "flex_140" ]]; then
+ apt-get update && \
+ apt-get install -y --no-install-recommends --fix-missing parallel pciutils numactl
+fi
diff --git a/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md b/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md
index 63e8195cd..669eae345 100644
--- a/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md
+++ b/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/DEVCATALOG_FLEX.md
@@ -9,7 +9,7 @@ This document has instructions for running ResNet50 v1.5 inference using Intel®
| Item | Detail |
| ------ | ------- |
| Host machine | Intel® Data Center GPU Flex Series |
-| Drivers | GPU-compatible drivers need to be installed: [Download Driver 602](https://dgpu-docs.intel.com/installation-guides/ubuntu/ubuntu-jammy-dc.html#step-1-add-package-repository)
+| Drivers | GPU-compatible drivers need to be installed: [Download Driver 647](https://dgpu-docs.intel.com/releases/stable_647_21_20230714.html)
| Software | Docker* Installed |
## Get Started
diff --git a/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/README.md b/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/README.md
deleted file mode 100644
index 047a27f27..000000000
--- a/quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/README.md
+++ /dev/null
@@ -1,105 +0,0 @@
-
-# ResNet50 v1.5 inference
-
-
-## Description
-
-This document has instructions for running ResNet50 v1.5 inference using
-Intel(R) Extension for TensorFlow with Intel(R) Data Center GPU Flex Series.
-
-
-## Hardware Requirements:
-- Intel® Data Center GPU Flex Series
-
-## Software Requirements:
-- Ubuntu 20.04 (64-bit)
-- Intel GPU Drivers: Intel® Data Center GPU Flex Series [419.40](https://dgpu-docs.intel.com/releases/stable_419_40_20220914.html)
-
- |Release|OS|Intel GPU|Install Intel GPU Driver|
- |-|-|-|-|
- |v1.0.0|Ubuntu 20.04|Intel® Data Center GPU Flex Series| Refer to the [Installation Guides](https://dgpu-docs.intel.com/installation-guides/ubuntu/ubuntu-focal-dc.html) for latest driver installation. If install the verified Intel® Data Center GPU Flex Series [419.40](https://dgpu-docs.intel.com/releases/stable_419_40_20220914.html), please append the specific version after components, such as `apt-get install intel-opencl-icd=22.28.23726.1+i419~u20.04`|
-
-- Intel® oneAPI Base Toolkit 2022.3: Need to install components of Intel® oneAPI Base Toolkit
- - Intel® oneAPI DPC++ Compiler
- - Intel® oneAPI Math Kernel Library (oneMKL)
- * Download and install the verified DPC++ compiler and oneMKL in Ubuntu 20.04.
-
- ```bash
- $ wget https://registrationcenter-download.intel.com/akdlm/irc_nas/18852/l_BaseKit_p_2022.3.0.8767_offline.sh
- # 4 components are necessary: DPC++/C++ Compiler, DPC++ Libiary, Threading Building Blocks and oneMKL
- $ sh ./l_BaseKit_p_2022.3.0.8767_offline.sh
- ```
- For any more details, please follow the procedure in https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html.
-
- - Set environment variables
- Default installation location {ONEAPI_ROOT} is /opt/intel/oneapi for root account, ${HOME}/intel/oneapi for other accounts
- ```bash
- source {ONEAPI_ROOT}/setvars.sh
- ```
-
-
-## Datasets
-
-Download and preprocess the ImageNet dataset using the [instructions here](/datasets/imagenet/README.md).
-After running the conversion script you should have a directory with the
-ImageNet dataset in the TF records format.
-
-Set the `DATASET_DIR` to point to the TF records directory when running ResNet50 v1.5.
-
-
-## Quick Start Scripts
-
-| Script name | Description |
-|:-------------:|:-------------:|
-| [`online_inference.sh`](online_inference.sh) | Runs online inference for int8 precision |
-| [`batch_inference.sh`](batch_inference.sh)| Runs batch inference for int8 precision |
-| [`accuracy.sh`](accuracy.sh) | Measures the model accuracy for int8 precision |
-
-
-## Run the model
-Install the following pre-requisites:
-* Python version 3.9
-* Create and activate virtual environment.
- ```bash
- virtualenv -p python
- source /bin/activate
- ```
-* Install TensorFlow and Intel® Extension for TensorFlow (ITEX):
-
- Intel® Extension for TensorFlow requires stock TensorFlow v2.10.0 to be installed.
-
- ```bash
- pip install tensorflow==2.10.0
- pip install --upgrade intel-extension-for-tensorflow[gpu]
- ```
- To verify that TensorFlow and ITEX are correctly installed:
- ```
- python -c "import intel_extension_for_tensorflow as itex; print(itex.__version__)"
- ```
-* Download the frozen graph model file, and set the FROZEN_GRAPH environment variable to point to where it was saved:
- ```bash
- wget https://storage.googleapis.com/intel-optimized-tensorflow/models/gpu/resnet50v1_5_int8_h2d_avg_itex.pb
- ```
-
-See the [datasets section](#datasets) of this document for instructions on
-downloading and preprocessing the ImageNet dataset. The path to the ImageNet
-TF records files will need to be set as the `DATASET_DIR` environment variable
-prior to running a [quickstart script](#quick-start-scripts).
-
-### Run the model on Baremetal
-Navigate to the ResNet50 v1.5 inference directory, and set environment variables:
-```
-export DATASET_DIR=
-export OUTPUT_DIR=
-export PRECISION=int8
-export FROZEN_GRAPH=
-
-Run quickstart script:
-./quickstart/image_recognition/tensorflow/resnet50v1_5/inference/gpu/