Мини-пк intel® neural compute stick 2

Содержание

Аппаратное обеспечение Intel для машинного обучения

У Intel есть продукты общего назначения – центральные процессоры, которые могут использоваться как для обучения, так и для использования нейронной сети. Для обучения модели предпочтительны серверные микропроцессоры Intel Xeon (https://www.intel.ru/content/www/ru/ru/products/processors/xeon/view-all.html) (в первую очередь это связано со скоростью работы), довольно частая практика – это использование облачных вычислений для тренировки модели, в этом случае, сервера, на которых это облако работает, могут функционировать под управлением Intel Xeon. Для того, чтобы использовать полученную модель подойдут процессоры Intel Xeon, Core, Atom, требования к вычислительным мощностям при работе с готовой моделью ниже, чем к процессу ее обучения, поэтому тут можно обойтись менее производительными устройствами.

Также есть специализированные решения, которые изначально проектировались для работы в рамках направления Deep Learning.  В первую очередь хотелось бы сказать про процессор (если его вообще так можно назвать) Intel Nervana, он в первую очередь ориентирован на тренировку нейронных сетей.

Для запуска натренированной сети предоставляется целый набор различных устройств. Это Intel FPGA  – программируемые логические схемы. После покупки Intel фирмы Altera чипы Stratix, Arria, MAX теперь выпускаются под брендом Intel.

Для этих целей также может использоваться Intel Iris Graphics – интегрированное в микропроцессор графические ядро. Есть специализированные устройства для распознавания речи (Intel GNA (IP)).  Более подробно про аппаратные и программные средства Intel для работы в области искусственного интеллекта можете прочитать здесь. Для нас наибольший интерес представляют чипы Movidius Myriad, в частности Myriad 2, на котором построен Movidius NCS, обзору которого будет посвящен данный цикл статей.

Dependencies

After updating the git submodules, all the source code for the build is on the system, however there are a number of other build dependencies that need to be available during the build. There is a script to install these build dependencies in the inference-engine directory named install_dependencies.sh. This script is validated for Ubuntu* and CentOS* so it may need to be modified depending on the platform.  

If the script doesn’t work straightaway on your system there may be some trial work required to get the necessary components Below are the packages (Ubuntu package names) that are installed by the install_dependencies.sh script as of this writing. To avoid typing the apt-get command for each package it’s possible to cut and paste relevant lines from the install_dependencies.sh script. If apt is not available or packages are not available, some research may be required to determine how to get the equivalent components installed on your system. If apt is supported then you can likely install them via:

 Where <package name> is each of the following apt packages:

build-essential cmake curl wget libssl-dev ca-certificates
git libboost-regex-dev gcc-multilib* g++-multilib* libgtk2.0-dev pkg-config
unzip automake libtool autoconf libcairo2-dev libpango1.0-dev
libglib2.0-dev libswscale-dev libavcodec-dev libavformat-dev libgstreamer1.0-0 gstreamer1.0-plugins-base
libusb-1.0-0-dev libopenblas-dev libpng12-dev**      

* Not required when building on Raspberry Pi* 3

** libpng12-dev renamed to libpng-dev in Ubuntu 18

If one or more of the packages above can’t be found or fails to install its worthwhile to attempt to build before going through the trouble of tracking down a replacement. Not all packages will be required for all build scenarios.

Building

After all the build tools and dependencies are installed, the inference engine and Intel Movidius Myriad VPU plugin can be built by executing the following commands which will use cmake to create Makefiles and then build via make and with those Makefiles.

Running Your first Machine Learning Model

Unlike the newer Edge TPU based Coral hardware from Google, or NVIDIA’s new Jetson Nano, the out-of-the-box experience with the Neural Compute Stick is built around C++ rather than Python. However we’re lacking some of the tools we need to do that, so first of all we need to install .

$ sudo apt-get install cmake

Then we can go ahead and build one of the pre-trained Face Detection demos.

$ cd inference_engine_vpu_arm/deployment_tools/inference_engine/samples$ mkdir build$ cd build$ cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-march=armv7-a"$ make -j2 object_detection_sample_ssd   .   .   . Linking CXX executable ../armv7l/Release/object_detection_sample_ssd Built target object_detection_sample_ssd$

Unlike the Intel distribution, the Raspberry Pi version of the toolkit is lacking the model and associated XML file with the model topology. So before we can run the model we also need to download both of those files.

$ wget --no-check-certificate https://download.01.org/openvinotoolkit/2018_R5/open_model_zoo/face-detection-adas-0001/FP16/face-detection-adas-0001.bin$ wget --no-check-certificate https://download.01.org/openvinotoolkit/2018_R5/open_model_zoo/face-detection-adas-0001/FP16/face-detection-adas-0001.xml

We’ll also need an image to run the face detection demo on, I grabbed an image I had lying around of me taken at CES earlier in the year and copied it in my home directory on the Raspberry Pi using from my laptop.

Now we can run our demo,

$ ./armv7l/Release/object_detection_sample_ssd -m face-detection-adas-0001.xml -d MYRIAD -i ~/me.jpg InferenceEngine:API version ............ 1.4Build .................. 19154Parsing input parameters Files were added: 1     /home/pi/me.jpg Loading pluginAPI version ............ 1.5Build .................. 19154Description ....... myriadPlugin Loading network files:face-detection-adas-0001.xmlface-detection-adas-0001.bin Preparing input blobs Batch size is 1 Preparing output blobs Loading model to the plugin Image is resized from (960, 960) to (672, 384) Batch size is 1 Start inference (1 iterations) Processing output blobs element, prob = 1    (410.391,63.5742)-(525.469,225.703) batch id : 0 WILL BE PRINTED!   .   .   . Image out_0.bmp created!total inference time: 155.233Average running time of one iteration: 155.233 msThroughput: 6.44194 FPS Execution successful$

Setting Up Your Build Environment

Note: This guide assumes you are using the root user and does not include sudo in its commands. If you have created another user and are logged in as that, run these commands as root to install correctly.

Make sure your device software is up to date:

Some of the toolkit’s dependencies do not have prebuilt ARMv7 binaries and need to be built from source – this can increase the build time significantly compared to other platforms. Preparing to build the toolkit requires the following steps:

  • Installing build tools
  • Installing CMake* from source
  • Installing OpenCV from source
  • Cloning the toolkit

These are outlined below, step by step.

Installing Build Tools  

Install build-essential:

This will install and setup the GNU C and GNU CPlusPlus compilers. If everything completes successfully, move on to install CMake* from source.

Install CMake* from Source

To begin, fetch CMake from the Kitware* GitHub* release page, extract it, and enter the extracted folder:

Run the bootstrap script to install additional dependencies begin the build:

Note: The install step is optional, but recommended. Without it, CMake will run from the build directory.

Note: The number of jobs the make command uses can be adjusted with the –j flag – it is recommended to set the number of jobs at the number of cores on your platform.
You can check the number of cores on your system by using the command  grep –c ^processor /proc/cpuinfo . Be aware that setting the number too high can lead to memory overruns, failing the build. If time permits, it is recommended to run 1 to 2 jobs.

CMake is now fully installed.

Install OpenCV from Source

OpenCV requires some additional dependencies. Install the following from your package
manager (in this case, apt):

  • git
  • libgtk2.0-dev
  • pkg-config
  • libavcodec-dev
  • libavformat-dev
  • libswscale-dev

Clone the repository from OpenCV GitHub* page, prepare the build environment, and build:

OpenCV is now fully installed.

Download Source Code and Install Dependencies

The open-source version of Intel OpenVINO toolkit is available through GitHub. The repository folder is titled  dldt , for Deep Learning Development Toolkit.

The repository also has submodules that must be fetched:

Intel OpenVINO toolkit has a number of build dependencies. The install_dependencies.sh script fetches these for you. There must be some changes made to the script to run properly on ARM* platforms. If any issues arise when trying to run the script, then you must install each dependency individually.

Note: For images that ship with a non-Bash POSIX-Compliant shell this script (as of 2019 R1.1) includes the use of the function keyword and a set of double brackets which do not work for non-Bash shells.

Using your favorite text editor, make the following  changes.Original Line 8 : 

Line 8 Edit:

Original Line 23:

Line 23 Edit:

The script also tries to install two packages that are not needed for ARM: gcc-multilib and gPlusPlus-multilib. They should be removed from the script, or all other packages will need to be installed independently.

Run the script to install:

If the script finished successfully, you are ready to build the toolkit. If something has failed at this point, make sure that you install any listed dependencies and try again.

Powering Your Raspberry Pi

The more modern Raspberry Pi boards, and especially the latest model the Raspberry Pi 3, Model B+, needs a USB power supply that will provide +5V consistently at 2 to 2.5A. Depending on what peripherals the board needs to support that can be a problem.

Typically the Raspberry Pi uses between 500 and 1,000mA depending on the current state of the board. However attaching a monitor to the HDMI port uses 50mA, adding a camera module requires 250mA, and keyboards and mice can take as little as 100mA or well over 1,000mA depending on the model. With the Neural Compute Stick itself requiring at least 500mA.

However I’ve found that most USB chargers will tend to under supply the Raspberry Pi, and as a result the board will register a low power condition and start to throttle the CPU speed. If things get worse the board may suffer brown outs and start to randomly, or repeatedly, reboot.

If you have a monitor attached to your Raspberry Pi board this is the point where you’ll see a yellow lightning bolt in the top right hand corner of your screen. However if you’re running your Raspberry Pi headless, you can still check from the command line using .

$ vcgencmd get_throttled

However the output is in the form of binary flags, and therefore more than somewhat impenetrable. Fortunately it’s not that hard to put together a script to parse the output of the command and get something that’s a bit more human readable.

$ sh ./throttled.shStatus: 0x50005Undervolted:   Now: YES   Run: YESThrottled:   Now: YES   Run: YESFrequency Capped:   Now: NO   Run: NO$

If you the script reports that the board is under-volted it’s likely you should replace your power supply with a more suitable one before proceeding. Unless you’re really sure about your own power supply, I’d recommend you pick on the official Raspberry Pi USB power supply.

The official supply has been designed to consistently provide +5.1V despite rapid fluctuations in current draw. It also has an attached micro USB cable, which means that you don’t accidentally use a poor quality cable — something that can really be an issue.

Those fluctuations in demand is something that happens a lot with when you’re using peripherals with the Raspberry Pi, and something that other supplies — designed to provide consistent current for charging cellphones — usually don’t cope with all that well.

Intel Neural Compute Stick. Искусственный разум на флешке — 2 +4

  • 22.11.18 07:28


saul

#430492

Хабрахабр

4800

Машинное обучение, Обработка изображений, Блог компании Intel, Интернет вещей

Не дожидаясь, когда другие вендоры воспользуются ее референсным дизайном AI-модулей на все случаи жизни, Intel сама вывела на рынок новое поколение специализированного компьютера в форм-факторе USB-донгла — Intel Neural Compute Stick 2. Предыдущий Compute Stick еще носил имя Movidius и был выпущен в 2017 году непосредственно после покупки Intel одноименной компании. Теперь у него новое название и новый процессор, существенно превосходящий по производительности предыдущий. А вот цена осталась та же.
Основой устройства служит Intel Movidius Myriad X Vision Processing Unit (VPU) — специализированный SoC, содержащий в себе 16 вычислительных ядер общего назначения, а также аппаратные компоненты для ускорения инференса нейронных сетей и компьютерного зрения. По сравнению со своим предшественником Intel Neural Compute Stick 2 обеспечивает 8-кратный прирост производительности в таких задачах, как классификация изображений и определение объектов.
Основные характеристики устройства таковы:

  • Поддерживаемые фреймворки: TensorFlow, Caffe
  • Подключение: USB 3.0 Type-A
  • Размеры: 72.5 x 27 x 14 мм
  • Совместимые ОС: Ubuntu 16.04.3 LTS (64 bit), CentOS 7.4 (64 bit), Windows 10 (64 bit)

Open Visual Inference & Neural Network Optimization (OpenVINO) toolkitна специальном разделе сайта IDZдоступен для предзаказа

Комментарии (16):

  1. Sdima1357

    22.11.18 10:59/#19401666
    / -3

    Никому не нужная фигня версии 2. Цена не соответствует функциональности. Если бы стоила в десять раз меньше, то можно было бы подумать к чему приспособить, а так нет…

    • saul

      23.11.18 09:26/#19406168

      Если в 10 раз меньше — это уже обычная флешка получится.

      Sdima1357

      23.11.18 11:06/#19406602

      Производительность около одного ТОРs. Orange Pi stick около 2.8 ТОРs за те же деньги .($67 ) Топовый Nvidia более 100 int8 tera op per second.

  2. Vespertilio

    22.11.18 11:05/#19401696
    / +2

    > обеспечивает 8-кратный прирост производительности в таких задачах, как классификация изображений и определение объектов.
    Относительно чего? Есть какие-нибудь сравнительные тесты относительно современных карт Нвидиа например? И почему нет поддержки МакОС?

    excentro

    22.11.18 11:19/#19401758

    Тоже интересно

    CAJAX

    22.11.18 03:11/#19403300
    / +2

    Относительно первой версии.

    NEWANDY

    23.11.18 09:22/#19406156

    Они же не соревнуются в производительности с видеокартами.
    У них же фокус на портативные девайсы с нейронкой.

  3. Plesser

    22.11.18 12:02/#19401970

    На предыдущей версии нельзя было обучать модели, можно ли на этой это делать?

    pda0

    22.11.18 07:16/#19404608
    / +1

    Думаю, что нет, т.к. в этом нет смысла. Эти штуки предназначены чтобы впихнуть предобученную нейросеть в какой-нибудь квадрик. Не для того, чтобы из них собирать кластер. (Я про эту не скажу, но прошлые и rapsberry pi прикидывал, топовая видеокарта уделывает такие кластеры по соотношению цена/производительность, цена/энергопотребление как детей.)

  4. leshabirukov

    22.11.18 04:08/#19403606

    Основные характеристики устройства таковы: Производительность? Напишите, сколько опс и каких (типы данных).

  5. OnelaW

    22.11.18 05:35/#19404134

    Мозг сломал пока сообразил что это за зверек. Как отдельный донгл идея интересная, а если в виде платы расширения под pci? Или гибридное решение.

    • saul

      23.11.18 09:25/#19406162

      Про платы расширения — это предыдущий пост. Сейчас есть ускорители на FPGA, но они сильно дорогие.

      • Mogwaika

        23.11.18 10:25/#19406408

        А какие опреации нужны для нейронок для обучения и для работы?

        pda0

        23.11.18 11:04/#19409448

        Для работы — смотря что за функция в нейроне. Обычно нужна сложение-умножение. Для обучения — смотря что за метод.

  6. r_ii

    22.11.18 07:03/#19404572

    Вполне себе полезный «ускоритель» для IoT устройств. Практический пример — позволяет распознавать объекты в видео потоке в режиме реального времени на Raspberry Pi 3.
    Но я бы не стал его рассматривать как устройство для PC.

  7. n0th1ng

    23.11.18 06:39/#19405876

    Интересно, можно ли с помощью этого стика и Raspberry Pi 3 сделать автономного робота?

What’s Relevant in the Repository

The inference-engine provides the API used to initiate neural network inferences and retrieve the results of those inferences. In addition to the API, the inference engine directory also includes plugins for different hardware targets such as CPU, GPU, and the MYRIAD VPU. When the API is called it will rely on the plug-ins to execute inferences on these hardware targets.For execution on the Intel NCS 2 (or the original Intel Movidius NCS) the inference engine needs to call the MYRIAD VPU plug-in. Therefore, the bare minimum which will need to be built to use an Intel NCS 2 is the inference engine API and the MYRIAD plug-in. The other plug-ins in the repository will not be needed and depending on your platform may not apply.

Setting Up to Build

To prepare the system for building, the build tools, the git submodules, and the dependencies need to be on the build system. Each of these are explained in this section.

ncappzoo Compatibility Requirements

Hardware compatibility

The projects in the ncappzoo are periodically tested on Intel x86-64 Systems unless otherwise stated in the project’s README.md file. Although not tested on other harware platforms most projects should also work on any hardware which can run the OpenVINO toolkit including the Raspberry Pi 3/3B/3B+/4B hardware
The projects in the ncappzoo work on both the Intel NCS2 and the original Intel Movidius NCS devices.

Operating System Compatibility

The projects in the ncappzoo are tested and known to work on the Ubuntu 18.04 OS. These projects will likely work on other Linux based operating systems as well but they aren’t tested on those unless explicitly stated in the project’s README.md file and there may be some tweaks required as well. If any specific issues are found for other OSes please submit a pull request as broad compatibility is desirable.

OpenVINO and DLDT Compatibility

The projects in the master branch depend on the Deep Learning Deployment Toolkit (DLDT) portion of the OpenVINO toolkit. There are two flavors of the the OpenVINO toolkit’s DLDT:

  • The open source distribution of the OpenVINO toolkit DLDT. This is the means by which the Intel NCS2 device can be used with most single board computers on the market and is also helpful for other non-Ubuntu development systems. Here are some links regarding the open source distribution of the OpenVINO with the Intel NCS2:

Note: When using the open source distribution of the OpenVINO toolkit, you may need to modify your shell’s path and environment variables to point to the toolkit’s directories.

The projects in the ncappzoo work with both flavors of the OpenVINO Toolkit and unless otherwise specified in a project’s README.md file all projects are targeted for the OpenVINO Toolkit 2020.1 release.

OpenCV Compatibility

Some projects also rely on OpenCV. For these projects, OpenCV distributed with the OpenVINO release is the recommended version. Other versions may also work but are not tested an may require tweaks to get working.

Raspberry Pi Compatibility

The ncappzoo is compatible with the Raspberry Pi 3 B+ and the Raspberry Pi 4. Some additional configuration steps are required:

Intel Distribution of OpenVINO for Raspbian* OS

The Intel Distribution of OpenVINO toolkit for Raspbian OS does not include the Model Optimizer. To use the ncappzoo, you must clone the open source version of the OpenVINO Deep Learning Development Toolkit (DLDT) and use that version of the Model Optimizer. Clone the repository, install dependencies for TensorFlow* and Caffe*, and set up your PATH and PYTHONPATH variables to point to the Model Optimizer:

Open Source OpenVINO Deep Learning Development Toolkit (DLDT)

To setup the open source version of OpenVINO with your Raspberry Pi, add to the PATH, PYTHONPATH, and LD_LIBRARY_PATH environment variables the location of the build Inference Engine libraries and Python API.

Компактный нейронный сопроцессор

Компания Movidius, принадлежащая Intel и занимающаяся разработкой визуальных процессоров для интернета вещей, представила миниатюрное компактное устройство Neural Compute Stick. Новинка позиционируется как вычислительный сопроцессор с функциональностью искусственного интеллекта, позволяющий добавить возможность машинного обучения подключенному ПК простым подключением к порту USB.

Ключевая особенность устройства заключается в том, что для процесса машинного обучения или развертывания новой нейронной сети с применением Neural Compute Stick не требуется подключение к интернету: USB-сопроцессор функционирует совершенно автономно.

В сентябре 2016 г. компания Movidius была приобретена Intel за неназванную сумму. По итогам сделки в Intel объявили о планах использовать технологии Movidius при разработке устройств интернета вещей, дополненной, виртуальной и совмещенной реальности, таких как роботах, дронах, автоматических цифровых камерах безопасности и т.д.

Впервые USB-сопроцессор Neural Compute Stick был представлен в качестве прототипа под рабочим названием Fathom в апреле 2016 г. – тогда еще независимой компанией Movidius. Некоторое время после приобретения компании новости о разработках Movidius исчезли со страниц новостных сайтов. Теперь Neural Compute Stick коммерциализирован и официально поступает в продажу, однако технологическая идея устройства претерпела минимальные изменения по сравнению с Fathom.

USB-сопроцессор Movidius Neural Compute Stick

Устройство Neural Compute Stick выполнено на базе точно такого же процессора, который используется во множестве устройств с машинным зрением — например, автономном дроне DJI. Потребителю или производителю техники, желающему усилить возможности искусственного интеллекта своей системы, достаточно подключить один или несколько сопроцессоров Neural Compute Stick к порту (портам) USB.

Разработка под Intel NCS

Для разработки под Intel NCS вам потребуется непосредственно само устройство и SDK для него. В состав SDK входит NC Toolkit и NC APINC Toolkit включает в себя Profiler, Checker и CompilerProfiler использует готовую нейронную сеть (на базе Caffe или Tensorflow), позволяет строить для нее графическое представление, выполняет сеть на NCS и собирает различные метрики (количество flops, размер, время работы для каждого слоя). Checker используется для запуска процедуры распознавания для конкретного изображения и проверки результатов классификации. Compiler преобразует Caffe/Tensorflow модель в граф, с которым может работать Intel MovidiusNCAPI используется в приложениях, которые работаю с NCS через USB. Workflow работы с NCS выглядит следующим образом.

На этом мы закончим краткий обзор Intel Movidius Neural Compute Stick. В следующей статье мы разберем установку NCSDK на VirtualBox и запуск тестового приложения.

Installation and Build Notes

OpenCV

The article linked above asks you to download OpenCV from source directly from OpenCV’s public GitHub repository.  However, as of 7/18/2019, the current repository fails to build on Raspbian 10. Instead, download the stable OpenCV-4.1.0 and build from that source package. Commands are below to build and install OpenCV from that package in a folder called OpenVINO on the current user’s home directory. This will also build the Python* 3 libraries for OpenCV:

This will build a compatible version of OpenCV. You can continue on to build the Deep Learning Deployment Toolkit at this point. Don’t forget to set the OpenCV_DIR environment variable to the install location of OpenCV:

To verify the correct version of OpenCV, use the commands below. These commands require the OpenCV Python 3 wrapper, which is built with the commands above:

The command should return ‘4.1.0’.

OpenVINO

OpenVINO should build correctly on your Raspberry Pi 4 if you’ve built the correct version of OpenCV. However, an issue with the GCC* compiler’s default settings may cause runtime issues. To solve this, build the toolkit with the following CMake flag:

Your full CMake command should look like the following: