Install mpi on windows

Установка и начала использования библиотеки MPI

Иногда необходимо запустить приложение на нескольких машинах (или процессорах), чтобы улучшить производительность (т.е. уменьшить время выполнения). Можно создать компьютерную сеть для последующего запуска приложения распределённо по всем узлам. При разработке такого приложения необходимо организовать обмен сообщениями. Я знаю две реализации:

  • использование сокетов и работа с OS API напрямую,
  • использование MPI.

Первый вариант обладает большими возможностями, но библиотека MPI существенно проще и, в действительности, шире применяется в параллельных вычислениях. MPI представляет собой стандарт некоторого набора функций для обмена сообщениями между процессами одного приложения. Существует бесплатная реализация данной библиотеки MPICH2, которая будет использоваться в данной статье. Вы модете найти большое количество мануалов и руководств по функциям библиотеки. Сейчас я остановлюсь только на установке и проверке работоспособности.

Установка библиотеки MPICH2 под Windows

Для того чтобы начать работу с библиотекой MPICH2, необходимо скачать совместимую с используемой операционной системой версию продукта здесь. Для ОС Windows – это установочный пакет формата MSI, поэтому инсталляция библиотеки проходит стандартным образом. Важно, что установку в этом случае надо проводить для всех пользователей системы.

Теперь необходимо добавить два основных исполняемых файла библиотеки mpiexec.exe и smpd.exe в список правил брандмауэра. Это необходимо, поскольку, при организации кластера используется сеть и доступ к каждому узлу сети должен быть разрешен для компонентов MPI. Конкретные настройки зависят от типа используемого брандмауэра.

На следующем этапе необходимо создать пользователя в системе, от имени которого будут исполняться компоненты библиотеки. Важно, что данный пользователь обязательно должен иметь свой пароль, т.к. MPICH2 не позволяет зарегистрировать исполняющего пользователя с пустым паролем. Регистрация осуществляется с помощью компонента wmpiregister.exe, находящегося в папке bin библиотеки и имеющего понятный оконный интерфейс:

Однако, это возможно сделать, используя консольную команду [путь_к_библиотеке]/bin/mpiexec -register.

Установка практически завершена. Осталось проверить правильность всех сделанных настроек. Для этой цели в папке examples есть примеры программ с параллельными алгоритмами. Для запуска можно использовать компонент wmpiexec.exe, который использует оконный интерфейс, который не нуждается в дополнительных комментариях.

Другой путь для исполнения приложений с использованием MPI – через консоль, например, написав подобную команду [путь_к_библиотеке]/bin/mpiexec -n 2 cpi.exe, где -n 2 указывает количество задействованных процессов (здесь их 2), а cpi.exe – это имя исполняемого приложения. Для простоты работы через консоль советую добавить в переменную окружения PATH путь к mpiexec.exe. Если выполнение приложения производится на однопроцессорной машине, то происходит эмуляция многопроцессорности, т.е. проверять работоспособность своих приложений можно «не отходя от кассы».

Проверка работоспособности

В качестве IDE для разработки используется MVS 2005. Напишем программу, которая будет привествовать этот мир от имени разных новорожденных процессов процессов. Для этого используется пустой проект (empty project) с изменением некоторых настроек проекта.

Читайте также:  4 гигабайта оперативной памяти windows

Итак, в первую очередь добавим директории, где будут лежать подключаемые заголовочные файлы и файлы библиотеки. Если кто-то не знает, то делается это следующим образом:

  • Выбираем пункт меню Tools => Options.
  • В дропдауне “Show directories for:” выбираем пункт “Include files”.
  • Добавляем [путь_к_библиотеке]\Include
  • В дропдауне “Show directories for:” выбираем пункт “Library files”.
  • Добавляем [путь_к_библиотеке]\Lib
  • В Solution Explorer кликаем правой кнопкой мыши на проекте и выбираем add => existing item. Выбираем все файлы с расширением .lib в папке [путь_к_библиотеке]\Lib

Проект полностью готов для работы с MPI. Могу посоветовать создавать фильтр для файлов библиотеки, добавленных в проект, чтобы они не мешались. Теперь добавим cpp файл с кодом приложения:

#include «stdio.h»
#include «mpi.h»
#include «stdlib.h»
#include «math.h»

int ProcNum;
int ProcRank;

int main( int argc, char *argv[]) <
MPI_Status status;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank);
MPI_Comm_size(MPI_COMM_WORLD, &ProcNum);

printf( «From process %i: Hello, World!\n» , ProcRank);

* This source code was highlighted with Source Code Highlighter .

Компилируем его и запускаем полученный бинарник через wmpiexec на 4 процессах.

Как видим, мир поприветствовал каждый рождённый процесс.

Я умышленно приводил код без каких либо комментариев, а только с целью демонстрации работы библиотеки. В будущем я планирую посвятить статью списку функций MPI. Также интересной является тема избыточной параллельности и, вообще, вопрос когда стоит распарарллеливать приложение, а когда нет. Эти исследования также будут приведены позже. Поэтому у меня возник основной вопрос — сфера применимости в web технологиях? Пока мой интерес к параллельным вычислениям вызван другой проблемой: ускорение моделирования разного рода процессов.

Настройка среды для MPI-программирования

Выбираем операционную систему, затем переходим по ссылке и скачиваем msi — файл , например:

Затем следует щелкнуть по имени файла, тогда запустится программа -установщик. Для установки потребуются права Администратора системы ( запуск MPI -программ выполняется соответствующей службой).

После щелчка будет произведена установка диспетчера процессов spmd ( spmd process manager ). Необходимо указать «секретное» слово . По умолчанию это:

В меню «Пуск»->»Все программы» появится раздел MPICH2 с пунктами:

jumpshot wmpiconfig.exe wmpiexec.exe wmpiregister.exe

В папке MPICH2 располагаются папки:

Динамически подключаемые ( dll ) библиотеки копируются в папку windows/system32 . Диспетчер процессов smpd автоматически запускается сразу же после установки MPICH2 , а также после перезагрузки системы.

Запустим MS Visual Studio 2008 и создадим новый проект Win32 Console Application (Консольное приложение Win32), в конфигурации Release.В окно проекта копируется исходный текст программы, если он уже существует или программа набирается заново. Затем необходимо настроить пути и ссылки на библиотеку MPICH2 .

В строке Project ->

properties -> C++->General->Additional Include Directories вводится путь к каталогу include (см. рис. П-1).

В строке Project ->

properties -> C++->Linker->General->Additional Library Directories вводится путь к каталогу lib (см. рис. П-2).

В строке Project ->

properties -> C++->Linker->Input->Additional Dependencies вводится имя библиотеки mpi.lib (см. рис. П-3).

Теперь проект настроен на использование MPICH2 .

Using Intel® MPI Library 5.1 on Microsoft* Windows* with Microsoft* MPI based applications

Published: 02/25/2016 Last Updated: 02/25/2016

Why it is needed?

In the past, different MPI implementations were binary incompatible with one another. This meant that you had to recompile your MPI application to use it with a different MPI implementation.

Читайте также:  Search setting windows 10

Fortunately, the situation has changed since then. At Supercomputing 2013, Argonne National Laboratory, Intel, Cray and IBM announced a common initiative for binary compatibility of MPI implementations. With this initiative, MPICH-based MPI implementations become binary compatible with one another, and no recompilation is needed to use a different MPI implementation with your compiled MPI application. This creates the possibility to compare performance of a particular HPC application when using different MPI implementations.

Intel® MPI Library on Windows* has the following benefits:

  • Support of the wide range of cluster hardware and software
    • Full support and tuned performance of all modern Intel® processors;
    • Full support and tuned performance of wide variety of modern interconnects, full support of Intel® interconnects;
  • Integration with Intel® Trace Analyzer and Collector
    • Tracing all MPI events in parallel application;
    • Disbalance detection;
    • MPI correctness checks;
    • API for user code instrumentation;
  • Extended debug and statistics
    • Intel MPI Library can collect key statistics about parallel run to identify issues and tune performance;
  • Full control of parallel application execution
    • Rich set of controls via environment variables, control flags or configuration files;
  • Support
    • Online support with Intel® Premier Support;
    • Intel® Developer Zone;
    • Forums.

Requirements

Install the Intel MPI Library for Windows OS on system based on the Intel® 64 architecture.

Step-by-step how to

To use Intel MPI Library 5.1 on Windows with MS-MPI* based applications you can recompile the sources of your application with Intel MPI Library, or use binary compatibility without recompilation.

In this article, the latter option will be covered.

Intel® C++/Fortran Compiler for Windows is used for building applications.

Let’s consider the following simple MPI application:

    For testing purposes compile the application with MS-MPI:

Check the MS-MPI library dependency:

> dumpbin /dependents .exe

Dump of file testapp.exe

File Type: EXECUTABLE IMAGE

Image has the following dependencies:

Launch the application with MS-MPI and check the output:

> mpiexec –n 2 testapp.exe

Microsoft MPI 7.0.12437.6

Prepare Intel MPI Library environment for MS-MPI application launches, invoke the application, and check the output:

> copy impi.dll msmpi.dll

> mpiexec –n 2 testapp.exe

Intel(R) MPI Library 5.1.2 for Windows* OS

5. A simple MS-MPI Fortran application code and the steps to launch it with Intel MPI Library are as follows:

> ifort path to MS-MPI Include directory >/mpi.f90 testapp.f90 -o testapp.exe -I» path to MS-MPI Include directory >» -I»» path to MS-MPI Include directory >\x64″ /link /LIBPATH:»

>\x64″ msmpifec.lib msmpi.lib

> mpiexec –n 2 testapp.exe

Microsoft MPI 7.0.12437.6

> copy impi.dll msmpi.dll

> mpiexec –n 2 testapp.exe

Intel(R) MPI Library 5.1.2 for Windows* OS

Conclusion

This article demonstrates how to run an application linked with a non-Intel MPI implementation using Intel MPI Library on Windows* OS. To evaluate Intel MPI Library you can download the Intel MPI Library Runtime Environment free of charge (with limited support options). For more details, please refer to the Intel MPI Library Licensing FAQ.

*Other names, brands , and images may be claimed as the property of others.

Читайте также:  Как очистить все журналы windows

Install MPI on Windows, Mac and Ubuntu

(If you meet any errors and need help, please leave them in the comments.)

Windows

  1. Install Microsoft Visual Studio.
  2. Install Microsoft MPI (MSDN)
    Find here.
  3. Test

Install Open MPI in Ubuntu 14.04, 13.10

  1. Download the latest version of OpenMPI:
  1. Open a terminal, install dependencies (you could add “sudo” before some of the commands if you are meeting errors!):

sudo apt-get install libibnetdisc-dev

  1. Decompress the download file:

sudo tar -xvf openmpi-1.10.2.tar.bz2

cd openmpi-1.10.2
4. Configure the installation file
./configure –prefix=”/home/$USER/.openmpi”

  1. Install OpenMPI (This path will take time to complete, few minutes)

sudo make install
6. Setup path in Environment Variable

export PATH=”$PATH:/home/$USER/.openmpi/bin”
export LD_LIBRARY_PATH=”$LD_LIBRARY_PATH:/home/$USER/.openmpi/lib/”
7. Test if install was successful

mpirun
Result should show ‘How to use’ message:

Install Open MPI in Mac

  1. Download the latest version of OpenMPI:
  1. Open a terminal, install dependencies:

sudo apt-get install libibnetdisc-dev
3. Decompress the download file:

tar -xvf openmpi-1.10.2.tar.bz2

cd openmpi-1.10.2
4. Configure the installation file
./configure –prefix=/usr/local/openmpi
5. Install OpenMPI (This path will take time to complete, few minutes)

sudo make install
6. Setup path in Environment Variable

export MPI_DIR=/usr/local/openmpi
echo $PATH
export PATH=/usr/local/openmpi/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/openmpi/lib:$LD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=$LD_LIBRARY_PATH

  1. Test if install was successful

mpirun
Result should show ‘How to use’ message:

Install mpi on windows

Microsoft MPI (MS-MPI) is a Microsoft implementation of the Message Passing Interface standard for developing and running parallel applications on the Windows platform.

MS-MPI offers several benefits:

  • Ease of porting existing code that uses MPICH.
  • Security based on Active Directory Domain Services.
  • High performance on the Windows operating system.
  • Binary compatibility across different types of interconnectivity options.

Version of MPI standard

MS-MPI is MPI 2.2 compliant with the exception of Fortran bindings errata around attributes interop between C and Fortran. MS-MPI implements a subset of features from MPI 3.1 standard:

  • Non-blocking collectives,
  • RMA,
  • MPI shared memory,
  • New datatypes,
  • Large counts,
  • Matched probe.

For the full list of APIs please see Microsoft MPI Reference.

The following are current downloads for MS-MPI:

Earlier versions of MS-MPI are available from the Microsoft Download Center.

Microsoft high performance computing resources

  • Featured tutorial: How to compile and run a simple MS-MPI program
  • Featured guide: Set up a Windows RDMA cluster with HPC Pack and A8 and A9 instances to run MPI applications
  • Microsoft High Performance Computing for Developers
  • Microsoft HPC Pack (Windows HPC Server) Technical Library
  • Azure HPC Scenarios

Please make sure to select the following workloads during installation:

  • .NET desktop development (required for CBT/Nuget packages)
  • Desktop development with C++
  • Update GFORTRAN_BIN in Derectory.Build.props to the install location of GFortran

Based on the installed VS/SDK/WDK versions, update VCToolsVersion and WindowsTargetPlatformVersion in Directory.Build.props

Note that the build system uses CommonBuildToolSet(CBT). You may need to unblock CBT.core.dll (under .build/CBT) depending on your security configurations. Please refer to CBT documentation for additional details.

To build, open a Native Tools Command Prompt for Visual Studio and run msbuild from root folder.

Оцените статью