網頁

顯示具有 tao 標籤的文章。 顯示所有文章
顯示具有 tao 標籤的文章。 顯示所有文章

2023年6月21日 星期三

如何在 python 中使用 tao 產生的 yolov4 模型

參考 Nvidia TAO Computer Vision Sample Workflows 產生 yolov4-tiny 模型
此 模型 與 一般產生 的 模型 不一樣
一般產生的模型 參考 tensorrt_demos 即可在 python 中使用

只能將 
tao yolo_v4_tiny export 出的模型(.etlt)用於 DeepStream
而由 
tao  converter 產生的 trt.engine 不能使用於 DeepStream 也不能在 python 中使用

有說明如何使用 tao 產生的模型在 Triton 伺服器上
在 yolov3_postprocessor.py 中發現 tao 產生的 yolo
已經將輸出的 NMS 處理過, 並將內容置於 
BatchNMS(-1,1): 偵測出的數量
BatchNMS_1(-1,200,4): 座標
BatchNMS_2(-1,200): 信心
BatchNMS_3(-1,200): 類別
輸入的方式也有改變
cv2 讀出的圖 不需 cvtColor, 也不用除以 255.0
只需將 BHWC 轉成 BCHW
img = img.transpose((2, 0, 1)).astype(np.float32)

tao 的執行是在 docker 中,所以很難除錯
發現下列命令,可以直接進入 docker 中,執行 python, 查詢版本環境等
docker run -it --rm --gpus all \
  -v "/mnt/Data/tao/yolo_v4_tiny_1.4.1":"/workspace/tao-experiments" \
  -v "/mnt/Data/TensorRT/tensorrt_demos":"/workspace/tensorrt_demos" \
  -v "/mnt/CT1000SSD/ImageData/Light":"/workspace/Light" \
  nvcr.io/nvidia/tao/tao-toolkit:4.0.0-tf1.15.5 \
  bash

將模型轉換成 TensorRT 除了使用
!tao converter -k $KEY \
                   -p Input,1x3x416x416,8x3x416x416,16x3x416x416 \
                   -e $USER_EXPERIMENT_DIR/export/trt.engine \
                   -t fp32 \
                   $USER_EXPERIMENT_DIR/export/yolov4_cspdarknet_tiny_epoch_$EPOCH.etlt
外, 也可使用
!tao-deploy yolo_v4_tiny gen_trt_engine \
  -m $USER_EXPERIMENT_DIR/export/yolov4_cspdarknet_tiny_epoch_$EPOCH.etlt \
  -e $SPECS_DIR/yolo_v4_tiny_retrain_kitti.txt \
  -k $KEY \
  --data_type fp32 \
  --batch_size 1 \
  --engine_file $USER_EXPERIMENT_DIR/export/yolov4_tao_deplay.trt
但若是要在不同平台上轉換
參考 TAO Converter 下載安裝,並執行轉換
./tao-converter_v4.0.0_trt8.5.1.7 \
  -k nvidia_tlt \
  -p Input,1x3x416x416,2x3x416x416,4x3x416x416 \
  -e yolo_v4_tiny_1.4.1/yolo_v4_tiny/export/yolov4_tao_converter_fp32.engine \
  -t fp32 \
  yolo_v4_tiny_1.4.1/yolo_v4_tiny/export/yolov4_cspdarknet_tiny_epoch_080.etlt

參考 tensorrt_demos 修改 utils/yolo_with_plugins.py, 改名成 triton_yolo_with_plugins.py 如下
"""yolo_with_plugins.py
Implementation of TrtYOLO class with the yolo_layer plugins.
"""
from __future__ import print_function
import ctypes
import numpy as np
import cv2
import tensorrt as trt
import pycuda.driver as cuda

try:
    ctypes.cdll.LoadLibrary('./plugins/libyolo_layer.so')
except OSError as e:
    raise SystemExit('ERROR: failed to load ./plugins/libyolo_layer.so.  '
                     'Did you forget to do a "make" in the "./plugins/" '
                     'subdirectory?') from e

def _preprocess_yolo(img, input_shape, letter_box=False):
    """Preprocess an image before TRT YOLO inferencing.
    # Args
        img: int8 numpy array of shape (img_h, img_w, 3)
        input_shape: a tuple of (H, W)
        letter_box: boolean, specifies whether to keep aspect ratio and
                    create a "letterboxed" image for inference
    # Returns
        preprocessed img: float32 numpy array of shape (3, H, W)
    """
    if letter_box:
        img_h, img_w, _ = img.shape
        new_h, new_w = input_shape[0], input_shape[1]
        offset_h, offset_w = 0, 0
        if (new_w / img_w) <= (new_h / img_h):
            new_h = int(img_h * new_w / img_w)
            offset_h = (input_shape[0] - new_h) // 2
        else:
            new_w = int(img_w * new_h / img_h)
            offset_w = (input_shape[1] - new_w) // 2
        resized = cv2.resize(img, (new_w, new_h))
        img = np.full((input_shape[0], input_shape[1], 3), 127, dtype=np.uint8)
        img[offset_h:(offset_h + new_h), offset_w:(offset_w + new_w), :] = resized
    else:
        img = cv2.resize(img, (input_shape[1], input_shape[0]))

    #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = img.transpose((2, 0, 1)).astype(np.float32)
    #img /= 255.0
    return img

class HostDeviceMem(object):
    """Simple helper data class that's a little nicer to use than a 2-tuple."""
    def __init__(self, host_mem, device_mem):
        self.host = host_mem
        self.device = device_mem

    def __str__(self):
        return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device)

    def __repr__(self):
        return self.__str__()

def get_input_shape(engine):
    """Get input shape of the TensorRT YOLO engine."""
    binding = engine[0]
    assert engine.binding_is_input(binding)
    binding_dims = engine.get_binding_shape(binding)
    if len(binding_dims) == 4:
        return tuple(binding_dims[2:])
    elif len(binding_dims) == 3:
        return tuple(binding_dims[1:])
    else:
        raise ValueError('bad dims of binding %s: %s' % (binding, str(binding_dims)))

def allocate_buffers(engine, context):
    """Allocates all host/device in/out buffers required for an engine."""
    inputs = []
    outputs = []
    bindings = []
    stream = cuda.Stream()
    for binding in engine:
        binding_dims = engine.get_binding_shape(binding)
        binding_dtype = engine.get_tensor_dtype(binding)
        binding_format = engine.get_tensor_format_desc(binding)
        binding_loc = engine.get_tensor_location(binding)
        binding_mode = engine.get_tensor_mode(binding)
        binding_shape = engine.get_tensor_shape(binding)
        binding_shape_inference = engine.is_shape_inference_io(binding)
        print('binding_dims:{} {} {}'.format(binding, binding_dims, binding_dtype))
        print('  {}'.format(binding_format))
        print('  {} {} {} {}'.format(binding_loc, binding_mode, binding_shape, binding_shape_inference))
        size = trt.volume(binding_dims)
        if size < 0: size *= -1;
        print('  size:{}'.format(size))
        dtype = trt.nptype(engine.get_binding_dtype(binding))
        # Allocate host and device buffers
        host_mem = cuda.pagelocked_empty(size, dtype)
        device_mem = cuda.mem_alloc(host_mem.nbytes)
        # Append the device buffer to device bindings.
        bindings.append(int(device_mem))
        # Append to the appropriate list.
        if engine.binding_is_input(binding):
            #binding_pro_shape = engine.get_profile_shape(0, binding)
            #print('  {}'.format(binding_pro_shape))
            if binding_dims[0] == -1:
                alloc_dims = np.copy(binding_dims)
                alloc_dims[0] = 1
                context.set_binding_shape(0, alloc_dims)
            inputs.append(HostDeviceMem(host_mem, device_mem))
        else:
            outputs.append(HostDeviceMem(host_mem, device_mem))
    return inputs, outputs, bindings, stream

def do_inference(context, bindings, inputs, outputs, stream, batch_size=1):
    """do_inference (for TensorRT 6.x or lower)
    This function is generalized for multiple inputs/outputs.
    Inputs and outputs are expected to be lists of HostDeviceMem objects.
    """
    # Transfer input data to the GPU.
    [cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs]
    # Run inference.
    context.execute_async(batch_size=batch_size,
                          bindings=bindings,
                          stream_handle=stream.handle)
    # Transfer predictions back from the GPU.
    [cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs]
    # Synchronize the stream
    stream.synchronize()
    # Return only the host outputs.
    return [out.host for out in outputs]

def do_inference_v2(context, bindings, inputs, outputs, stream):
    """do_inference_v2 (for TensorRT 7.0+)
    This function is generalized for multiple inputs/outputs for full
    dimension networks.
    Inputs and outputs are expected to be lists of HostDeviceMem objects.
    """
    # Transfer input data to the GPU.
    [cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs]
    # Run inference.
    context.execute_async_v2(bindings=bindings, stream_handle=stream.handle)
    # Transfer predictions back from the GPU.
    [cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs]
    # Synchronize the stream
    stream.synchronize()
    # Return only the host outputs.
    return [out.host for out in outputs]

class TrtYOLO(object):
    """TrtYOLO class encapsulates things needed to run TRT YOLO."""
    def _load_engine(self):
        TRTbin = 'yolo/%s.trt' % self.model
        TRTbin = self.model
        with open(TRTbin, 'rb') as f, trt.Runtime(self.trt_logger) as runtime:
            return runtime.deserialize_cuda_engine(f.read())

    def __init__(self, model, category_num=80, letter_box=False, cuda_ctx=None):
        """Initialize TensorRT plugins, engine and conetxt."""
        self.model = model
        self.category_num = category_num
        self.letter_box = letter_box
        self.cuda_ctx = cuda_ctx
        if self.cuda_ctx:
            self.cuda_ctx.push()

        self.inference_fn = do_inference if trt.__version__[0] < '7' \
                                         else do_inference_v2
        self.trt_logger = trt.Logger(trt.Logger.INFO)
        # add for errors
        # IPluginCreator not found in Plugin Registry
        # getPluginCreator could not find plugin: BatchedNMSDynamic_TRT version: 1
        # Serialization assertion plan->header.magicTag == rt::kPLAN_MAGIC_TAG failed
        trt.init_libnvinfer_plugins(self.trt_logger, namespace="")
        self.engine = self._load_engine()

        self.input_shape = get_input_shape(self.engine)

        try:
            self.context = self.engine.create_execution_context()
            self.inputs, self.outputs, self.bindings, self.stream = \
                allocate_buffers(self.engine, self.context)
        except Exception as e:
            raise RuntimeError('fail to allocate CUDA resources') from e
        finally:
            if self.cuda_ctx:
                self.cuda_ctx.pop()

    def __del__(self):
        """Free CUDA memories."""
        del self.outputs
        del self.inputs
        del self.stream

    def detect(self, img, letter_box=None):
        """Detect objects in the input image."""
        letter_box = self.letter_box if letter_box is None else letter_box
        img_h, img_w, _ = img.shape
        img_resized = _preprocess_yolo(img, self.input_shape, letter_box)
        #print(img_resized.shape, img_resized.dtype)

        # Set host input to the image. The do_inference() function
        # will copy the input to the GPU before executing.
        self.inputs[0].host = np.ascontiguousarray(img_resized)
        if self.cuda_ctx:
            self.cuda_ctx.push()
        trt_outputs = self.inference_fn(
            context=self.context,
            bindings=self.bindings,
            inputs=self.inputs,
            outputs=self.outputs,
            stream=self.stream)
        if self.cuda_ctx:
            self.cuda_ctx.pop()

        y_pred = [i.reshape(1, -1,)[:1] for i in trt_outputs]
        keep_k, boxes, scores, cls_id = y_pred
        #print(keep_k.shape)
        #print(boxes.shape)
        keep_k[0,0] = 1
        locs = np.empty((0,4), dtype=np.uint)
        cids = np.empty((0,1), dtype=np.uint)
        confs = np.empty((0,1), dtype=np.float32)
        for idx, k in enumerate(keep_k.reshape(-1)):
            mul = np.array([img_w,img_h,img_w,img_h])
            loc = boxes[idx].reshape(-1, 4)[:k] * mul
            loc = loc.astype(np.uint)
            cid = cls_id[idx].reshape(-1, 1)[:k]
            cid = cid.astype(np.uint)
            conf = scores[idx].reshape(-1, 1)[:k]
            locs = np.concatenate((locs, loc), axis=0)
            cids = np.concatenate((cids, cid), axis=0)
            confs = np.concatenate((confs, conf), axis=0)
        #print(locs.shape, cids.shape, confs.shape)
        #print(locs, cids, confs)
        return locs, confs, cids

下列程式使用上列的程式
import cv2
import numpy as np
import tensorrt as trt
import pycuda.autoinit # This is needed for initializing CUDA driver
import pycuda.driver as cuda
from utils.triton_yolo_with_plugins import TrtYOLO

#MODEL_PATH = '/workspace/tao-experiments/yolo_v4_tiny/export/yolov4_tao_convert.engine'
MODEL_PATH = '/workspace/tao-experiments/yolo_v4_tiny/export/yolov4_tao_deplay.trt'
#MODEL_PATH = '/workspace/tao-experiments/yolo_v4_tiny/export/trt.engine'
        
def main():
    trt_yolo = TrtYOLO(MODEL_PATH, 5, True)
    img_org = cv2.imread('bb.jpg')
    img = np.copy(img_org)
    print(img.shape, img.dtype)
    boxes, confs, clss = trt_yolo.detect(img, False)
    print(boxes.shape, confs.shape, clss.shape)
    print(boxes, confs, clss)
    for box, conf, clss in zip(boxes, confs, clss):
        x_min, y_min, x_max, y_max = box[0], box[1], box[2], box[3]
        cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (255, 255, 255), 2)
        print(box, conf, clss)
    cv2.imwrite('aa.jpg', img)
    print('aaa')

if __name__ == '__main__':
    main()

除錯說明
訊息: Serialization assertion plan->header.magicTag == rt::kPLAN_MAGIC_TAG failed
解決: TensorRt 的版本不一致,安裝不同版本,或利用 docker
訊息: IPluginCreator not found in Plugin Registry
訊息: getPluginCreator could not find plugin: BatchedNMSDynamic_TRT version: 1
解決: 需安裝 TensorRT OSS
在 load_engine() 之前加上
trt.init_libnvinfer_plugins(self.trt_logger, namespace="")

2023年5月4日 星期四

Nvidia TAO Computer Vision Sample Workflows

參考: Nvidia TAO(Train, Adapt, and Optimize)

user@host:~$ pip3 install --upgrade pip
Traceback (most recent call last):
  File "/home/user/.local/bin/pip3", line 7, in <module>
    from pip._internal.cli.main import main
ModuleNotFoundError: No module named 'pip._internal'

user@host:~$ python3 -m pip --version
pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6)
user@host:~$ python3 -m pip install --upgrade pip
Collecting pip
  Cache entry deserialization failed, entry ignored
  Using cached https://files.pythonhosted.org/packages/a4/6d/6463d49a933f547439d6b5b98b46af8742cc03ae83543e4d7688c2420f8b/pip-21.3.1-py3-none-any.whl
Installing collected packages: pip
Successfully installed pip-21.3.1

user@host:~$ pip3 install virtualenv
user@host:~$ pip3 install virtualenvwrapper
user@host:~$ mkdir .virtualenvs
user@host:~$ vi .bashrc
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source $HOME/.local/bin/virtualenvwrapper.sh
user@host:~$ source .bashrc
user@host:~$ mkvirtualenv tao -p /usr/bin/python3
(tao) user@host:~$ deactivate
user@host:~$ lsvirtualenv
user@host:~$ workon tao
(tao) user@host:~$ pip3 install nvidia-pyindex
(tao) user@host:~$ pip3 install nvidia-tao
(tao) user@host:~$ pip3 install jupyter
(tao) user@host:~$ tao info

到 https://catalog.ngc.nvidia.com/orgs/nvidia/teams/tao/resources/cv_samples 網站
右上角 Download 選 WGET 或 CLI, 會將命令拷貝至剪貼簿,如下命令,並執行
ngc registry resource download-version "nvidia/tao/cv_samples:v1.4.1"
wget --content-disposition https://api.ngc.nvidia.com/v2/resources/nvidia/tao/cv_samples/versions/v1.4.1/zip -O cv_samples_v1.4.1.zip

(tao) user@host:~/Data/tao$ unzip -u cv_samples_v1.4.1.zip -d ./cv_samples_v1.4.1 && rm -rf cv_samples_v1.4.1.zip 
user@host:~/Data/tao$ cp -ar cv_samples_v1.4.1/yolo_v4_tiny/ yolo_v4_tiny_1.4.1
(tao) user@host:~/Data/tao$ cd cv_samples_v1.4.1/
(tao) user@host:~/Data/tao/cv_samples_v1.4.1$ 
(tao) user@host:~/Data/tao/cv_samples_v1.4.1$ jupyter notebook --ip 0.0.0.0 --port 8888 --allow-root
依據命令返回說明,開啟網頁
進入 yolo_v4_tiny, 點選 yolo_v4_tiny.ipynb
修改下列環境變數到你真實的位置
%env LOCAL_PROJECT_DIR=YOUR_LOCAL_PROJECT_DIR_PATH
%env LOCAL_PROJECT_DIR=/home/user/Data/tao/yolo_v4_tiny_1.4.1
檢查工具版本
(tao) user@host:~/Data/tao/yolo_v4_tiny_1.4.1$ python3 --version
(tao) user@host:~/Data/tao/yolo_v4_tiny_1.4.1$ docker version
(tao) user@host:~/Data/tao/yolo_v4_tiny_1.4.1$ apt list -a nvidia-container-toolkit
(tao) user@host:~/Data/tao/yolo_v4_tiny_1.4.1$ apt list -a nvidia-docker2
(tao) user@host:~/Data/tao/yolo_v4_tiny_1.4.1$ nvidia-smi
(tao) user@host:~/Data/tao/yolo_v4_tiny_1.4.1$ docker login nvcr.io

到 https://catalog.ngc.nvidia.com/ 搜尋 object
可找到 TAO Pretrained Object Detection
進入,點選右上 Download, 選 CLI,將命令拷貝
可由命令查到真實位置
ngc registry model download-version "nvidia/tao/pretrained_object_detection:cspdarknet_tiny"

參考 https://catalog.ngc.nvidia.com/orgs/nvidia/containers/deepstream
user@host:~/Data/V2Pdetect$ docker run --gpus all -it --rm --net=host --privileged -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -w /opt/nvidia/deepstream/deepstream-6.2 nvcr.io/nvidia/deepstream:6.2-devel

查詢已安裝套件的版本
參考 https://docs.nvidia.com/metropolis/deepstream/dev-guide/text/DS_Quickstart.html?highlight=compatibility#platform-and-os-compatibility
其中 nvidia driver 的版本, docker 是使用 host 的 driver
root@host:/opt/nvidia/deepstream/deepstream-6.2# pip list
root@host:/opt/nvidia/deepstream/deepstream-6.2# dpkg -l|grep nvinfer
root@host:/opt/nvidia/deepstream/deepstream-6.2# dpkg -l|grep cudnn
root@host:/opt/nvidia/deepstream/deepstream-6.2# dpkg -l|grep cudnn
root@host:/opt/nvidia/deepstream/deepstream-6.2# cat /etc/os-release 
root@host:/opt/nvidia/deepstream/deepstream-6.2# update-alternatives --display cuda
root@host:/opt/nvidia/deepstream/deepstream-6.2# nvidia-smi

root@host:/opt/nvidia/deepstream/deepstream-6.2# ./install.sh 
root@host:/opt/nvidia/deepstream/deepstream-6.2# ./user_additional_install.sh 

user@host:~/Data/DeepStream/deepstream_tao_apps$ git clone https://github.com/NVIDIA-AI-IOT/deepstream_tao_apps.git
user@host:~/Data/DeepStream/deepstream_tao_apps$ cd deepstream_tao_apps
user@host:~/Data/DeepStream/deepstream_tao_apps/deepstream_tao_apps$ git show-ref
user@host:~/Data/DeepStream/deepstream_tao_apps/deepstream_tao_apps$ cd ..
user@host:~/Data/DeepStream/deepstream_tao_apps$ mv deepstream_tao_apps deepstream_tao_apps-tao4.0_ds6.2ga
user@host:~/Data/DeepStream/deepstream_tao_apps$ cd deepstream_tao_apps-tao4.0_ds6.2ga/

user@host:~/Data/V2Pdetect$ docker run --gpus all -it --rm --net=host --privileged \
  -v /tmp/.X11-unix:/tmp/.X11-unix \
  -v /etc/localtime:/etc/localtime \
  -v /home/user/Data/DeepStream/deepstream_tap_apps/deepstream_tao_apps-tao4.0_ds6.2ga/:/home/deepstream_tao_apps \
  -v /home/user/Data/V2Pdetect/multi_rtsp:/home/multi_rtsp \
  -e DISPLAY=$DISPLAY \
  -w /opt/nvidia/deepstream/deepstream-6.2 \
  nvcr.io/nvidia/deepstream:6.2-devel

root@host:/opt/nvidia/deepstream/deepstream-6.2# cd /home/deepstream_tao_apps/
root@host:/home/deepstream_tao_apps# ./download_models.sh 
root@host:/home/deepstream_tao_apps# ls models/yolov4-tiny/
root@host:/home/deepstream_tao_apps# cd post_processor/
root@host:/home/deepstream_tao_apps/post_processor# make
Makefile:25: *** "CUDA_VER is not set".  Stop.
root@host:/home/deepstream_tao_apps/post_processor# dpkg -l | grep CUDA
root@host:/home/deepstream_tao_apps/post_processor# export CUDA_VER=11.8
root@host:/home/deepstream_tao_apps/post_processor# cd ../apps/tao_detection/
root@host:/home/deepstream_tao_apps/apps/tao_detection# make
自己準備個 sample_720p.h264,以便測試
root@host:/home/deepstream_tao_apps/apps/tao_detection# ./ds-tao-detection -c ../../configs/yolov4-tiny_tao/pgie_yolov4_tiny_tao_config.txt -i file:///home/deepstream_tao_apps/sample/streams/sample_720p.h264 -d
root@host:/home/deepstream_tao_apps/apps/tao_detection# ./ds-tao-detection -c ../../configs/yolov4-tiny_tao/pgie_yolov4_tiny_tao_config.txt -i rtsp://root:passwd@192.168.0.107:554/live1s1.sdp -d

將 tao 產生的 labels.txt, yolov4_cspdarknet_tiny_epoch_080.etlt 拷貝到 deepstream_tao_apps 下
並合併 nvinfer_config.txt 和 pgie_yolov4_tiny_tao_config.txt 
root@host:/home/deepstream_tao_apps/apps/tao_detection# ./ds-tao-detection -c ../../configs/yolov4-tiny_tao/pgie_light.txt -i file:///home/deepstream_tao_apps/sample/streams/sample_720p.h264 -d

root@host:/home/multi_rtsp# apt-get update
root@host:/home/multi_rtsp# apt-get install libopencv-dev
root@host:/home/multi_rtsp# apt-get install libclutter-gst-3.0-dev

2022年6月1日 星期三

Integrate TAO model with DeepStream SDK In Docker

參考 DeepStream Platform and OS Compatibility
參考 TensorRT Open Source Software
參考 Ubuntu 安裝 DeepStream 使用 Docker 部分

在 DeepStream Platform and OS Compatibility 文件中
DS 6.0.1
CUDA 11.4.1
cuDNN 8.2+
TRT 8.0.1
Driver R470.63.01

在 nvcr.io/nvidia/deepstream:6.0.1-devel Docker 中
Deepstream 6.0.1
TensorRT 8.0.1-1 + cuda11.3

替換 nvidia driver,不然會產生錯誤
Failed to establish dbus connection
$ apt list --installed|grep nvidia
$ sudo ubuntu-drivers devices
$ sudo apt-get remove --purge nvidia-driver-495
$ sudo apt-get install nvidia-driver-470
$ sudo reboot

確認 CUDA, TensorRT 安裝的版本
$ dpkg -l | grep -i cuda-cuda
$ dpkg -L cuda-cudart-11-5
$ dpkg -l | grep TensorRT

準備 DeepStream 開發用 Docker
$ docker pull nvcr.io/nvidia/deepstream:6.0.1-devel
$ xhost +
access control disabled, clients can connect from any host
$ sudo docker run --gpus ""device=0"" -it --rm --net=host -v /tmp/.X11-unix:/tmp/.X11-unix -v /etc/localtime:/etc/localtime -e DISPLAY=$DISPLAY -w /opt/nvidia/deepstream/deepstream-6.0 nvcr.io/nvidia/deepstream:6.0.1-devel
# cd samples/configs/deepstream-app
# deepstream-app -c source4_1080p_dec_infer-resnet_tracker_sgie_tiled_display_int8.txt 
# cd /opt/nvidia/deepstream/deepstream-6.0/sources/apps/sample_apps
/deepstream-app
# export CUDA_VER=11.4
# make
# exit

準備 TensorRT OSS 編譯環境 Docker
$ git clone -b master https://github.com/nvidia/TensorRT TensorRT_OSS-8.0.1
$ cd TensorRT_OSS-8.0.1
$ git tag -n
$ git checkout 8.0.1
$ git describe --tags
8.0.1
$ git submodule update --init --recursive
$ cat docker/ubuntu-18.04.Dockerfile | grep CUDA_VERSION
ARG CUDA_VERSION=11.3.1
$ ./docker/build.sh --file docker/ubuntu-18.04.Dockerfile --tag tensorrt-ubuntu18.04-cuda11.3.1 --cuda 11.3.1
$ ./docker/launch.sh --tag tensorrt-ubuntu18.04-cuda11.3.1 --gpus all
$ cd TensorRT
$ mkdir -p build && cd build
$ cmake .. -DTRT_LIB_DIR=$TRT_LIBPATH -DTRT_OUT_DIR=`pwd`/out
$ make -j$(nproc)
$ exit

下載主要程式,須注意版本
$ git clone https://github.com/NVIDIA-AI-IOT/deepstream_tao_apps.git
$ sudo apt install gitk
$ git branch -r
$ git checkout release/tao3.0_ds6.0.1
$ git log -1
$ sudo docker run --gpus all -it --rm --net=host \
 -v /etc/localtime:/etc/localtime \
 -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY \
 -v /your_path_to/Data/TensorRT/TensorRT_OSS-8.0.1:/home/TensorRT \
 -v /your_path_to/Data/DeepStream/deepstream_tao_apps:/home/deepstream_tao_apps \
 -w /opt/nvidia/deepstream/deepstream-6.0 nvcr.io/nvidia/deepstream:6.0.1-devel
# cd /home/deepstream_tao_apps/
# ./download_models.sh 
# export CUDA_VER=11.4
# make
# cp /home/TensorRT/build/out/libnvinfer_plugin.so.8.0.1 /usr/lib/x86_64-linux-gnu/
# ./apps/tao_detection/ds-tao-detection -c configs/frcnn_tao/pgie_frcnn_tao_config.txt -i /opt/nvidia/deepstream/deepstream-6.0/samples/streams/sample_720p.h264 -d

# cd /opt/nvidia/deepstream/deepstream-6.0/sources/gst-plugins/gst-nvdsvideotemplate/
# make
# cp libnvdsgst_videotemplate.so /opt/nvidia/deepstream/deepstream-6.0/lib/gst-plugins/
# rm -rf ~/.cache/gstreamer-1.0/

# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/nvidia/deepstream/deepstream/lib/cvcore_libs
# cd /home/deepstream_tao_apps/apps/tao_others/deepstream-gaze-app
# ./deepstream-gaze-app 3 ../../../configs/facial_tao/sample_faciallandmarks_config.txt $URI ./gazenet

# cd ../deepstream-gesture-app
# ./deepstream-gesture-app 3 3 ../../../configs/bodypose2d_tao/sample_bodypose2d_model_config.txt $URI ./gesture

# cd ../deepstream-bodypose2d-app/
# ./deepstream-bodypose2d-app 3 ../../../configs/bodypose2d_tao/sample_bodypose2d_model_config.txt $URI ./body2dout

# cd ../deepstream-faciallandmark-app/
# ./deepstream-faciallandmark-app 3 ../../../configs/facial_tao/sample_faciallandmarks_config.txt $URI ./landmarks

# cd ../deepstream-emotion-app/
# ./deepstream-emotion-app 3 ../../../configs/facial_tao/sample_faciallandmarks_config.txt $URI ./landmarks

在 Jeston 上測試
$ docker pull nvcr.io/nvidia/l4t-base:r32.4.3
$ xhost +
$ sudo docker run -it --rm --net=host --runtime nvidia  -e DISPLAY=$DISPLAY -v /tmp/.X11-unix/:/tmp/.X11-unix nvcr.io/nvidia/l4t-base:r32.4.3

# export URI=rtsp://user:passwd@192.168.0.108:554/live1s2.sdp
# gst-launch-1.0 uridecodebin uri=$URI name=d d. ! nvvidconv ! nvegltransform ! nveglglessink
# gst-launch-1.0 uridecodebin uri=$URI name=d d. ! nvvidconv ! nvoverlaysink

2022年5月24日 星期二

TAO Toolkit Triton Apps 測試紀錄

參考 TAO Toolkit Triton Apps

$ pip3 install virtualenv virtualenvwrapper
$ mkdir $HOME/.virtualenvs
$ vi ~/.bashrc
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /home/user/.local/bin/virtualenvwrapper.sh
$ source ~/.bashrc

$ mkvirtualenv tao -p /usr/bin/python3
$ deactivate
$ workon tao

$ git clone https://github.com/NVIDIA-AI-IOT/tao-toolkit-triton-apps.git
$ cd tao-toolkit-triton-apps/tao_triton
$ pip3 install -r requirements-pip.txt 
$ pip3 install nvidia-pyindex
$ pip3 install tritonclient[all]
$ add2virtualenv=`pwd`
$ cd ..
$ bash scripts/start_server.sh 若產生下列錯誤
...
Get:1 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64  InRelease [1581 B]
Err:1 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64  InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY A4B469963BF863CC
Get:2 http://archive.ubuntu.com/ubuntu focal InRelease [265 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]
...

$ vi docker/Dockerfile
在
# Download and install TAO Toolkit converter
前,加上
RUN apt-key del 7fa2af80
RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/3bf863cc.pub
RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu2004/x86_64/7fa2af80.pub

$ bash scripts/start_server.sh 


new session, 準備圖檔於 images 目錄
$ mkdir images images_out
$ cd images
$ wget https://github.com/openalpr/benchmarks/raw/master/seg_and_ocr/usimages/ca286.png
$ mv ca286.png 5VCF203.png
$ wget https://developer.nvidia.com/sites/default/files/akamai/NGC_Images/models/peoplenet/input_11ft45deg_000070.jpg
$ mv input_11ft45deg_000070.jpg peopleseg.jpg
$ cd ../tao-toolkit-triton-apps
$ export PYTHONPATH=`pwd`:$PYTHONPATH
$ pip install scikit-image
$ python tao_triton/python/entrypoints/tao_client.py ../images -m peoplenet_tao -x 1 -b 8 --mode DetectNet_v2 -i https -u localhost:8000 --async --output_path ../images_out --postprocessing_config tao_triton/python/clustering_specs/clustering_config_peoplenet.prototxt 
$ python tao_triton/python/entrypoints/tao_client.py ../images -m dashcamnet_tao -x 1 -b 8 --mode DetectNet_v2 -i https -u localhost:8000 --async --output_path ../images_out --postprocessing_config tao_triton/python/clustering_specs/clustering_config_dashcamnet.prototxt --class_list car,bicycle,person,road_sign
$ python tao_triton/python/entrypoints/tao_client.py ../images -m vehicletypenet_tao -x 1 -b 1 --mode Classification -i https -u localhost:8000 --async --output_path ../images_out
$ python tao_triton/python/entrypoints/tao_client.py ../images -m lprnet_tao -x 1 -b 1 --mode LPRNet -i https -u localhost:8000 --async --output_path ../images_out
$ python tao_triton/python/entrypoints/tao_client.py ../images -m yolov3_tao -x 1 -b 1 --mode YOLOv3 -i https -u localhost:8000 --async --output_path ../images_out
$ python tao_triton/python/entrypoints/tao_client.py ../images -m peoplesegnet_tao -x 1 -b 1 --mode Peoplesegnet -i https -u localhost:8000 --async --output_path ../images_out

2022年5月20日 星期五

Triton example MNIST


準備模型
$ mkdir mnist_infer & cd mnist_infer
$ vi train.py
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds

def normalize_img(image, label):
    """Normalizes images: `uint8` -> `float32`."""
    return tf.cast(image, tf.float32) / 255., label

(ds_train, ds_test), ds_info = tfds.load(
    'mnist',
    split=['train', 'test'],
    shuffle_files=True,
    as_supervised=True,
    with_info=True,
    try_gcs=True
)

ds_train = ds_train.map(normalize_img, 
        num_parallel_calls=tf.data.experimental.AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)
ds_train = ds_train.batch(128)
ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)

ds_test = ds_test.map(normalize_img, 
        num_parallel_calls=tf.data.experimental.AUTOTUNE)

ds_test = ds_test.batch(128)
ds_test = ds_test.cache()
ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28, 1)),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10)
])
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.001),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)
model.summary()
model.fit(ds_train, epochs=10, validation_data=ds_test)
score = model.evaluate(ds_test, verbose=0)
for name, score in zip(model.metrics_names, score):
    print("%s: %.2f" % (name, score))
model.save('model.savedmodel')

$ cd server.22.04/docs/examples/model_repository
$ mkdir -p mnist/1
$ cp -r your_path_to/mnist_infer/model.savedmodel mnist/1/
$ vi config.pbtxt
name: "mnist"
platform: "tensorflow_savedmodel"
max_batch_size: 32
input [
    {
        name: "flatten_input"
        data_type: TYPE_FP32
        format: FORMAT_NHWC
        dims: [28, 28, 1]
    }
]
output [
    {
        name: "dense_1"
        data_type: TYPE_FP32
        dims: [10]
    }
]
instance_group [
    {
        kind: KIND_GPU
        count: 2
    }
]

optimization { execution_accelerators {
    gpu_execution_accelerator : [ {
        name : "tensorrt"
        parameters { key: "precision_mode" value: "FP16" }}]
}}

version_policy { latest { num_versions: 1 } }

dynamic_batching {
  preferred_batch_size: [ 4, 8 ]
  max_queue_delay_microseconds: 100
}

運行 Triton Inference Server
$ docker run --gpus=1 --rm -p8000:8000 -p8001:8001 -p8002:8002 -v/home/mark/Data/DeepStream/tao/triton-inference-server/server.22.04/docs/examples/model_repository:/models nvcr.io/nvidia/tritonserver:22.04-py3 tritonserver --model-repository=/models

測試使用程式,準備灰階數字圖片 input.jpg
$ cd mnist_infer
$ vi client.py
from PIL import Image
import numpy as np
import tritonclient.grpc as grpcclient
from tritonclient.utils import triton_to_np_dtype

## 前處理
img = Image.open('input.jpg').convert('L')
img = img.resize((28, 28))
imgArr = np.asarray(img)/255
imgArr = np.expand_dims(imgArr[:, :, np.newaxis], 0)
imgArr = imgArr.astype(triton_to_np_dtype('FP32'))

## Client-Server 溝通
triton_client = grpcclient.InferenceServerClient(url='localhost:8001', verbose=0)
inputs = []
inputs.append(grpcclient.InferInput('flatten_input', imgArr.shape, 'FP32'))
inputs[0].set_data_from_numpy(imgArr)
outputs = []
outputs.append(grpcclient.InferRequestedOutput('dense_1',class_count=0))
responses = []
responses.append(triton_client.infer('mnist',inputs,
        request_id=str(1),
        model_version='1',
        outputs=outputs))

## 後處理
print (np.argmax(responses[0].as_numpy('dense_1')[0]))

$ docker run -it --rm --net=host --name Triton_mnist \
 -v/your_path_to/mnist_infer:/data -w'/data' \
 nvcr.io/nvidia/tritonserver:22.04-py3-sdk bash \
 -c 'python /data/client.py'

測試使用網頁,準備資料 input.json
$ sudo apt-get install jq
$ curl http://localhost:8000/v2/models/mnist | jq .

$ vi mnist_image.py
import numpy as np
from tensorflow.keras.datasets import mnist

(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train / 255.

idx = 1
X = X_train[idx].reshape(784)
values = np.expand_dims(X, axis=0).reshape((1,28,28,1)).flatten().tolist()
print(y_train[idx])
#print(values)
cmd = '{"inputs":[{"name":"flatten_input","data":'+str(values)+',"datatype":"FP32","shape":[1,28,28,1]}]}'
with open("input.json","w") as f:
    f.write(cmd)
    
$ python mnist_image.py
$ curl -s -d @./input.json -X POST http://localhost:8000/v2/models/mnist/infer -H "Content-Type: application/json" | jq .

2022年5月19日 星期四

Triton 安裝



$ docker pull nvcr.io/nvidia/tritonserver:22.04-py3

$ git clone https://github.com/triton-inference-server/server.git server.22.04
$ cd server.22.04/docs/examples/
$ ./fetch_models.sh
開啟 Triton Server
$ docker run --gpus=1 --rm -p8000:8000 -p8001:8001 -p8002:8002 \
 -v/your_path_to/server.22.04/docs/examples/model_repository:/models \
 nvcr.io/nvidia/tritonserver:22.04-py3 tritonserver \
 --model-repository=/models

測試 Triton Server
$ curl -v localhost:8000/v2/health/ready
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8000 (#0)
> GET /v2/health/ready HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Length: 0
< Content-Type: text/plain
< 
* Connection #0 to host localhost left intact

使用 Triton Client
可以參考 Github: Triton Client Libraries and Examples 直接使用 Docker
$ docker pull nvcr.io/nvidia/tritonserver:22.04-py3-sdk
$ docker run -it --rm --net=host nvcr.io/nvidia/tritonserver:22.04-py3-sdk
/workspace# /workspace/install/bin/image_client -m densenet_onnx -c 3 -s INCEPTION /workspace/images/mug.jpg
Request 0, batch size 1
Image '/workspace/images/mug.jpg':
    15.349570 (504) = COFFEE MUG
    13.227468 (968) = CUP
    10.424897 (505) = COFFEEPOT
/workspace# exit

2022年5月13日 星期五

Gazenet 視線追蹤

參考 Nvidia TAO(Train, Adapt, and Optimize) 安裝一些環境
開啟 http://0.0.0.0:8888/notebooks/gazenet/gazenet.ipynb
並參考說明文件 Gaze Estimation

修改
%env LOCAL_PROJECT_DIR=FIXME
%env SAMPLES_DIR=FIXME
為
os.environ["LOCAL_PROJECT_DIR"]="/your_host_path_to/cv_samples_vv1.3.0"
os.environ["SAMPLES_DIR"]="/your_host_path_to/cv_samples_vv1.3.0"

放到 /your_host_path_to/cv_samples_vv1.3.0/gazenet/data
$ unzip MPIIFaceGaze.zip
$ cp ../sample_labels/data_factory.zip MPIIFaceGaze
$ cd MPIIFaceGaze/
$ unzip data_factory.zip
$  cd ../../specs
$ vi gazenet_tlt_pretrain.yaml
修改 num_epoch

但結果不如預期

2022年5月11日 星期三

Nvidia TAO(Train, Adapt, and Optimize)

Nvidia TLT(Transfer Learning Toolkit) 改版變成 Nvidia TAO(Train, Adapt, and Optimize)


$ curl https://get.docker.com | sh \
  && sudo systemctl --now enable docker
$ sudo groupadd docker
$ sudo usermod -aG docker $USER
$ docker run hellow-world

$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \
      && curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \
      && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | \
            sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
            sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
$ sudo apt-get update
$ sudo apt-get install -y nvidia-docker2
$ sudo systemctl restart docker
$  sudo docker run --rm --gpus all nvidia/cuda:11.0.3-base-ubuntu20.04 nvidia-smi

$ wget -O ngccli_linux.zip https://ngc.nvidia.com/downloads/ngccli_linux.zip && unzip -o ngccli_linux.zip && chmod u+x ngc
$ md5sum -c ngc.md5
$ echo "export PATH=\"\$PATH:$(pwd)\"" >> ~/.bash_profile && source ~/.bash_profile
$ ngc config set
$ docker login nvcr.io
Username: $oauthtoken
Password: YOUR_NGC_API_KEY
$ ngc registry model list
$ ngc registry image list

$ pip3 install virtualenv virtualenvwrapper
$ mkdir $HOME/.virtualenvs
$ vi ~/.bashrc
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /home/mark/.local/bin/virtualenvwrapper.sh
$ source ~/.bashrc

$ mkvirtualenv tao -p /usr/bin/python3
$ deactivate
$ workon tao

$ pip3 install nvidia-pyindex
$ pip3 install nvidia-tao
$ pip3 install jupyter
$ tao info

$ cd Data/tao/
# 下載 使用 WGET
$ wget --content-disposition https://api.ngc.nvidia.com/v2/resources/nvidia/tao/cv_samples/versions/v1.3.0/zip -O cv_samples_v1.3.0.zip
$ unzip -u cv_samples_v1.3.0.zip  -d ./cv_samples_v1.3.0 && rm -rf cv_samples_v1.3.0.zip && cd ./cv_samples_v1.3.0
# 下載 使用 CLI
$ ngc registry resource download-version "nvidia/tao/cv_samples:v1.3.0"
$ cd ./cv_samples_v1.3.0
# 啟動 jupyter
$ jupyter notebook --ip 0.0.0.0 --port 8888 --allow-root
# 開啟網頁 http://0.0.0.0:8888/tree

以 http://0.0.0.0:8888/notebooks/detectnet_v2/detectnet_v2.ipynb 為例
並參考 TAO 命令及參數文件 Object Detection/DetectNet_v2
修改
os.environ["LOCAL_PROJECT_DIR"] = FIXME
os.environ["LOCAL_PROJECT_DIR"] = "your_host_path_to/cv_samples_vv1.3.0"

會自動產生 ~/.tao_mounts.json

安裝 TAO launcher
!pip3 install nvidia-pyindex
!pip3 install nvidia-tao

下載 kitti object detection 資料集
到 http://www.cvlibs.net/datasets/kitti/eval_object.php?obj_benchmark=2d 網站
申請帳號,並下載
Download left color images of object data set (12 GB) 左眼看到的景
Download training labels of object data set (5 MB)

產生 Tfrecords
下載並安裝 NGC CLI
使用 ngc 下載 pretrained_detectnet_v2:resnet18
train evaluate prune (re)train evaluate inference 
export 產生 resnet18_detector.etlt

Int8 Optimization (效果不好,請改用 QAT)
 calibration_tensorfile 產生 calibration.tensor
 export 產生 calibration.bin resnet18_detector.etlt resnet18_detector.trt.int8(可用於 inference)
 converter 產生 resnet18_detector.trt(可用於 inference)
 inference (效果不好,請改用 QAT)

QAT 需要重新 train
  train evaluate export evaluate inference
 
列出 tao task
$ tao list
刪除 tao task
$ tao stop --container_id 40e28a67c2

inference config file
inferencer_config {
  tensorrt_config {
    etlt_model: "/workspace/tao-experiments/detectnet_v2/experiment_dir_final/resnet18_detector.etlt"
    save_engine: true
    trt_engine: "/workspace/tao-experiments/detectnet_v2/experiment_dir_final/resnet18_detector.trt"
    calibrator_config {
      calibration_cache: "/workspace/tao-experiments/detectnet_v2/experiment_dir_final/calibration.bin"
    }
  }
}
若是 trt_engine 檔案尚未產生,會由 etlt_model 產生 trt_engine
若是已經有 trt_engine,直接使用