Patrones de Programación Paralela

Download Report

Transcript Patrones de Programación Paralela

Patrones de Programación Paralela
Sesión:
Intel® Software College
Objetivos
Al término de esta sesión, será capaz de:
• Describir los conceptos detrás de los patrones de diseño y
patrones de diseño en paralelo
• Dados códigos seriales o algoritmos, escoger la mejor
Estructura Algorítmica en el patrón de diseño (paralelismo de
tarea o descomposición geométrica) para usarse en la
paralelización del código y defender su selección.
• Dado el código serial o algoritmos, escoger la mejor
Estructura de Soporte en el patrón de diseño (SPMD,
Paralelismo de ciclos o Maestro/Esclavo) para usarse en la
paralelización de código y defender su selección.
2
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Agenda
Patrón de estructura de lenguaje
El patrón de paralelismo de tareas
El patrón de descomposición geométrica
Estructuras de Soporte
Resumen
3
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Agenda
Patrón de estructura de lenguaje
El patrón de paralelismo de tareas
El patrón de descomposición geométrica
Estructuras de Soporte
Resumen
4
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrones de Diseño y Patrones de
Lenguajes
Un patrón de diseño es:
• Una “solución de un problema en un contexto.”
• Una descripción estructurada de soluciones de alta calidad a
problemas recurrentes
• Un intento de codificar experiencia tal que todos los
diseñadores puedan capturar que “ la calidad sin un nombre"
que distingue realmente excelentes diseños
Un patrón de lenguaje es:
• Un catálogo estructurado de patrones de diseño que soportan
actividades de diseño como “redes de patrones de diseño
conectadas”
5
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Referencia
Detalla un patrón de lenguaje para
diseño de algoritmos paralelos
Ejemplos en MPI, OpenMP y Java
Representa la hipótesis del autor
para como los programadores
piensan acerca de la programación
en paralelo
Patterns for Parallel Programming, Timothy G.
Mattson, Beverly A. Sanders, Berna L. Massingill,
Addison-Wesley, 2005, ISBN 0321228111
6
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Estructura del Lenguaje
El diseño de software puede verse como una serie de mejoras
Considera el proceso en términos de 4 espacios de diseño
• Progresivamente añade al diseño elementos en niveles
inferiores
7
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Estructura del Lenguaje
Espacio de diseño
Encontrando concurrencia
Evolución del diseño
Tareas, datos compartidos,
órdenes parciales
Estructura del algoritmo
Hilo/Estructuras de proceso,
planificación
Estructuras de soporte
Organización del código fuente, Datos
compartidos
Mecanismos de
implementación
8
Mensajes, sincronización, división
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Encontrando Concurrencia del Diseño del
Espacio
Encontrando el alcance de la paralelización:
• Comienza con una aplicación secuencial que resuelve el
problema original
• Descompone la aplicación en tareas o conjuntos de datos
• Analiza la dependencia entre tareas antes de la
descomposición
9
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Encontrando Concurrencia del Diseño del
Espacio
Análisis de descomposición
Análisis de dependencias
Agrupar tareas
Descomposición de dominios
Descomposición de tareas
Ordenar grupos
Compartir datos
10
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Encontrando concurrencia
Del código serial:
• Usa un analizador, tal como “Intel® VTuneTM Performance
Analyzer”
• Identifica hotspots en una aplicación
• Examina el código en los hotspots
• Determina cuando las tareas dentro de los hotspots pueden
ejecutarse independientemente
De un documento de diseño:
• Examina los componentes de diseño
• Encuentra componentes que contienen operaciones
independientes
11
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Espacio de Diseño de la Estructura del
Algoritmo
Estructura usada para organizar computo para soportar
paralelismo
¿Cómo está estructurado el cómputo?
Organizado por datos
¿Lineal?
Descomposición
Geométrica
12
¿Recursivo?
Datos
Recursivos
Organizado por tareas
¿Lineal?
Paralelismo
de tareas
¿Recursivo?
Divide y
Vencerás
Organizado por flujo
de datos
¿Regular?
Pipeline
¿Irregular?
Coordinación
basada en
eventos
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Consideraciones que afectan a las
estructuras de los algoritmos
Las siguientes consideraciones afectan las metas de diseño,
• Eficiencia
• El programa paralelo debe ejecutarse rápidamente y hacer buen
uso de los recursos de procesamiento
• Simplicidad
• Algoritmos simples (fáciles de entender) son más fáciles de
desarrollar, depurar, verificar y mantener
• Portabilidad
• Los programas deben ejecutarse en el rango más amplio de
computadoras paralelas
• Escalabilidad
• Los algoritmos paralelos deben ser efectivos en un amplio rango
de número de hilos y núcleos, y tamáños de datos o conjuntos de
datos
13
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Consideraciones que afectan a las
estructuras de los algoritmos
Puede haber conflictos entre dos o más de las consideraciones
(Eficiencia, Simplicidad, Portabilidad, Escalabilidad)
• El balanceo de las consideraciones es crítico para obtener el
mejor código paralelo
14
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Estructuras de Soporte del Espacio de
Diseño
Bloques de construcción de alto nivel usados para organizar el
código fuente
Categorizados en estructuras de programa y estructuras de
datos
Estructuras de
Programa
SPMD
Single Program Multiple Data
Estructuras de Datos
Datos compartidos
Paralelismo de Ciclos
Maestro/Esclavo
Fork/Join
15
Cola compartida
Arreglo distribuido
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Mecanismos de Implementación del Espacio
de Diseño
Bloques de construcción de bajo nivel implementando bloques
de construcción específicos usados en cómputo paralelo
• No propiamente patrones de diseño; incluidos para hacer el
patrón del lenguaje autónomo
Gestión del UE*
Control de hilos
Control de Procesos
Sincronización
Comunicaciones
Sinc. de Memoria/Vallas
Paso de Mensajes
Exclusión Mutua
Com. Colectiva
Barreras
Otras Com
* UE = Unidad de Ejecución
16
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Agenda
Patrón de estructura de lenguaje
El patrón de paralelismo de tareas
El patrón de descomposición geométrica
Estructuras de Soporte
Resumen
17
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Estructuras de Algoritmos del Espacio de
Diseño
¿Cómo está estructurado el cómputo?
Organizado por datos
¿Lineal?
Descomposición
Geométrica
18
¿Recursivo?
Datos
Recursivos
Organizado por tareas
¿Lineal?
Paralelismo
de tareas
¿Recursivo?
Divide y
Vencerás
Organizado por flujo
de datos
¿Regular?
Pipeline
¿Irregular?
Coordinación
basada en
eventos
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Tareas
Problema:
• ¿Cómo puedes explotar la concurrencia en términos de un
conjunto de distintas tareas?
Ejemplos:
• Ray tracing – el cómputo de cada rayo es independiente al
cómputo de cualquier otro rayo
• Dinámica Molecular – Actualización de las fuerzas sobre los
átomos es independiente; combinando todos las fuerzas de
los cómputos parciales de cada hilo se hace cuando terminan
todas las fuerzas son calculadas
19
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Contexto del Patrón de Paralelismo de
Tareas
Cada algoritmo es una colección de tareas concurrentes
• Puede encontrarse a través de la inspección del código
• El factor común es descomponer la computación en una
colección de tareas concurrentes
• Las tareas pueden ser completamente independientes
• Las tareas pueden tener dependencias que necesitan satisfacerse
20
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Contexto del Patrón de Paralelismo de
Tareas
Las tareas son usualmente conocidas a principio de la
computación
Las tareas pueden surgir dinámicamente (por ejemplo,
búsqueda en un árbol)
Normalmente deben esperar a que todas las tareas terminen
antes de completar el problema
• Puede ser capaz de terminar cuando se encuentra la solución
antes de completar todas las tareas
• Ejemplo: Búsqueda - si el elemento se encuentra, no es necesario
seguir buscando, si el elemento no estaba presente, debe
terminar de la búsqueda para asegurarse
21
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Consideraciones del Patrón de Paralelismo
de Tareas
Tamaño de Tareas
• Tareas pequeñas para balancear carga vs. Tareas grandes
para reducir sobrecarga de planificación
Administrando Dependencias
• Sin destruir eficiencia, simplicidad, o escalabilidad
22
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Soluciones del Patrón de Paralelismo de
Tareas
Tres elementos de diseño clave para patrones de paralelismo de
tareas
• Tareas y cómo se definen
• Las dependencias entre las tareas
• Planificación de las tareas a hilos
23
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Definiendo Tareas
Descomponer un algoritmo serial con descomposición de tareas
de reunir dos criterios:
• Debe ser al menos un número de tareas como hilos (o
núcleos)
• Preferible que haya más tareas que hilos
• Mayor flexibilidad en la planificación
• Ayudar a lograr una carga más equilibrada entre los hilos
• La cantidad de cómputo dentro de una tarea debe ser lo
suficientemente grande como para compensar la sobrecarga
de gestión de tareas e hilos
Si la descomposición inicial no reúne estos criterios, deben
considerarse descomposiciones alternas
24
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: ejemplo de definición de tareas
Considere una aplicación de procesamiento de imágenes, donde
cada pixel es independiente
¿Cuál es el nivel apropiado de descomposición de tareas?
• Tarea == un pixel
• Tarea == una línea
• Tarea == bloques dentro de la imagen
25
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Administrando Dependencias en Soluciones en el Patrón de
Paralelismo de Tareas
Ordenar los acuerdos entre las tareas pueden ser manejados
para forzar grupos de tareas a ejecutarse en orden
Paisaje
Poner
techo
Tejas en
el techo
Construir
Paredes
Instalación
Eléctrica
Enjarre
Parte
Exterior
26
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Gestionando Dependencias en Patrones de
Solución de Paralelismo de Tareas
Resolver dependencias de datos puede ser más complicado
• El caso más simple es tener no dependencias
(vergonzosamente paralelas)
• Estrategias para manejar dependencias de datos entre
tareas:
•
•
•
•
Removerlas (replicando datos)
Transformando variables de inducción
Reducciones
Protegiendo explícitamente (patrón de datos compartidos)
27
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dependencias Removibles
No una dependencia verdadera, pero una dependencia aparente
que puede eliminarse con transformación de código
La solución más simple sería crear, inicializar, y usar variables
locales
• Puede implicar la replicación de trabajo dentro de los hilos
Algoritmo Serial:
Calcula X
Calcula Y
Calcula Z
For i = 1, 20
Calcula a[i] = F(X,Y,Z,b[i])
28
Hilo 1
Calcula global X
Calcula
Calcula local
globalX Y
Calcula
Calcula local
globalY Z
Calcula
localX,Y,Z
Z listos
Envía señal
For
For ii =
= 1,
1, 10
10
Calcula
a[i]
Calcula a[i] =
= F(X,Y,Z,b[i])
F(X,Y,Z,b[i])
Hilo 2
Espera que X,Y,Z estén listos
Calcula local X
Calcula local Y
Calcula local Z
For i = 11, 20
For i = 11, 20
Calcula a[i] = F(X,Y,Z,b[i])
Calcula a[i] = F(X,Y,Z,b[i])
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dependencias Removibles
Las variables de inducción se
incrementan en cada pasada
dentro del ciclo
Arreglar reemplazando los
incrementos con expresiones
equivalentes en función al
índice del ciclo
29
i1 = 4;
i2 = 0;
for (I = 0; I < N; I++)
{
B[i1++] = ... ;
i2 = i2 + I;
A[i2] = ... ;
}
for (I = 0; I < N; I++)
{
B[I+4] = ...;
A[((I+1)*I)/2)] = ...;
}
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dependencias “Separables”
Dependencias en estructuras de datos compartidas usadas para
acumular de datos calculados en cada hilo
• Mueve la acumulación fuera de la concurrencia:
• Replica los datos a cada hilo, inicialízalos como se requiera
• Ejecuta las tareas usando la copia local de la estructura de datos
• Al completarse, combina todas las copias en una estructura de
datos global
30
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dependencias “Separables”
• El ejemplo más común: Reducción
• Una colección de datos se reduce a un solo valor aplicando
una operación binaria a todos los elementos de la colección
• La operación binaria debe ser asociativa y conmutativa
for (int i = 0; i < N; i++)
sum += a[i] * b[i];
31
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Protección Explícita de Datos Compartidos
Si la dependencia no puede removerse o separarse desde las
tareas, entonces los datos compartidos que se actualizan deben
protegerse
Implementa una región crítica en el código que accesa datos
compartidos
• Si se hace cualquier actualización, todos los accesos (lectura
y escritura) deben estar en una región crítica
• Agrega lógica de programación para forzar la exclusión mutua
en una región crítica
• Usa objetos de sincronización apropiada para crear exclusión
mutua
32
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Planificando Tareas
Las tareas deben asignarse a hilos para que se ejecuten
Planifica tareas con carga de trabajo balanceada
Usuales dos tipos de planificación
• Planificación estática
• Las tareas se asignan a hilos al inicio del cómputo y no cambian
• Fácil de programar y provoca poca sobrecarga
• Debe usarse siempre que sea posible
• Planificación dinámica
• Las tareas se asignan conforme procede el cómputo
33
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Consideraciones de Planificación Estática
El trabajo debe diferenciarse con id de hilo único para cada hilo
Si las tareas son colecciones de llamadas a funciones
independientes separadas
• Agrupa las llamadas en tareas que son asignadas a hilos
Si las tareas son iteraciones de ciclos, dos planificaciones
posibles
• Divide el número total de iteraciones entre el número de hilos
y asigna un bloque de iteraciones a los hilos
• Inicia cada conjunto de hilos de iteración por número de id de
hilo (0..N-1), cada hilo calcula cada enésima iteración
34
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Consideraciones de Planificación Dinámica
Usada cuando el tamaño de la ejecución de tareas es variable e
impredecible
Métodos posibles para planificación dinámica de tareas
1. Usar una estructura compartida para mantener las tareas
• Si las tareas se pueden encapsular dentro de una estructura, crea
una cola global que tener y despachar tareas cuando los hilos
necesiten más trabajo
• Si las tareas se almacenan en un archivo, los hilos comparten
acceso para leer tareas del archivo
35
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Consideraciones de Planificación Dinámica
Métodos posibles para planificación dinámica de tareas
2. Algunas tareas pueden tomar pre-procesamiento en orden
de estar listas para que se les asigne computación
• Usa un hilo extra para obtener tareas listas para los hilos y
asignarlas a hilos cuando sean solicitadas (Patrón
maestro/esclavo)
• Usar un hilo extra para poner tareas en una cola compartida para
que otros hilos las tomen conforme las necesiten (patrón
Productor/Consumidor)
3. Si las tareas están indexadas, crea un contador compartido
para mantener registro de y asignar la próxima tarea a
ejecución
36
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Evitar Desastres Aereos
Z
Y
X
37
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Evitar Desastres Aereos
Escenario de un conjunto de aviones alrededor de un
aeropuerto
¿Hay dos aviones demasiado cerca entre ellos mismos?
• Si, envía un mensaje de advertencia y registra el evento
• Lleva registro del número de advertencias generadas por un
avión en el escenario
• Será usado para determinar cual vuelo puede estar más en
peligro
38
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Evitar Desastres Aereos
Los aviones tienen un número de vuelo y una posición actual en
un espacio 3-D
• X y Y son la posición con respecto a la tierra (mapa)
• Z es la altitud actual
Pseudo-código en la siguiente diapositiva
• El cálculo de la distancia se usa para determinar peligro
potencial
39
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Posicionamiento de
Aviones
function AirplanePositions (N, M, Flights)
int const N, M;
//Número de aviones, aeropuertos
Array of Airplane_t :: Flights(N); // arreglo de estructuras de aviones
Real :: distX, distY, distZ, distance
loop [j = 0, N]
loop [k = j+1, N]
distX = (Flights[j].Xcoord – Flights[k].Xcoord) ^ 2
distY = (Flights[j].Ycoord – Flights[k].Ycoord) ^ 2
distZ = (Flights[j].Zcoord – Flights[k].Zcoord) ^ 2
distance = sqrt(distX + distY + distZ)
if (distance < SAFETY_MARGIN)
PrintWarning(Flights[j],Flights[k])
Flights[j].numWarnings++
Flights[k].numWarnings++
end loop[k]
end loop[j]
end function AirplanePositions
40
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Posicionamiento de
Aviones– Definir tareas
function AirplanePositions (N, M, Flights)
int const N, M;
//number of planes, airports
Array of Airplane_t :: Flights(N); // array of planes structs
Real :: distX, distY, distZ, distance
loop [j = 0, N]
loop [k = j+1, N]
distX = (Flights[j].Xcoord – Flights[k].Xcoord) ^ 2
distY = (Flights[j].Ycoord – Flights[k].Ycoord) ^ 2
distZ = (Flights[j].Zcoord – Flights[k].Zcoord) ^ 2
distance = sqrt(distX + distY + distZ)
if (distance < SAFETY_MARGIN)
PrintWarning(Flights[j],Flights[k])
Flights[j].numWarnings++
Flights[k].numWarnings++
end loop[k]
El cálculo de la distancia
end loop[j]
entre cada avión es una
end function AirplanePositions
tarea
41
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Posicionamiento de
Aviones – Dependencias
function AirplanePositions (N, M, Flights)
int const N, M;
//Número de aviones, aeropuertos
Array of Airplane_t :: Flights(N); // arreglo de estructuras de aviones
Cada hilo necesitará una
Dar
a cada
hilolos
una
copia del
local
copia
local de
índices
loop [j = 0, N]
de esas variables
ciclo j,k de trabajo
loop [k = j+1, N]
Real :: distX, distY, distZ, distance
distX = (Flights[j].Xcoord – Flights[k].Xcoord) ^ 2
distY = (Flights[j].Ycoord – Flights[k].Ycoord) ^ 2
distZ = (Flights[j].Zcoord – Flights[k].Zcoord) ^ 2
distance = sqrt(distX + distY + distZ)
if (distance < SAFETY_MARGIN)
PrintWarning(Flights[j],Flights[k])
Flights[j].numWarnings++
Flights[k].numWarnings++
end loop[k]
end loop[j]
end function AirplanePositions
La Actualización de
variables compartidas
debe protegerse
42
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Posicionamiento de Aviones
¿Cómo deben planificarse las tareas?
loop [j = 0, N]
loop [k = j+1, N]
if (NOT j.Landed OR NOT k.Landed) then
distX = (Flights[j].Xcoord – Flights[k].Xcoord) ^ 2
distY = (Flights[j].Ycoord – Flights[k].Ycoord) ^ 2
distZ = (Flights[j].Zcoord – Flights[k].Zcoord) ^ 2
distance = sqrt(distX + distY + distZ)
if (distance < SAFETY_MARGIN)
LogWarning(Flights[j],Flights[k])
Flights[j].numWarnings++
Flights[k].numWarnings++
end loop[k]
end loop[j]
Planificación Estática
Planificación Dinámica
Divide hasta N aviones y asígnalos Establecer contador global (0..Na hilos
1)
• Asignar N/(# de hilos) aviones a Los hilos acceden el contador para
un hilo
el siguiente[j], incrementa el
contador
• Asignar cada n-ésimo avión a
cada hilo, iniciar con id del hilo
• Deben proteger el acceso e
incrementar el contador global
43
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Dinámica Molecular
¿Qué son las tareas dentro del pseudocódigo?
¿Hay dependencias? ¿Cómo pueden resolverse?
¿Cómo deben planificarse las tareas para ejecutarse en hilos?
44
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Código de la Dinámica
Molecular
Colecciones de átomos calculan fuerzas entre pares de átomos
Solo pares de átomos que están con un radio igual a un límite
preestablecido
• La lista de vecinos para cada átomo determina que otros átomos
están dentro del radio
• Tercera ley de Newton: La fuerza del Atom[i] en el Atom[j] es el
negativo del Atom[j] en el Atom[i]
• Si el Atom[j] está en la lista de vecinos del Atom[i], entonces el
Atom[i] no estará en la lista para el Atom[j]
Pseudo-código en la siguiente diapositiva
• No se requieren cálculos físicos para este ejercicio
• No se muestran como los vecinos hacen sus actualizaciones
45
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Código de la Dinámica
Molecular
function non_bonded_forces_all (N, Atoms, neighbors, Forces)
Int const N
//number of atoms
Array of Real :: atoms(3,N)
// 3D coordinates
Array of Real :: Forces(3,N)
// force in each dimension
Array of List :: neighbors(N)
// atoms in cutoff volume
Real :: forceX, forceY, forceZ
loop [i] over atoms
loop [j] over neighbors(i)
forceX = non_bonded_force_pair(atoms(1,i), atoms(1,j))
forceY = non_bonded_force_pair(atoms(2,i), atoms(2,j))
forceZ = non_bonded_force_pair(atoms(3,i), atoms(3,j))
Forces(1,i) += forceX;
Forces(1,j) -= forceX;
Forces(2,i) += forceY;
Forces(2,j) -= forceY;
Forces(3,i) += forceZ;
Forces(3,j) -= forceZ;
end loop[j]
end loop[i]
end function non_bonded_forces_all
46
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Agenda
Patrón de estructura de lenguaje
El patrón de paralelismo de tareas
El patrón de descomposición geométrica
Estructuras de Soporte
Resumen
47
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Estructuras de Algoritmos del Espacio de
Diseño
¿Cómo está estructurado el cómputo?
Organizado por datos
¿Lineal?
Descomposición
Geométrica
48
¿Recursivo?
Datos
Recursivos
Organizado por tareas
¿Lineal?
Paralelismo
de tareas
¿Recursivo?
Divide y
Vencerás
Organizado por flujo
de datos
¿Regular?
Pipeline
¿Irregular?
Coordinación
basada en
eventos
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Descomposición Geométrica
Problema:
• ¿Como un algoritmo paralelo puede estar organizado
alrededor de una estructura de datos que puede
descomponerse en “fragmentos” independientes y
concurrentemente actualizables?
49
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Descomposición Geométrica
Ejemplos:
• Predicción del clima – Divide el área de interés en
secciones discretas, no sobrepuestas; calcula los efectos del
viento, tierra, sol, humedad, clima en secciones vecinas, etc.
Iterativamente
• Fractales de Newton-Raphson – Para cada punto dentro
de un plano complejo, calcula el número de iteraciones
requeridas para alcanzar la raíz del polinomial; punto de color
apropiadamente
50
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Contexto del Patrón de Descomposición
Geométrica
Muchos problemas pueden entenderse mejor como una
secuencia de operaciones en el núcleo de una estructura de
datos
• Todos los elementos de la estructura se actualizan o se usan
para cómputo
51
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Contexto del Patrón de Descomposición
Geométrica
La estructura se divide en sub-estructuras contiguas o subregiones
• Arreglos: divide entre una o más dimensiones
• Listas: define sublistas de elementos discretos
• Grafos y Árboles: construye sub-grafos o sub-árboles
52
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Contexto del Patrón de Descomposición
Geométrica
Usaremos el término genérico fragmento para referir una subregión
La descomposición de datos en fragmentos implica una división
del cómputo en tareas para operar en elementos de cada
fragmento
• Las tareas se ejecutarán concurrentemente
• Cada tarea actualizará el fragmento asociado
• Las tareas pueden requerir datos de fragmentos vecinos que
deben ser compartidos
• Los fragmentos vecinos contienen datos que estaban “cerca” en la
estructura de datos original
53
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Propuestas del Patrón de Descomposición
Geométrica
Metas: simplicidad, portabilidad, escalabilidad, y eficiencia
Fragmentos de datos deben asignarse a hilos
• El balanceo de carga puede ser un factor, especialmente
cuando se usan fragmentos de tamaño variable
• El cómputo asociado debe ser ejecutado por el hilo
Asegurarse que los datos necesarios para actualizar los
fragmentos están disponibles cuando se requieren
• Los datos desde dentro de un fragmento son de fácil acceso
• Acceder datos esenciales de fragmentos vecinos pueden
requerir coordinación entre hilos
54
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrones de Soluciones de Descomposición
Geométrica
Deben considerarse las siguientes actividades clave:
• Descomposición de datos
• Particionar la estructura de datos global en fragmentos
• Considera granularidad y la forma de los fragmentos
• Operación de intercambio
• Asegurarse que cada tarea tenga acceso a todos los datos
necesarios para la actualización
• ¿Se requiere tener disponibles datos “externos”?
• Operación de actualización (cómputo)
• Actualizando los elementos dentro del fragmento
• Normalmente la mayor parte del cómputo
• Distribución de datos y planificación de tareas
• Como mapear fragmentos y asociar cómputo a hilos
55
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
1. Descomposición de Datos - Granularidad
La granularidad de la descomposición de los datos tendrá un
impacto significativo en el rendimiento y eficiencia de la
aplicación
• Descomposición Grano-grueso
• Menos fragmentos pero más grandes
• Requiere menor cantidad de datos compartidos
(sincronización/comunicación)
• Descomposición Grano-fino
• Más fragmentos pero más pequeños
• Puede haber (mucho) más fragmentos que hilos; más fácil para el
balanceo de carga
• Mayor cantidad de datos compartidos y sincronización
56
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
1. Descomposición de Datos - Granularidad
La granularidad óptima puede ser difícil de obtener
matemáticamente al principio de la computación
• Experimentos para encontrar el mejor tamaño en la
descomposición
• Si las cargas de trabajos varían entre ejecuciones, el tamaño
de la descomposición puede ser parametrizable dentro de la
aplicación
• Bueno para escalabilidad de la aplicación
57
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
1. Descomposición de Datos – Forma
(Arreglo)
La forma de los fragmentos puede afectar la cantidad de
comunicación y sincronización requerida
• Los datos a compartir usualmente son valores de frontera de
los fragmentos
• Datos compartidos escalan de la superficie de los fragmentos
• La computación escala con el volumen de los fragmentos
(número de elementos de datos en un fragmento)
16 celdas, 8 compartidas
16 celdas, 4 compartidas
58
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
1. Descomposición de Datos – Forma
(Arreglo)
16 celdas, 8 compartidas
16 celdas, 4 compartidas
Tamaño y forma de los fragmentos pueden ser afectados por
otros factores
• Tamaño línea caché, renglón-mayor o columna-mayor, código
fuente antes/después
59
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
1. Descomposición de Datos – Forma
(Gráfico)
La superficie del subgrafo puede dividirse a lo ancho para
dividirse en subgrafos
• Asume que los datos deben compartirse a través de las
Nodos
aristas
Vecinos
6
9
6
12
6
11
6
8
La mejor división de nodos a hilos para minimizar vecinos
asignados a hilos diferentes
60
Nodos
Vecinos
6
3
6
6
6
7
6
4
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Misión de descomposición
Describe esquemas de descomposición para los siguientes
conjuntos de datos:
• Red de cuadros representando la masa de tierra y costa de
Australia
• Catálogo de libros en una librería
• Gráfica que representa un mapa de 3000 ciudades en México
(nodos) y carreteras entre ellos (aristas)
61
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
2. Operación de Intercambio
Factor clave en un patrón correcto de Descomposición
Geométrica
• Asegurar que el intercambio de datos entre segmentos
vecinos sea eficiente
• ¿Copiar datos a estructuras de datos locales o accederlos
conforme se necesiten?
62
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
2. Operación de Intercambio
Copiar datos a una estructura de datos local
• Si hay datos disponibles antes de una operación de
actualización y no cambiará durante la copia
• Requiere memoria extra por hilo, pero no bloqueos en las
copias
Acceder los datos conforme se requieren
• Obtiene ventaja de la memoria compartida entre hilos
• Retrasos en la coordinación entre hilos mientras los datos son
necesitados
Debe haber coordinación entre hilos para
asegurarse que los datos están disponibles y no
cambiarán durante el intercambio
63
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
3. Operación de Actualización
Ejecución de las tareas asociadas actualizará concurrentemente
la estructura de datos
64
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
3. Operación de Actualización
Consideraciones de la codificación para la interacción de
intercambio y actualización
• Si todos los datos están disponibles al inicio de las tareas y no
cambiarán durante el cómputo, la paralelización será más fácil y
probablemente eficiente
• Si se van a copiar datos no locales de otros fragmentos antes de
operaciones de cómputo de actualización, añade una fase de
recopilación de datos antes de comenzar la actualización
• Si no se van a acceder datos no locales a través de operaciones de
actualización, agrega código para asegurarse que se encuentran los
datos correctos y garantizar que se observa un protocolo de acceso
adecuado (exclusión mutua)
• Mezclar operaciones de intercambio y actualización pueden
complicar la lógica de la aplicación, especialmente para asegurar
que se obtienen datos correctos
65
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
4. Distribución de Datos y Planificación de
Tareas
Determina que hilos actualizarán que segmentos de datos
La distribución estática es lo más simple
• La coordinación para el intercambio será sencilla para
determinar e implementar
• Lo más apropiado cuando la cantidad de cómputo en las
tareas es uniforme
La distribución dinámica es útil para el balanceo de carga
• Requiere (muchas) más tareas que hilos
• La operación de intercambio será más compleja
• Debe asegurarse que las actualizaciones de datos no-locales se
ha completado
66
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
4. Distribución de Datos y Planificación de
Tareas
¿Qué hay acerca de redistribución dinámica de la distribución
estática inicial?
• Si la cantidad de trabajo por hilo cambia sobre el curso del
cómputo
• Ejemplo: operación de matriz que elimina renglones/columnas
• Aplicación que puede reconfigurar la distribución de
tareas/datos para la carga de trabajo
• La Ganancia en el rendimiento debe superar la sobrecarga
añadida por la re-distribución
67
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Multiplicación de
Matrices
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
C[i][j] = 0.0;
B
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
for (k = 0; k < L; k++)
C[i][j] += A[i][k] * B[k][j];
¿Qué se puede calcular de manera
independiente?
• Elementos individuales de C
• Renglones de C (usando todo de B)
A
C
• Columnas de C (usando todo de A)
• Bloques de C
68
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Multiplicación de
Matrices
¿Qué estructura de datos grande necesita ser actualizada?
¿Cómo debe descomponerse la estructura de datos? ¿Qué
granularidad será la mejor?
¿Qué datos necesitan compartirse entre tareas asociadas con
los fragmentos de datos? ¿Hay datos no locales que requieren
intercambiarse?
¿Cómo debemos asignar los fragmentos a los hilos? ¿Estático o
Dinámico?
69
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Multiplicación de
Matrices con Posibles Respuestas
¿Qué estructura de datos grande necesita ser actualizada?
• La matriz C
¿Cómo debe descomponerse la estructura de datos? ¿Qué
granularidad será la mejor?
• Elementos individuales parece que sería grano demasiado fino
• Grupos de renglones entran en renglones más accesados y es
grano grueso
• Los bloques pueden usarse enfocándose en el tamaño y
utilización del caché
70
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Multiplicación de
Matrices con Posibles Respuestas
¿Qué datos necesitan compartirse entre tareas asociadas con
los segmentos de datos? ¿Hay datos no locales que requieren
intercambiarse?
• Elementos de los arreglos A y B son compartidos (pero no
actualizados)
• Si estos caben en la memoria, pueden compartirse sin
intercambiarse
¿Cómo debemos asignar los segmentos a los hilos? ¿Estático o
Dinámico?
• Como no se requiere intercambio de datos, la distribución estática
es la más simple
71
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Multiplicación de
Matrices
Modifica los límite del ciclo “i”, basado en
un identificador de hilo único, asignando
grupos de renglones a hilos individuales
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
C[i][j] = 0.0;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
for (k = 0; k < L; k++)
C[i][j] += A[i][k] * B[k][j];
Cada hilo requerirá copias locales de
todas las variables índices de los ciclos
72
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Juego de la vida
¿Cuál es la mayor cantidad de datos que pueden actualizarse
concurrentemente?
¿Cómo deben descomponerse estos datos?
¿Cómo deben planificarse los datos y tareas para ejecutarse en hilos?
¿Qué consideraciones se necesitan tomar en cuenta para la carga de
trabajo?
73
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Agenda
Patrón de estructura de lenguaje
El patrón de paralelismo de tareas
El patrón de descomposición geométrica
Estructuras de Soporte
• SPMD
• Paralelismo de Ciclos
• Maestro/Esclavo
Resumen
74
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Estructuras de Soporte, Espacio de Diseño
Bloques de construcción de alto nivel usados para organizar el
código fuente
Categorizados en estructuras de programa y estructura de
datos
Estructuras del
Programa
SPMD
Estructuras de Datos
Datos compartidos
Paralelismo de ciclos
Maestro esclavo
Fork/join
Cola compartida
Arreglo distribuido
Fork/join
75
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón SPMD
Problema
• ¿Cómo estructuramos un programa paralelo para hacer
iteraciones entre hilos que sean fácilmente manejables para
integrarlos con los núcleos de computación?
Contexto
• Las iteraciones entre hilos deben estar bien orquestadas para
lograr soluciones correctas y eficientes
• Muchos algoritmos paralelos tienen operaciones similares
llevadas a cabo por cada hilo, pero puede haber algunos
cuantos requerimientos ligeramente diferentes para un
conjunto de hilos o datos
• Solo los algoritmos más complejos necesitan instrucciones y
flujos de datos muy diferentes en cada hilo
76
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón SPMD
Propuesta
• Sería más fácil balancear las necesidades conflictivas de
escalabilidad y de mantenimiento dentro de una solo código
fuente en vez de que sea a través de varios archivos fuentes
77
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón SPMD – Solución
Una sola aplicación creará hilos para ejecutar código y
funciones dentro del código fuente
• Dada la naturaleza de la programación multihilos, el patrón
SPMD es el default
78
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón SPMD – Solución
Codificando Elementos para implementar el patrón SPMD
• Obtener un identificador único
• Asignar un ID para cada hilos, usualmente de 0..N-1
• Usa el ID para diferenciar comportamiento entre hilos
diferentes
• Las instrucciones de saltos pueden usarse para asignar bloques
de código
• Usar el ID en los cálculos del índice del ciclo para dividir
iteraciones entre los hilos
79
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón SPMD – Solución
• Distribuye datos
• Decompone datos globales en fragmentos y accede los
fragmentos basándote en el ID
• Finaliza
• Si datos globalmente relevantes fueron distribuidos entre hilos, se
requieren recombinar los resultados parciales
80
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón SPMD – Discusión
Los programas SPMD están mas cercanamente alineados con
ambientes distribuidos de paso de mensajes
Un solo programa que crea hilos es el default para la
programación multihilos
• Los hilos dentro del mismo proceso comparten código y datos
• Más relevante con modelos de hilos generales que OpenMP
81
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos
Problema
• ¿Como estructurar un programa paralelo de un programa
serial donde un conjunto de ciclos computacionalmente
intensivos dominan el tiempo de ejecución?
82
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos
Contexto
• Un gran número de aplicaciones científicas y técnicas hacen uso de
construcciones iterativas (basadas en ciclos)
• La meta es “hacer evolucionar” código secuencial en código paralelo
transformando ciclos para ejecutar iteraciones separadas en hilos
• Las iteraciones de ciclos deben funcionar bien como tareas
paralelas
• Computacionalmente intensivas
• Expresar suficiente concurrencia
• La mayoría independientes
• Quitar las dependencias entre ciclos si están presentes
Este patrón es particularmente relevante para usar OpenMP,
Intel TBB
83
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos
Equivalencia Secuencial
• Programa que arroja resultados idénticos con uno o muchos
hilos
• Errores de variaciones de redondeo pueden ser aceptables
• Código secuencialmente equivalente es más fácil de escribir y
mantener
Paralelismo Incremental
• Es más fácil mantener la correctud si las transformaciones del
ciclo pueden hacerse y probarse una a la vez
• Puede ser difícil con modelos generales de hilos y distribución
de datos a segmentos locales (se necesita transformación de
“todo el código”)
84
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos
Utilización de Memoria
• Patrones de acceso de datos deben caber bien con las
jerarquías de memoria
• Dividir las iteraciones para los hilos puede arruinar los
patrones de acceso secuencial
• Puede ser necesario re-estructurar los para un mejor acceso
85
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos - Solución
Un estilo de programación alineado con OpenMP, Intel TBB
• Modelos generales de paralelismo pueden usarse con
asignaciones de iteraciones de ciclos provistas por el
programador
86
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos - Solución
Codificando elementos para implementar el patrón de
paralelismo de ciclos
• Emcontrar hotspots
• Identifica los ciclos computacionalmente más intensivos
inspeccionando el código, entendiendo el algoritmo, o usa un
programa para el análisis
• Eliminar dependencias de los ciclos
• Encuentra dependencias entre iteraciones o conflictos de datos
• Remueve dependencias o protege daos con sincronización
• Paraleliza los ciclos
• Divide las iteraciones entre hilos
• Optimiza la planificación de ciclos
• Planifica iteraciones de ciclos para asegurar el balanceo de carga
87
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos Consideraciones
El tiempo de cómputo dentro de las iteraciones debe ser
suficiente para superar la sobrecarga de crear hilos y asignarles
trabajo
• Solución: Mezclar hilos
• Dada una secuencia de ciclos con rangos de índices consistentes,
mezclar esos ciclos en un solo ciclo incrementará el trabajo por
iteración del ciclo resultante
88
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Patrón de Paralelismo de Ciclos Consideraciones
El número más grande de iteraciones disponibles, habrá mayor
flexibilidad para decisiones de planificación
• Solución: Unir ciclos anidados
• Combinar ciclos anidados puede llevarnos a un solo ciclo con un
contador grande de iteraciones
• Contadores de iteraciones grandes pueden también permitir
mejores oportunidades de superar la sobrecarga
89
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Ejemplo de unir hilos
Un número primo de iteraciones
nunca permitirá un balanceo de
carga perfecto
#define N 23
#define M 1000
. . .
¿Paraleliza el ciclo interno? ¿Hay
for (k = 0; k < N; k++)
suficientes iteraciones para
for (j = 0; j < M; j++)
superar la sobrecarga de la
w_new[k][j] = DoSomeWork(w[k][j], k, j);
gestión de los hilos?
Un número grande de
iteraciones da más
oportunidad de
balancear la carga y
eliminar la sobrecarga
#define N 23
#define M 1000
. . .
for (kj = 0; kj < N*M; kj++) {
k = kj / M;
j = kj % M;
w_new[k][j] = DoSomeWork(w[k][j], k, j);
DIV y MOD con el valor límite del
}
ciclo interno
Estos cálculos son sobrecarga
90
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dividendo Iteraciones de un Ciclo - OpenMP
#define N 23
#define M 1000
. . .
#pragma omp for private(k,j) schedule(static, 500)
for (kj = 0; kj < N*M; kj++) {
k = kj / M;
j = kj % M;
w_new[k][j] = DoSomeWork(w[k][j], k, j);
}
Añade pragma de OpenMP para dividir las iteraciones entre
hilos
• Añade cláusulas de ambiente de datos y planificación como
sea necesario
91
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dividendo Iteraciones un Ciclo – Divide en
Segmentos
#define N 23
#define M 1000
#define numThreads 4
. . .
Estas deben ser
privadas para cada
hilo
int start = ((N*M)/numThreads) * myID;
int end
= ((N*M)/numThreads) * (myID+1);
. . .
if (myID == (numThreads-1))
end = N*M;
. . .
for (kj = start; kj < end; kj++) {
k = kj / M; j = kj % M;
w_new[k][j] = DoSomeWork(w[k][j], k, j);
}
Asegúrate que
todas las
iteraciones se
incluyen
Calculo punto inicial (start) y final (end) para las iteraciones de
los ciclos basada en el número de hilos y número identificador
del hilo
92
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dividendo Iteraciones del Ciclo – Balanceo
de carga
23 * 5323 = 122,429 iteraciones
#define N 23
#define M 5323
#define numThreads 16
ID del hilo
Iteraciones
Asignadas
13
0
7651
iteraciones
1extras!
7651
122,429 / 16 = 7651.8125
int start = ((N*M)/numThreads) * myID;
int end
= ((N*M)/numThreads) * (myID+1);
. . .
. . .
if (myID
(numThreads-1))
end = N*M;
ID
(float)==
start
(float) end
Iteraciones
#define N 23
Asignadas
. . .
...
...
14
7651
15
7664
#define M 5323
0
0.000 kj7651.813
7651
for
(kj = start;
end; kj++)
#define <numThreads
16{ .
1
7651.813
15303.625
7652
. . .
2
. .
}
15303.625
22955.438
7652
int start
= (int)((float)(N*M)/numThreads)
* myID;
(float)
. . . int end . . .= (int)((float)(N*M)/numThreads)
...
* (myID+1);
(float)
...
. . .
5
38259.063
...
...
45910.875
7651
if (myID
== (numThreads-1))
...
. . .
14
107125.375
15
114777.188
...
end = N*M;
114777.188
for (kj
= start; kj7652
< end; kj++) {
93
122429.000
7652
. . .
}
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Dividendo Iteraciones del Ciclo – Turno Rotatorio
#define N 23
#define M 1000
#define numThreads 4
Cada hilo hace cada
iteración (numThreads)th
. . .
for (kj = myID; kj < N*M; kj+=numThreads) {
k = kj / M;
j = kj % M;
w_new[k][j] = DoSomeWork(w[k][j], k, j);
}
Rango de valores de myID es [0..numThreads-1]
Buen balanceo de cargaen el número de iteraciones
• Entre ±1 entre cualquiera de los hilos
• Fácilmente codificado, no se pueden perder iteraciones
Ten cuidado de problemas potenciales de acceso a
memoria y caché
94
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Paralelismo de Ciclos
¿Qué tipo de asignación se utilizaría en los siguientes cálculos
para dividir las iteraciones entre los hilos?
Computar el siguiente cuadro de una película animada por
computadora
• Ciclo sobre renglones
• Ciclo sobre pixeles en un renglón (columnas)
• Calcula pixel
95
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Paralelismo de Ciclos
Buscar a través del catálogo de una librería para encontrar
cuántos libros tienen la palabra “loop” en el título
•
•
•
•
Un ciclo sobre las letras del alfabeto
Un ciclo sobre los autores con la primera letra en el nombre
Un ciclo sobre los libros por autor
Incrementar el contador global si el titulo tiene “loop
96
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
El Patrón Maestro/Esclavo
Problema
• ¿Como debe un programa estar organizado cuando el diseño
es dominado por la necesidad de un balancear dinámicamente
el trabajo en un conjunto de tareas?
Contexto
• Balancear la cargas de las tarea también domina la porción
serial y causa sobrecarga
• Las cargas de trabajo de las tareas es variable e impredecible
• Porciones de código computacionalmente intensivas no mapean a
ciclos simples
• Capacidad de núcleos en el sistema varían, cambian, impredecible
• Particularmente relevante para el patrón de Paralelismo de
Tareas
97
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
El Patrón Maestro/Esclavo
Forces
• Trabajo impredecible por tarea requiere una lógica de
asignación dinámica
• Operaciones de balanceo de carga crean sobrecarga en la
sincronización
• Menos tareas y más largas pueden reducir esto, pero restringen
opciones
• Mantener el equilibrio entre balanceo de carga y mantener el
código
98
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
El Patrón Maestro/Esclavo - Solución
Hilo Maestro
• Inicia el cómputo
• Controla la distribución de tareas a ser asignada a los hilos
esclavos
Hilos Esclavos
• Están en un ciclo mientras haya más tareas por hacerse
• Aceptan tareas del hilo maestro
• Ejecutan cada tarea asignada
Consideraciones en la Programación
• Distribución de tareas
• Detectar terminación y disposición de los esclavos
99
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
El Patrón Maestro/Esclavo Detectando
Terminación
Rendezvous
• Enviar una señal de terminación a cada esclavo
• Hasta que se recibe una tarea, los esclavos checan si hay
nuevo trabajo o la terminación de la tarea
100
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
El Patrón Maestro/Esclavo Detectando
Terminación
Bolsa de tareas
• Si todas las tareas están inicialmente cargadas en una bolsa,
una bolsa vacía significa que el cómputo se completó
• Añadir la terminación de tareas en la cola de tareas, después
de todo el cálculo
• Por simplicidad, añade una tarea de terminación por hilo esclavo
Shared Monotonic Counter
• Counter greater than number of known tasks signals
completion
101
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Implementación
Rendezvous en el Código Maestro
LockSyncObject(BWlock);// sincroniza acceso al contador num_waiting
num_waiting++;
if (num_waiting !=2) {
// si no hay esclavo esperando...
UnlockSyncObject(BWLock);
SleepUntilWorkerArrives(); // ...espera
}
else {
WakeUpSleepingWorkerThread(); // despierta al esclavo
num_waiting = 0;
// resetea para el siguiente rendezvous
UnlockSyncObject(BWLock);
}
<TRANSFIERE DATOS, ASIGNA UNA TAREA NUEVA O ENVÍA TERMINACIÓN>
102
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
CASO DE ESTUDIO: Implementación
Rendezvous, Código del Hilo Esclavo
LockSyncObject(WorkerLock);//asegura la exclusion de otros esclavos
LockSyncObject(BWlock);//sincroniza acceso al contador num_waiting
num_waiting++;
if (num_waiting !=2) {
// si el maestro no está esperando...
UnlockSyncObject(BWLock);
SleepUntilBossArrives(); // ...espera
}
else {
WakeUpSleepingBossThread();
// despierta al maestro
num_waiting = 0;
// resetea para el siguiente rendezvous
UnlockSyncObject(BWLock);
}
<TRANSFIERE DATOS, ASIGNA UNA TAREA NUEVA O ENVÍA TERMINACIÓN>
UnlockSyncObject(WorkerLock);//permite el siguiente esclavo a
rendezvous
103
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVITY: Boss/Worker
What type of task distribution method would be used on the
following computations to divide iterations among threads?
Compute Mandlebrot set
• Loop over rows
•
Loop over pixels in a row (columns)
•
Compute pixel
104
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
ACTIVIDAD: Maestro/Esclavo
Search through library catalog to find how many books have
“loop” in the title
• Loop over letters of alphabet
• Loop over authors with first letter in name
•
Loop over books by author
•
Increment global counter if title has “loop”
105
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.
Intel® Software College
Agenda
Patrón de estructura de lenguaje
El patrón de paralelismo de tareas
El patrón de descomposición geométrica
Estructuras de Soporte
Resumen
106
13/04/2015
Copyright © 2006, Intel Corporation. All rights reserved.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.